package cn.com.countrygarden.bi.main.service.experience.impl;

import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.dao.experience.WcxExperienceMapper;
import cn.com.countrygarden.bi.main.dto.message.SmsParamBO;
import cn.com.countrygarden.bi.main.model.experience.WcxEmployeesManage;
import cn.com.countrygarden.bi.main.service.experience.TygWxService;
import cn.com.countrygarden.bi.main.service.message.SmsTemplateSender;
import cn.com.countrygarden.bi.main.util.MD5;
import cn.com.countrygarden.bi.main.util.MySessionContext;
import cn.com.countrygarden.bi.main.util.RandomUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class TygWxServiceImpl implements TygWxService {
    @Autowired
    private WcxExperienceMapper wcxExperienceMapper;
    @Autowired
    private SmsTemplateSender smsTemplateSender;
    @Override
    public Result checkPhone(String phone) {
        Result resut=new Result();
        try{
            List<WcxEmployeesManage> wcxEmployeesManages = wcxExperienceMapper.selectByPhone(phone);
            // 有激活的数据则返回true，没有则返回false
            for(int i=0;i<wcxEmployeesManages.size();i++){
                WcxEmployeesManage wcxEmployeesManage = wcxEmployeesManages.get(i);
                String effective = wcxEmployeesManage.getEffective();
                if("1".equals(effective)){
                    resut.setResultCode(200);
                    resut.setResultMsg("成功");
                    break;
                }
                if("0".equals(effective)){
                    resut.setResultCode(10003);
                    resut.setResultMsg("账户未启用，请联系管理员");
                }
            }
            if(wcxEmployeesManages.size() ==0){
                resut.setResultCode(10004);
                resut.setResultMsg("账户不存在");
            }
            return resut;
        }catch(Exception e){
            e.printStackTrace();
            resut.setResultCode(500);
            resut.setResultMsg("系统异常，请稍后再试");
            return resut;
        }
    }

    @Override
    public Result sendMessage(String phone, HttpServletRequest req, HttpServletResponse res) {
        //校验手机号码是否合法
        Result result1 = checkPhone(phone);
        if(!"200".equals(result1.getResultCode()+"")){
            return result1;
        }
        Result result=new Result();
        String password = RandomUtil.randomNumbers(4);
        SmsParamBO bo = SmsParamBO.builder().phone(phone).templateParams(CollUtil.newArrayList(password)).build();
        try{
            smsTemplateSender.sendSms(bo);
        }catch(Exception e){
            e.printStackTrace();
            result.setResultCode(500);
            result.setResultMsg("短信发送失败，请稍后再试");
            return result;
        }
        HttpSession session = req.getSession();
//          //"使用tongyi"+phone做为唯一key值，修复两个手机号同时登使用短信验证登录时的错误问题
            session.setAttribute("tygwx", password);
            session.setMaxInactiveInterval(180);
            String id = session.getId();
            result.setResultCode(200);
            result.setData(id);
        return result;
    }

    @Override
    public Result code(String phone, HttpServletRequest req, String code, String userInfo, String sessionId) {
        Result result=new Result();
        if(code == null || code ==""){
            result.setResultCode(400);
            result.setResultMsg("验证码不能为空");
            return result;
        }
        if(phone == null || phone ==""){
            result.setResultCode(400);
            result.setResultMsg("手机号码不能为空");
            return result;
        }
        if(userInfo == null || userInfo ==""){
            result.setResultCode(400);
            result.setResultMsg("详细信息不能为空");
            return result;
        }
        if(sessionId ==null){
            result.setResultCode(400);
            result.setResultMsg("短信验证码标识不能为空");
            return result;
        }
        HttpSession session = MySessionContext.getSession(sessionId);
        if(session ==null){
            result.setResultCode(10014);
            result.setMessage("验证码错误");
            return result;
        }
        //HttpSession session = req.getSession();
        String attribute = (String)session.getAttribute("tygwx");
        if(!code.equals(attribute)){
            result.setResultCode(10014);
            result.setMessage("验证码错误");
            return result;
        }
        session.removeAttribute("tygwx");
        try{
            // {"city":"深圳","country":"中国","groupId":0,
            // "headImgUrl":"http://thirdwx.qlogo.cn/mmopen/hBDd7L7B1hZIXyBvjxP0QeygvEDhXOYAV1wP1yRGDwNkC5hKg4ap3qjKFPn4w51fEDDApnLINRKPxLaqq6PPMAyibW8yWic2fN/132","language":"zh_CN","nickname":"026旭","openId":"o3GBrs47OT29R0Kk_Bw9jPi6YeCE","province":"广东","qrScene":"0","qrSceneStr":"","remark":"","sex":1,"sexDesc":"男","subscribe":true,"subscribeScene":"ADD_SCENE_PROFILE_CARD","subscribeTime":1605770990,"tagIds":[]}
            JSONObject jsonObject = JSONObject.parseObject(userInfo);
            Object openid = jsonObject.get("openId");
            Object nickname = jsonObject.get("nickname");
            Object headimgurl = jsonObject.get("headImgUrl");
            Object subscribe = jsonObject.get("subscribe");
            if(openid ==null){
                result.setResultCode(400);
                result.setResultMsg("详细信息openId不存在");
                return result;
            }
            String s = genAccessToken(phone, openid.toString(), "wx");
            //绑定用户、可能为客户、也可能为员工
            Set<String> phoneSet = new HashSet<String>();
            List<WcxEmployeesManage> wcxEmployeesManages = wcxExperienceMapper.selectByPhone(phone);
            for(int i=0;i<wcxEmployeesManages.size();i++){
                WcxEmployeesManage wcxEmployeesManage = wcxEmployeesManages.get(i);
                int size = phoneSet.size();
                phoneSet.add(wcxEmployeesManage.getPhone());
                int size1 = phoneSet.size();
                wcxEmployeesManage.setOpendId(openid.toString());
                wcxEmployeesManage.setWxName(nickname ==null?"":nickname.toString());
                wcxEmployeesManage.setAccessToken(s);
                wcxEmployeesManage.setHeadImgurl(headimgurl ==null ?"":headimgurl.toString());
                //判断是否有用户编号如果没有，则设置
                String tygCertificateNumber = wcxEmployeesManage.getTygCertificateNumber();
                wcxEmployeesManage.setLastUpdated(new Date());
                wcxEmployeesManage.setIsLogin("1");
                wcxEmployeesManage.setStatus("1");
                wcxEmployeesManage.setIsFocusWx(subscribe== null?1:(((boolean)subscribe) == true?0:1));
                wcxExperienceMapper.update(wcxEmployeesManage);
                if(tygCertificateNumber ==null || "".equals(tygCertificateNumber)){
                    //生成编号
                    if(size != size1){
                        createCode(wcxEmployeesManage.getPhone());
                    }
                }
            }
            WcxEmployeesManage wcxEmployeesManage = wcxEmployeesManages.get(0);
            result.setData(wcxEmployeesManage);
        }catch(Exception e){
            e.printStackTrace();
            result.setResultCode(400);
            result.setResultMsg("详细信息非json格式解析错误");
            return result;
        }
        result.setResultCode(200);
        result.setMessage("成功登录");
        return result;
    }

    @Override
    public Result createCode(String phone) {
        //生成员工体验官证书编号
        SimpleDateFormat sim=new SimpleDateFormat("yyyy-MM-dd");
        String format = sim.format(new Date());
        String[] split = format.split("-");
        List<WcxEmployeesManage> wcxEmployeesManages;
        if(phone !=null && phone !=""){
            wcxEmployeesManages= wcxExperienceMapper.selectAllOrByPhoneBy0("0");
        }else{
            wcxEmployeesManages=wcxExperienceMapper.selectByPhoneAndIdentification(phone,"0");
        }
        String s = wcxExperienceMapper.selectMax("0");
        Integer num=0;
        String s1 = split[0];
        String numStringOne="";
        if(s ==null || "".equals(s)){
            //从年+4位算起
            num=100;
            for(int i=0;i<wcxEmployeesManages.size();i++){
                WcxEmployeesManage wcxEmployeesManage = wcxEmployeesManages.get(i);
                num=num+1;
                String numString = s1+String.format("%04d", num);
                numStringOne=numString;
                wcxEmployeesManage.setTygCertificateNumber(numString);
                wcxExperienceMapper.updateTygCertificateNumberByPhoen(wcxEmployeesManage);
            }
        }else{
            String substring = s.substring(0, 4);
            if(!substring.equals(s1)){
                //跨年冲101算起
                num=100;
                for(int i=0;i<wcxEmployeesManages.size();i++){
                    WcxEmployeesManage wcxEmployeesManage = wcxEmployeesManages.get(i);
                    num=num+1;
                    String numString = s1+String.format("%04d", num);
                    numStringOne=numString;
                    wcxEmployeesManage.setTygCertificateNumber(numString);
                    wcxExperienceMapper.updateTygCertificateNumberByPhoen(wcxEmployeesManage);
                }
            }else{
                String substring1 = s.substring(4);
                num =Integer.parseInt(substring1);
                for(int i=0;i<wcxEmployeesManages.size();i++){
                    WcxEmployeesManage wcxEmployeesManage = wcxEmployeesManages.get(i);
                    num=num+1;
                    String numString = s1+String.format("%04d", num);
                    numStringOne=numString;
                    wcxEmployeesManage.setTygCertificateNumber(numString);
                    wcxExperienceMapper.updateTygCertificateNumberByPhoen(wcxEmployeesManage);
                }
            }
        }
        List<WcxEmployeesManage> wcxEmployeesManages1;
        if(phone !=null && phone !=""){
            wcxEmployeesManages1= wcxExperienceMapper.selectAllOrByPhoneBy0("1");
        }else{
            wcxEmployeesManages1=wcxExperienceMapper.selectByPhoneAndIdentification(phone,"1");
        }
        String ss = wcxExperienceMapper.selectMax("1");
        if(ss ==null ||  "".equals(s)){
            //从年+4位算起
            num=0;
            for(int i=0;i<wcxEmployeesManages1.size();i++){
                WcxEmployeesManage wcxEmployeesManage = wcxEmployeesManages1.get(i);
                String tygCertificateNumber = wcxEmployeesManage.getTygCertificateNumber();
                if(tygCertificateNumber !=null){
                    continue;
                }
                num=num+1;
                String numString = s1+String.format("%04d", num);
                numStringOne=numString;
                wcxEmployeesManage.setTygCertificateNumber(numString);
                wcxExperienceMapper.updateTygCertificateNumberByPhoen(wcxEmployeesManage);
            }
        }else{
            String substring = s.substring(0, 4);
            if(!substring.equals(s1)){
                //跨年冲101算起
                num=101;
                for(int i=0;i<wcxEmployeesManages1.size();i++){
                    WcxEmployeesManage wcxEmployeesManage = wcxEmployeesManages1.get(i);
                    String tygCertificateNumber = wcxEmployeesManage.getTygCertificateNumber();
                    if(tygCertificateNumber !=null){
                        continue;
                    }
                    num=num+1;
                    String numString = s1+String.format("%04d", num);
                    numStringOne=numString;
                    wcxEmployeesManage.setTygCertificateNumber(numString);
                    wcxExperienceMapper.updateTygCertificateNumberByPhoen(wcxEmployeesManage);
                }
            }else{
                String substring1 = s.substring(4);
                num =Integer.parseInt(substring1);
                for(int i=0;i<wcxEmployeesManages1.size();i++){
                    WcxEmployeesManage wcxEmployeesManage = wcxEmployeesManages1.get(i);
                    String tygCertificateNumber = wcxEmployeesManage.getTygCertificateNumber();
                    if(tygCertificateNumber !=null){
                        continue;
                    }
                    num=num+1;
                    String numString = s1+String.format("%04d", num);
                    numStringOne=numString;
                    wcxEmployeesManage.setTygCertificateNumber(numString);
                    wcxExperienceMapper.updateTygCertificateNumberByPhoen(wcxEmployeesManage);
                }
            }
        }
        //selectMax
        Result result=new Result();
        result.setResultCode(200);
        result.setData(numStringOne);
        return result;
    }

    private String genAccessToken(String phone, String openId, String salt) {
        String accessToken = phone +"_"+openId +"_"+ salt;
        String hashAccessToken = MD5.GetMD5Code(accessToken).toUpperCase();
        return hashAccessToken;
    }
}
