package com.jfinal.club._front;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.club.common.controller.BaseController;
import com.jfinal.club.common.model.*;
import com.jfinal.club.util.*;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.upload.UploadFile;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Auther: LiuChao
 * @Date: 2021/2/26 19:11
 * @Description:
 */
public class IndexController extends BaseController {


    public void index(){
        render("index.html");
    }

    @Clear
    public void wxAuth( ) throws UnsupportedEncodingException {
        String code = get("code");
        String url = get("url");
        if (code != null) {
            //通过code来换取access_token
            JSONObject json = WeChatUtil.getWebAccessToken(code);
            //获取用户openid
            String openid = json.getString("openid");
            JSONObject userInfo = WeChatUtil.getUserInfo(json.getString("access_token"), openid);

            //设置到会话中
            setSessionAttr("openid", openid);
            setSessionAttr("nickname", userInfo.getString("nickname"));
            setSessionAttr("headimg", userInfo.getString("headimgurl"));
            //重定向到主页
            if (StringUtils.isBlank(url)) {
                render("index.html");
            } else {

                Users users = Users.dao.findFirst("select * from users where openid = ? ", openid);
                if(users != null){
                    setCookie(Cons.USERID, users.getId()+"", PropKit.getInt("cookie"), Cons.ContextPath+"/", null, true);

                }
                redirect(url);
            }
        } else {
            //重定向到授权页面
            redirect(WeChatUtil.WEB_REDIRECT_URL.replace("APPID", WeChatUtil.APPID).replace("REDIRECT_URI", URLEncoder.encode(PropKit.get("host") + "/wxAuth?url=" + url, "utf-8")));
        }

    }

    /**
     * 样品申请
     */
    @Before(FrontSessionInterface.class)
    public void apply(){
        String company = get("company", "");
        String name = get("name", "");
        String phone = get("phone", "");
        String email = get("email", "");
        String proId = get("proId", "");
        set("remark",get("remark",""));
        String uid = getCookie(Cons.USERID);
        Users users = Users.dao.findFirst("select * from users where id = ? ", uid);
        if(users == null){
            redirect(PropKit.get("host") + "/register");
            return;
        }

        Sample sample = Sample.dao.findFirst("select * from sample where user_id = ? and is_submit = 0", users.getId());

        if(sample == null){
            Sample s = new Sample();
            s.setUserId(users.getId());
            s.setCompany(company);
            s.setName(name);
            s.setMobile(phone);
            s.setEmail(email);
            s.setProductIds(proId);
            s.setCreateTime(new Date());
            s.setIsSubmit(0);
            s.save();
        }else{
            if(StringUtils.isNotBlank(company)){
                sample.setCompany(company);
            }
            if(StringUtils.isNotBlank(name)){
                sample.setName(name);
            }
            if(StringUtils.isNotBlank(phone)){
                sample.setMobile(phone);
            }
            if(StringUtils.isNotBlank(email)){
                sample.setEmail(email);
            }
            if(StringUtils.isNotBlank(sample.getProductIds())){
                String[] split = sample.getProductIds().split(",");

                int exits = 0;
                for (String s : split) {
                    if(s.equals(proId)){
                        exits = 1;
                    }
                }

                if(exits == 0 && StringUtils.isNotBlank(proId)){
                    sample.setProductIds(sample.getProductIds()+","+proId);
                }
            }else{
                sample.setProductIds(proId);
            }
            sample.update();

        }
        if(sample != null && StringUtils.isNotBlank(sample.getProductIds())){
            List<Product> productList = Product.dao.find("select * from product where id in (" + sample.getProductIds() + ") ");
            set("productList",productList);
        }



        set("sample",sample);
        set("users",users);
        render("apply.html");
    }


    /**
     * 样品申请
     */
    @Before(FrontSessionInterface.class)
    public void applyAjax(){
        String company = get("company", "");
        String name = get("name", "");
        String phone = get("phone", "");
        String email = get("email", "");
        String proId = get("proId", "");
        String uid = getCookie(Cons.USERID);
        Users users = Users.dao.findFirst("select * from users where id = ? ", uid);
        if(users == null){
            redirect(PropKit.get("host") + "/register");
            return;
        }



        Sample sample = Sample.dao.findFirst("select * from sample where user_id = ? and is_submit = 0", users.getId());

        if(sample == null){
            Sample s = new Sample();
            s.setUserId(users.getId());
            s.setCompany(company);
            s.setName(name);
            s.setMobile(phone);
            s.setEmail(email);
            s.setProductIds(proId);
            s.setCreateTime(new Date());
            s.setIsSubmit(0);
            s.save();
        }else{
            sample.setCompany(company);
            sample.setName(name);
            sample.setMobile(phone);
            sample.setEmail(email);
            if(StringUtils.isNotBlank(sample.getProductIds())){
                String[] split = sample.getProductIds().split(",");

                int exits = 0;
                for (String s : split) {
                    if(s.equals(proId)){
                        exits = 1;
                    }
                }

                if(exits == 0 && StringUtils.isNotBlank(proId)){
                    sample.setProductIds(sample.getProductIds()+","+proId);
                }
            }else{
                sample.setProductIds(proId);
            }
            sample.update();

        }
        if(sample != null && StringUtils.isNotBlank(sample.getProductIds())){
            List<Product> productList = Product.dao.find("select * from product where id in (" + sample.getProductIds() + ") ");
            set("productList",productList);
        }



        renderJson(Ret.ok());
    }

    /**
     * 申请提交
     */
    public void applySave(){
        Integer id = getInt("id", 0);
        String company = get("company", "");
        String name = get("name", "");
        String phone = get("phone", "");
        String email = get("email", "");
        String remark = get("remark", "");
        String productIds = get("productIds", "");

        String products = "";
        if(StringUtils.isNotBlank(productIds)){
            List<Product> productList = Product.dao.find("select * from product where id in ( " + productIds + " )");
            for (Product product : productList) {
                products += product.getTitle()+"；";
            }
        }

        Sample sample = Sample.dao.findById(id);
        sample.setIsSubmit(1);
        sample.setCompany(company);
        sample.setName(name);
        sample.setMobile(phone);
        sample.setEmail(email);
        sample.setRemark(remark);
        sample.setProductIds(productIds);
        sample.setProducts(products);
        sample.update();

        try {
            String str = "您有样品申请已提交,请注意查收";
            AliyunMail.sendMail(PropKit.get("fromEmail"), PropKit.get("emailPass"), AliyunMail.ALIDM_SMTP_HOST, AliyunMail.ALIDM_SMTP_PORT, "样品申请提交",
                    str, PropKit.get("fixEmail"), null, null);
        } catch (Exception e) {
            e.printStackTrace();
        }

        renderJson(Ret.ok());
    }

    public void applyRemove(){
        Integer id = getInt("id", 0);
        String company = get("company", "");
        String name = get("name", "");
        String phone = get("phone", "");
        String email = get("email", "");
        String productIds = get("productIds", "");
        Sample sample = Sample.dao.findById(id);
        sample.setCompany(company);
        sample.setName(name);
        sample.setMobile(phone);
        sample.setEmail(email);
        sample.setProductIds(productIds);
        sample.update();
        renderJson(Ret.ok());
    }

    /**
     * 用户注册
     */
    public void register(){
        String uid = getCookie(Cons.USERID);
        Users users = Users.dao.findFirst("select * from users where id = ? ", uid);
        if(users != null){
            set("users",users);
            render("center.html");
        }else{
            render("register.html");
        }
    }

    /**
     * 发送短信
     */
    public void sendPhone(){
        try {
            String phone = get("phone", "");
            Code code = Code.dao.findFirst("select * from code where phone = ?", phone);
            String sendCode = CommonUtil.getRandom(4);
            if(code != null){
                code.setSendTime(new Date());
                code.setCode(sendCode);
                code.update();
            }else{

                Code c = new Code();
                c.setPhone(phone.trim());
                c.setCode(sendCode);
                c.setSendTime(new Date());
                c.save();
            }

            String paramstring = "{\"code\":\"" + sendCode + "\"}";
            String templatecode = "SMS_177547615";
            String msg = HttpSender.sendSms("海名斯个人护理品", templatecode, phone, paramstring);

            if(Objects.equals("OK",msg)){
                renderJson(Ret.ok());
            }else{
                renderJson(Ret.fail().set("msg",msg));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 短信验证 登录
     */
    public void verifyPhone(){
        String phone = get("phone", "");
        String code = get("code", "");

        Code first = Code.dao.findFirst("select * from code where phone = ? and code = ? ", phone, code);

        if(first == null){
            renderJson(Ret.fail().set("msg","手机号或验证码输入有误~"));
            return;
        }

        if(System.currentTimeMillis() - first.getSendTime().getTime() > 300000){
            renderJson(Ret.fail().set("msg","验证码已失效,请重新发送~"));
            return;
        }


        Users users = Users.dao.findFirst("select * from users where mobile = ? ", phone);

        int uid = 0;
        String openid = getSessionAttr("openid");
        String nickname = getSessionAttr("nickname");
        String headimg = getSessionAttr("headimg");
        if(users == null){
            Users u = new Users();
            u.setMobile(phone);
            u.setCreateTime(new Date());
            u.setLoginTime(new Date());
            u.setOpenid(openid);
            u.setName(nickname);
            u.setAvatar(headimg);
            u.save();
            uid = u.getId();
        }else{
            users.setLoginTime(new Date());
            users.setOpenid(openid);
            users.setName(nickname);
            users.setAvatar(headimg);
            users.update();
            uid = users.getId();
        }

        setCookie(Cons.USERID, uid+"", PropKit.getInt("cookie"), Cons.ContextPath+"/", null, true);

        renderJson(Ret.ok());
    }


    @Before(FrontSessionInterface.class)
    public void next(){
        String uid = getCookie(Cons.USERID);
        Users users = Users.dao.findFirst("select * from users where id = ? ", uid);
        set("users",users);
        render("register_next.html");
    }

    @Before(FrontSessionInterface.class)
    public void userSave(){
        String uid = getCookie(Cons.USERID);
        Users users = Users.dao.findFirst("select * from users where id = ? ", uid);
        String name = get("name","");
        String company = get("company", "");
        String email = get("email", "");
        String phone = get("phone", "");

        users.setName(name);
        users.setCompany(company);
        users.setEmail(email);
        users.removeNullValueAttrs().update();
        String returnUrl = getCookie(Cons.RETURNURL);
        setCookie(Cons.RETURNURL, "/", PropKit.getInt("cookie"), Cons.ContextPath+"/", null, true);
        renderJson(Ret.ok().set("returnUrl",returnUrl));

    }

    @Before(FrontSessionInterface.class)
    public void userSaves(){

        UploadFile file = getFile("filepath", Cons.AVATAR);

        String uid = getCookie(Cons.USERID);
        Users users = Users.dao.findFirst("select * from users where id = ? ", uid);
        String name = get("name","");
        String company = get("company", "");
        String email = get("email", "");
        String phone = get("phone", "");

        users.setName(name);
        users.setCompany(company);
        users.setEmail(email);
        users.setMobile(phone);
        if(file != null){
            //添加新文件
            String filePath = CommonUtil.getFilePath(file, Cons.AVATAR);
            users.setAvatar(filePath);
        }
        users.removeNullValueAttrs().update();

        renderJson(Ret.ok());
    }

    public void center(){
        String uid = getCookie(Cons.USERID);
        Users users = Users.dao.findFirst("select * from users where id = ? ", uid);
        set("users",users);
        render("center.html");
    }


    public void levelTwo(){
        Integer pid = getInt("pid", 0);
        List<ProductType> productTypeList = ProductType.dao.find("select * from product_type  order by sort desc,create_time desc ");
        renderJson(Ret.ok().set("data",productTypeList));
    }

    public void levelThree(){
        Integer pid = getInt("pid", 0);
        Integer type = getInt("type", 0);
        List<Product> products = Product.dao.find("select * from product where pid = ? and FIND_IN_SET(?,types)", pid,type);
        renderJson(Ret.ok().set("data",products));
    }

    public void productList(){
        Integer pid = getInt("pid", 0);
        List<Product> products = Product.dao.find("select * from product where pid = ?", pid);
        renderJson(Ret.ok().set("data",products));
    }

    @Before(FrontSessionInterface.class)
    public void download(){
        Integer pid = getInt("pid");
        List<Files> filesList = Files.dao.find("select * from files where pid = ? order by sort desc,create_time desc", pid);
        set("filesList",filesList);
        render("download.html");
    }

    @Before(FrontSessionInterface.class)
    public void peifang_download(){
        Integer pid = getInt("pid");
        List<IdeasFiles> filesList = IdeasFiles.dao.find("select * from ideas_files where pid = ? order by sort desc,create_time desc", pid);
        set("filesList",filesList);
        render("peifang_download.html");
    }



    /**
     * 产品文件下载记录保存
     * 产品中的文件下载记录保存
     * 打开就作为下载记录一次
     */
    @Before(FrontSessionInterface.class)
    public void productDownloadRecordAdd(){
        Integer fid = getInt("fid", 0);
        DownloadRecord d = new DownloadRecord();

        d.setFid(fid);
        d.setUid(Integer.valueOf(getUserId()));
        d.setType(1);
        d.setCreateTime(new Date());
        d.save();

        renderJson(Ret.ok().set("msg","success"));
    }

    /**
     * 配方创意下载记录保存
     * 打开就作为下载记录一次
     */
    @Before(FrontSessionInterface.class)
    public void peifangDownloadRecordAdd(){
        Integer fid = getInt("fid", 0);
        DownloadRecord d = new DownloadRecord();
        d.setFid(fid);
        d.setUid(Integer.valueOf(getUserId()));
        d.setType(2);
        d.setCreateTime(new Date());
        d.save();
        renderJson(Ret.ok().set("msg","success"));
    }


}
