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

import cn.com.countrygarden.bi.main.core.Result;
import cn.com.countrygarden.bi.main.core.ResultCode;
import cn.com.countrygarden.bi.main.dao.experience.TygGzhInfoManageMapper;
import cn.com.countrygarden.bi.main.dao.experience.TygTagMapper;
import cn.com.countrygarden.bi.main.dao.experience.WcxExperienceMapper;
import cn.com.countrygarden.bi.main.dao.twerp.hm.TbSysUserMapper;
import cn.com.countrygarden.bi.main.dto.experience.TygGzhInfoManageDto;
import cn.com.countrygarden.bi.main.dto.experience.TygGzhUserInfoDto;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.experience.TygGzhInfoManage;
import cn.com.countrygarden.bi.main.model.experience.TygTag;
import cn.com.countrygarden.bi.main.model.experience.WcxEmployeesManage;
import cn.com.countrygarden.bi.main.model.twerp.hm.TbSysUser;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.service.experience.TygGzhInfoManageService;
import cn.com.countrygarden.bi.main.util.PageUtils;
import com.salesforce.SurveyConfigService;
import org.smartframework.common.GlobalConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Service
public class TygGzhInfoManageServiceImpl implements TygGzhInfoManageService {
    @Autowired
    private TygGzhInfoManageMapper tygGzhInfoManageMapper;
    @Autowired
    private AccessTokenService accessTokenService;
    @Value("${wechat.modelId}")
    private String modelId;
    @Autowired
    private TbSysUserMapper tbSysUserMapper;
    @Autowired
    private WcxExperienceMapper wcxExperienceMapper;
    @Autowired
    private SurveyConfigService surveyConfigService;
    @Autowired
    private TygTagMapper tygTagMapper;
    @Override
    public Result add(TygGzhInfoManage tygGzhInfoManage, HttpServletRequest req) {
        Result result=new Result();
        if(tygGzhInfoManage ==null){
            result.setResultCode(400);
            result.setResultMsg("编辑失败，参数错误");
            return result;
        }
        String accessToken = req.getParameter("AccessToken");
        AccessToken userAccessToken = accessTokenService.findByToken(accessToken);
        if(userAccessToken ==null){
            result.setResultCode(500);
            result.setMessage("当前登陆账户无法识别，请从重新登录或刷新页面后操作。");
            return result;
        }
        Integer id = tygGzhInfoManage.getId();
        if(id !=null){
            //编辑
            TygGzhInfoManage tygGzhInfoManage2=tygGzhInfoManageMapper.selectById(id);
            Integer status = tygGzhInfoManage2.getStatus();
            if(status != 0){
                result.setResultCode(10007);
                result.setResultMsg("编辑失败，模板消息已发送");
                return result;
            }
            tygGzhInfoManage.setUpdateBy(userAccessToken.getUserCode());
            tygGzhInfoManageMapper.updateById(tygGzhInfoManage);
            result.setResultCode(200);
            result.setResultMsg("编辑成功");
            return result;
        }
        tygGzhInfoManage.setCreateBy(userAccessToken.getUserCode());
        tygGzhInfoManage.setModelId(modelId);
        tygGzhInfoManageMapper.add(tygGzhInfoManage);
        result.setResultCode(200);
        result.setResultMsg("新增成功");
        return result;
    }

    @Override
    public Result list(TygGzhInfoManageDto tygGzhInfoManageDto) {
        Result result=new Result();
        int n = (tygGzhInfoManageDto.getPage() - 1) * tygGzhInfoManageDto.getSize();
        tygGzhInfoManageDto.setPageStart(n);
        List<TygGzhInfoManage> list = tygGzhInfoManageMapper.list(tygGzhInfoManageDto);
        for(int i=0;i<list.size();i++){
            TygGzhInfoManage tygInfoManage = list.get(i);
            String createBy = tygInfoManage.getCreateBy();
            TbSysUser byUserCode = tbSysUserMapper.findByUserCode(createBy);
            if(byUserCode !=null){
                String userName = byUserCode.getUserName();
                tygInfoManage.setCreateBy(userName);
            }
        }
        int total = tygGzhInfoManageMapper.count(tygGzhInfoManageDto);
        PageUtils pageUtils = new PageUtils(list,total);
        return result.setResultCode(ResultCode.SUCCESS).setData(pageUtils);
    }

    @Override
    public Result one(String id) {
        Result result=new Result();
        TygGzhInfoManage tygGzhInfoManage=tygGzhInfoManageMapper.selectById(Integer.parseInt(id));
        return result.setResultCode(ResultCode.SUCCESS).setData(tygGzhInfoManage);
    }

    @Override
    public Result del(String id) {
        Result result=new Result();
        if(id ==null){
            result.setResultCode(400);
            result.setMessage("id不能为空");
            return result;
        }
        TygGzhInfoManage tygGzhInfoManage = tygGzhInfoManageMapper.selectById(Integer.parseInt(id));
        Integer status = tygGzhInfoManage.getStatus();
        if(status == 0){
            tygGzhInfoManageMapper.del(id);
        }else{
            result.setResultCode(10006);
            result.setMessage("删除失败，模板消息已发送");
            return result;
        }
        return result.setResultCode(ResultCode.SUCCESS).setData("");
    }

    @Override
    public Result chooseUser(String id, int page, int size, String userId) {
        Result result=new Result();
        if(id ==null && userId ==null){
            result.setResultCode(400);
            result.setMessage("id不能为空");
            return result;
        }
        String personInfo="";
        if(id !=null){
            TygGzhInfoManage tygGzhInfoManage = tygGzhInfoManageMapper.selectById(Integer.parseInt(id));
            if(tygGzhInfoManage ==null){
                result.setResultCode(500);
                result.setMessage("项目不存在");
                return result;
            }
             personInfo = tygGzhInfoManage.getPersonInfo();
        }else{
            personInfo=userId;
        }
        if(personInfo ==null || personInfo ==""){
            PageUtils pageUtils = new PageUtils(new ArrayList<TygGzhInfoManage>(),0);
            return result.setResultCode(ResultCode.SUCCESS).setData(pageUtils);
        }
        String[] split = personInfo.split(",");
        List<WcxEmployeesManage> wcxEmployeesManages = wcxExperienceMapper.selectByIds(split,(page-1)*size,size);
        int i = wcxExperienceMapper.selectCountByIds(split);
        PageUtils pageUtils = new PageUtils(wcxEmployeesManages,i);
        return result.setResultCode(ResultCode.SUCCESS).setData(pageUtils);
    }

    @Override
    public Result selectUser(TygGzhUserInfoDto tygGzhUserInfoDto) {
        Result result=new Result();
        int size = tygGzhUserInfoDto.getSize();
        int page = tygGzhUserInfoDto.getPage();
        int pageStart = (page - 1) *  size;
        tygGzhUserInfoDto.setPageStart(pageStart);
        TygGzhUserInfoDto tygGzhUserInfoDto1 = chageTygGzhUserInfoDto(tygGzhUserInfoDto);
        List<WcxEmployeesManage> list=wcxExperienceMapper.selectByTygGzhUserInfoDto(tygGzhUserInfoDto1);
        int i=wcxExperienceMapper.selectByTygGzhUserInfoDtoCount(tygGzhUserInfoDto1);
        PageUtils pageUtils = new PageUtils(list,i);
        return result.setResultCode(ResultCode.SUCCESS).setData(pageUtils);
    }

    @Override
    public Result delselectUser(String id, String userIds) {
        Result result=new Result();
        if(id ==null){
            result.setResultCode(400);
            result.setMessage("id不能为空");
            return result;
        }
        if(userIds ==null){
            result.setResultCode(400);
            result.setMessage("请选择要删除的用户");
            return result;
        }
        TygGzhInfoManage tygGzhInfoManage = tygGzhInfoManageMapper.selectById(Integer.parseInt(id));
        if(tygGzhInfoManage ==null){
            result.setResultCode(500);
            result.setMessage("项目不存在");
            return result;
        }
        Integer status = tygGzhInfoManage.getStatus();
        String personInfo1 = tygGzhInfoManage.getPersonInfo();
        String[] split1 = userIds.split(",");
        List<String> list =  new ArrayList<>(Arrays.asList(personInfo1.split(",")));
        if(1 ==status){
            result.setResultCode(10006);
            result.setMessage("删除失败，模板消息已发送");
            return result;
        }else{
            for(int i=0;i<split1.length;i++){
                String s = split1[i];
                Iterator<String> iter = list.iterator();
                while (iter.hasNext()) {
                    String item = iter.next();
                    if (item.equals(s)) {
                        iter.remove();
                    }
                }
            }
        }
        String personInfo2="";
        if(list.size()==0){
            personInfo2="";
        }
        if(list.size()==1){
            personInfo2=list.get(0);
        }
        if(list.size()>1){
            personInfo2 = String.join(",", list);
        }
        tygGzhInfoManage.setPersonInfo(personInfo2);
        tygGzhInfoManageMapper.updatePersonById(id,personInfo2);
        return result.setResultCode(ResultCode.SUCCESS).setData("");
    }

    @Override
    public Result sendMessage(String id) {
        if(id ==null){
            //查询需要发送的数据
            List<TygGzhInfoManage> list=tygGzhInfoManageMapper.selectListStatusNoEquals1();
            if(list.size()==0){
                return null;
            }
            getValue(list);
        }else{

        };
        return null;
    }

    @Override
    public Result tag(String id) {
        Result result=new Result();
        if(id== null){
            List<TygTag> listTag=tygTagMapper.selectList();
            return result.setResultCode(ResultCode.SUCCESS).setData(listTag);
        }
        TygTag tygTag= tygTagMapper.selectById(id);
        return result.setResultCode(ResultCode.SUCCESS).setData(tygTag);
    }

    /**
     *拼接推送微信次数
     * */
    public List<Map<String,Object>> getValue(List<TygGzhInfoManage> tygGzhInfoManagelist){
        for(int i=0;i<tygGzhInfoManagelist.size();i++){
            TygGzhInfoManage tygGzhInfoManage = tygGzhInfoManagelist.get(i);
            Date releaseTime = tygGzhInfoManage.getReleaseTime();
            Integer status = tygGzhInfoManage.getStatus();
            String personInfo = tygGzhInfoManage.getPersonInfo();
            if(status ==1){
                continue;
            }
            String[] split = personInfo.split(",");
            sendCrnWx(split,tygGzhInfoManage);
            tygGzhInfoManage.setStatus(1);
            tygGzhInfoManageMapper.update(tygGzhInfoManage);
        }
        return null;
    }
    /**
     * 推送到crn
     * */
    public void sendCrnWx(String[] split,TygGzhInfoManage tygGzhInfoManage){
        //查询所有需要推送人的信息
        List<WcxEmployeesManage> wcxEmployeesManages = wcxExperienceMapper.selectAllByIds(Arrays.asList(split));
        int length = wcxEmployeesManages.size();
        int i1 = length % 150;
        int i2 = length / 150;
        if(i1 !=0){
            i2=i2+1;
        }
        for(int i=0;i<i2;i++){
            Map<String,Object> resultMap=new HashMap<String,Object>();
            ArrayList<Map<String,Object>> list=new ArrayList<>();
            for(int j=0;j<150;j++){
                if(j > wcxEmployeesManages.size()-1){
                    break;
                }
                ArrayList<Map<String,Object>> detailList=new ArrayList<Map<String,Object>>();
                Map<String,Object> map=new HashMap<String,Object>();
                WcxEmployeesManage wcxEmployeesManage = wcxEmployeesManages.get(i*150+j);
                String name = wcxEmployeesManage.getName();
                String sex = wcxEmployeesManage.getSex();
                map.put("touser",wcxEmployeesManage.getOpendId());
                map.put("url",tygGzhInfoManage.getDetaUrl());
                map.put("templateId",modelId);
                for(int i3=0;i3<7;i3++){
                    Map<String,Object> detailMap=new HashMap<String,Object>();
                    switch (i3){
                        case 0:
                            if("男".equals(sex)){
                                name=name+"先生";
                            };
                            if("女".equals(sex)){
                                name=name+"女士";
                            }

                            detailMap.put("value",name+","+tygGzhInfoManage.getTitle());
                            detailMap.put("key","first");
                            break;
                        case 1:
                            detailMap.put("value",tygGzhInfoManage.getProjectName());
                            detailMap.put("key","keyword1");
                            break;
                        case 2:
                            detailMap.put("value",tygGzhInfoManage.getTaskName());
                            detailMap.put("key","keyword2");
                            break;
                        case 3:
                            detailMap.put("value",tygGzhInfoManage.getFinishTime());
                            detailMap.put("key","keyword3");
                            break;
                        case 4:
                            detailMap.put("value",tygGzhInfoManage.getUrl());
                            detailMap.put("key","keyword4");
                            break;
                        case 5:
                            detailMap.put("value",tygGzhInfoManage.getAppoint());
                            detailMap.put("key","keyword5");
                            break;
                        case 6:
                            detailMap.put("value",tygGzhInfoManage.getDescs());
                            detailMap.put("key","remark");
                            break;
                    }
                    detailList.add(detailMap);
                }
                map.put("wechatTemplateList",detailList);
                list.add(map);
            }
            //openId
            resultMap.put("WechatAsyncTaskList",list);
            //循环一次推送到crn，发送微信模板消息
            String url = GlobalConfig.getConfigValue("salesforce.config.hostSurvey_tyg");
            try {
                surveyConfigService.querySfResultUtf8(url, "t_CreateWechatAsyncTask", resultMap);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    public TygGzhUserInfoDto chageTygGzhUserInfoDto(TygGzhUserInfoDto tygGzhUserInfoDto){
        String commName = tygGzhUserInfoDto.getCommName();
        String orgName = tygGzhUserInfoDto.getOrgName();
        String sex = tygGzhUserInfoDto.getSex();
        String identification = tygGzhUserInfoDto.getIdentification();
        if(commName !=null && commName.contains(",")){
            tygGzhUserInfoDto.setCommNameArray(Arrays.asList(commName.split(",")));
        }
        if(orgName !=null && orgName.contains(",")){
            tygGzhUserInfoDto.setOrgNameArray(Arrays.asList(orgName.split(",")));
        }
        if(sex !=null && sex.contains(",")){
            tygGzhUserInfoDto.setSexArray(Arrays.asList(sex.split(",")));
        }
        if(identification !=null && identification.contains(",")){
            tygGzhUserInfoDto.setIdentificationArray(Arrays.asList(identification.split(",")));
        }
        return tygGzhUserInfoDto;
    }
}
