package com.cftech.workshop.template.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cftech.accounts.model.MpAccountsEntity;
import com.cftech.accounts.model.SysJob;
import com.cftech.accounts.service.JobService;
import com.cftech.accounts.service.MpAccountsService;
import com.cftech.core.sql.Conds;
import com.cftech.core.util.*;
import com.cftech.workshop.template.model.Template;
import com.cftech.workshop.workshop.model.WorkShopMessageDto;
import com.cftech.workshop.workshop.service.WorkshopService;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.mp.api.core.req.model.message.IndustryTemplateMessageSend;
import org.mp.api.core.req.model.message.TemplateData;
import org.mp.api.wxsendmsg.JwTemplateMessageAPI;
import org.owasp.esapi.ESAPI;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * @author KangLiangHuang
 *         <p>
 *         定时测试类
 */
@Slf4j
public class JobDemo2 implements Job {


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        boolean isCluster = Boolean.valueOf(SystemConfig.p.getProperty("quartz.isCluster"));
        if (!isCluster) {
            return;
        }
        log.info("JobDemo2：启动任务=======================");
        run();
        String keyId = context.getTrigger().getKey().getName();//这个ID主键
        //获得明细数据
        JobDataMap jobInfo = context.getJobDetail().getJobDataMap();
        String id = jobInfo.get("uid") == null ? "" : jobInfo.getString("uid");//这个也是ID主键
        log.info("任务ID：" + id);
        TemplateService templateService = SpringContextHolder.getBean(TemplateService.class);
        Conds templateConds = new Conds();
        templateConds.equal("uuid", id);
        Template template = templateService.fetchSearchByConds(templateConds);

        if (template != null) {
            WorkshopService workshopService = SpringContextHolder.getBean(WorkshopService.class);
            MpTokenUtil mpTokenUtil = SpringContextHolder.getBean(MpTokenUtil.class);
            MpAccountsService mpAccountsService = SpringContextHolder.getBean(MpAccountsService.class);
            MpAccountsEntity mpAccountsEntity = mpAccountsService.getMpAccountsAppid(SystemConfig.p.getProperty("WX_MP_SERVER_APPID"));
            if ("0".equals(template.getType())) { //行程信息完善提醒，仅提醒已报名但未填写行程信息的客户
                Conds workConds = new Conds();
                workConds.greatEqual("w.status", 1);
                workConds.equal("w.wsid",template.getMeetingId());
                workConds.notNull("m.open_id");
                List<WorkShopMessageDto> workShopMessageDtoList = workshopService.getTemplateWorkShopMessage(workConds);
                for (WorkShopMessageDto workShopMessageDto : workShopMessageDtoList) {
                    if (StringUtils.isNotBlank(workShopMessageDto.getDetailsinfo())) {
                        workShopMessageDto.setDetailsinfo(ESAPI.encoder().decodeForHTML(workShopMessageDto.getDetailsinfo()));
                        JSONObject detainJson = JSON.parseObject(workShopMessageDto.getDetailsinfo());
                        if ("0".equals(detainJson.getString("isRelay"))) {
                            continue;
                        }
                    }
                    //没有填写过任何行程信息，直接发送模板消息及短信内容
                    String content = template.getContent();
                    if (StringUtils.isNotBlank(content)) {
                        content=ESAPI.encoder().decodeForHTML(content).replace("{{}}",workShopMessageDto.getSurname()+workShopMessageDto.getFirstName());
                        JSONObject templateJson = JSON.parseObject(content);
                        templateJson.put("touser", workShopMessageDto.getOpenId());
                        if(StringUtils.isNotBlank(template.getUrl())){
                            templateJson.put("url", ESAPI.encoder().decodeForHTML(template.getUrl()));
                        }
                        JwTemplateMessageAPI.sendTemplateMsgJson(templateJson.toString(), mpTokenUtil.getToken(mpAccountsEntity));
                        if (StringUtils.isNotBlank(template.getSendMessage())) {
                            try {
                                SMSSender.readContentFromPost(workShopMessageDto.getPhone(), template.getSendMessage());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        log.info("模板消息内容为空");
                    }
                }
            }else if("1".equals(template.getType())){
                Conds workConds = new Conds();
                workConds.greatEqual("w.status", 1);
                workConds.equal("w.wsid",template.getMeetingId());
                workConds.notNull("m.open_id");
                List<WorkShopMessageDto> workShopMessageDtoList = workshopService.getTemplateWorkShopMessage(workConds);
                for (WorkShopMessageDto workShopMessageDto : workShopMessageDtoList) {
                    if (StringUtils.isNotBlank(workShopMessageDto.getDetailsinfo())) {
                        workShopMessageDto.setDetailsinfo(ESAPI.encoder().decodeForHTML(workShopMessageDto.getDetailsinfo()));
                        JSONObject detainJson = JSON.parseObject(workShopMessageDto.getDetailsinfo());
                        if ("1".equals(detainJson.getString("isRelay"))) {
                            continue;
                        }
                    }else{
                        continue;
                    }
                    //没有填写过任何行程信息，直接发送模板消息及短信内容
                    String content = template.getContent();
                    if (StringUtils.isNotBlank(content)) {
                        content=ESAPI.encoder().decodeForHTML(content).replace("{{}}",workShopMessageDto.getSurname()+workShopMessageDto.getFirstName());
                        JSONObject templateJson = JSON.parseObject(content);
                        templateJson.put("touser", workShopMessageDto.getOpenId());
                        if(StringUtils.isNotBlank(template.getUrl())){
                            templateJson.put("url",ESAPI.encoder().decodeForHTML( template.getUrl()));
                            log.info(ESAPI.encoder().decodeForHTML( template.getUrl()));
                        }
                        JwTemplateMessageAPI.sendTemplateMsgJson(templateJson.toString(), mpTokenUtil.getToken(mpAccountsEntity));
                        if (StringUtils.isNotBlank(template.getSendMessage())) {
                            try {
                                SMSSender.readContentFromPost(workShopMessageDto.getPhone(), template.getSendMessage());
                            } catch (IOException e) {
                                log.error(e.getMessage());
                            }
                        }
                    } else {
                        log.info("模板消息内容为空");
                    }
                }
            }else if("2".equals(template.getType())){
                Conds workConds = new Conds();
                workConds.greatEqual("w.status", 1);
                workConds.equal("w.wsid",template.getMeetingId());
                workConds.notNull("m.open_id");
                List<WorkShopMessageDto> workShopMessageDtoList = workshopService.getTemplateWorkShopMessage(workConds);
                for (WorkShopMessageDto workShopMessageDto : workShopMessageDtoList) {
                    String content = template.getContent();
                    if (StringUtils.isNotBlank(content)) {
                        content=ESAPI.encoder().decodeForHTML(content).replace("{{}}",workShopMessageDto.getSurname()+workShopMessageDto.getFirstName());
                        JSONObject templateJson = JSON.parseObject(content);
                        templateJson.put("touser", workShopMessageDto.getOpenId());
                        if(StringUtils.isNotBlank(template.getUrl())){
                            templateJson.put("url", ESAPI.encoder().decodeForHTML(template.getUrl()));
                        }
                        JwTemplateMessageAPI.sendTemplateMsgJson(templateJson.toString(), mpTokenUtil.getToken(mpAccountsEntity));
                        if (StringUtils.isNotBlank(template.getSendMessage())) {
                            try {
                                SMSSender.readContentFromPost(workShopMessageDto.getPhone(), template.getSendMessage());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        log.info("模板消息内容为空");
                    }
                }
            }else if("3".equals(template.getType())){
                Conds workConds = new Conds();
                workConds.greatEqual("w.status", 1);
                workConds.equal("w.wsid",template.getMeetingId());
                workConds.notNull("m.open_id");
                List<WorkShopMessageDto> workShopMessageDtoList = workshopService.getTemplateWorkShopMessage(workConds);
                for (WorkShopMessageDto workShopMessageDto : workShopMessageDtoList) {
                    String content = template.getContent();
                    if (StringUtils.isNotBlank(content)) {
                        content=ESAPI.encoder().decodeForHTML(content).replace("{{}}",workShopMessageDto.getSurname()+workShopMessageDto.getFirstName());
                        JSONObject templateJson = JSON.parseObject(content);
                        templateJson.put("touser", workShopMessageDto.getOpenId());
                        if(StringUtils.isNotBlank(template.getUrl())){
                            templateJson.put("url", ESAPI.encoder().decodeForHTML(template.getUrl()));
                        }
                        JwTemplateMessageAPI.sendTemplateMsgJson(templateJson.toString(), mpTokenUtil.getToken(mpAccountsEntity));
                        if (StringUtils.isNotBlank(template.getSendMessage())) {
                            try {
                                SMSSender.readContentFromPost(workShopMessageDto.getPhone(), template.getSendMessage());
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        log.info("模板消息内容为空");
                    }
                }
            }else if("4".equals(template.getType())){
                String content = template.getContent();
                JwTemplateMessageAPI.sendTemplateMsgJson(content,mpTokenUtil.getToken(mpAccountsEntity));
            }
            //执行更新操作
            if (context.getNextFireTime() != null) {
                log.info("JobDemo2：下次执行时间=====" +
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                                .format(context.getNextFireTime()) + "==============");
            } else {
                JobService jobService = SpringContextHolder
                        .getBean(JobService.class);
                SysJob sysJob = new SysJob();

                sysJob.setJobuid(id);
                sysJob.setStatus("0");
                jobService.updateStatus(sysJob);
                log.info("JobDemo2一次性，已执行完成");
            }
        }
    }

    public void run() {
        log.info("JobDemo2：执行完毕=======================");
    }
}
