package com.qmth.sop.task.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qmth.sop.business.bean.result.FlowTaskSmsResult;
import com.qmth.sop.business.entity.SysMessage;
import com.qmth.sop.business.entity.SysUser;
import com.qmth.sop.business.entity.TSJobRemind;
import com.qmth.sop.business.service.SysMessageService;
import com.qmth.sop.business.service.SysUserService;
import com.qmth.sop.business.service.TSJobRemindService;
import com.qmth.sop.business.util.SmsSendUtil;
import com.qmth.sop.common.contant.SystemConstant;
import com.qmth.sop.common.enums.*;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Description: 流程任务执行job
 * @Param:
 * @return:
 * @Author: wangliang
 * @Date: 2021/7/9
 */
public class RemindTaskJob extends QuartzJobBean {
    private final static Logger log = LoggerFactory.getLogger(RemindTaskJob.class);

    @Resource
    SmsSendUtil smsSendUtil;

    @Resource
    TSJobRemindService tsJobRemindService;

    @Resource
    SysUserService sysUserService;

    @Resource
    SysMessageService sysMessageService;

    @Override
    @Transactional
    public void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("flowTaskQuartzJob,context:{}", context);
        try {
            JobDataMap map = context.getJobDetail().getJobDataMap();
            TSJobRemind tsJobRemindTask = (TSJobRemind) map.get(SystemConstant.JOB_DATA);
            if (Objects.nonNull(tsJobRemindTask)) {
                TSJobRemind tsJobRemind = tsJobRemindService.getById(tsJobRemindTask.getId());
                if (Objects.nonNull(tsJobRemind)) {//数据还在则说明要发送提醒短信
                    if (tsJobRemind.getType() == JobQuartzTypeEnum.FLOW) {//流程发送短信
                        FlowTaskSmsResult flowTaskSmsResult = tsJobRemindService.getFlowTaskRemindSmsInfo(tsJobRemind.getId());
                        Optional.ofNullable(flowTaskSmsResult).orElseThrow(() -> ExceptionResultEnum.USER_NO_EXISTS.exception());

                        Map<String, Object> templateParam = new HashMap<>();
                        templateParam.put("userName", flowTaskSmsResult.getRealName());

                        SysMessage sysMessage = null;
                        String configKey = null, content = null;
                        if (Objects.nonNull(flowTaskSmsResult)) {
                            String[] strs = tsJobRemind.getObjName().split(";");
                            if (tsJobRemind.getRemindType() == JobTypeEnum.BEFORE) {//教务处SOP和研究生SOP
                                content = MessageEnum.NOTICE_OF_SOP_DONE_REMIND.getTemplate();
                                content = content.replaceAll("\\$\\{userName\\}", flowTaskSmsResult.getRealName());
                                content = content.replaceAll("\\$\\{serviceName\\}", flowTaskSmsResult.getServiceName());
                                content = content.replaceAll("\\$\\{customName\\}", flowTaskSmsResult.getCustomName());
                                content = content.replaceAll("\\$\\{flowName\\}", strs[0] + "【" + strs[1] + "】");

                                configKey = SystemConstant.SMS_SOP_BEFORE_REMIND_CODE;
                                templateParam.put("serviceName", flowTaskSmsResult.getServiceName());
                                templateParam.put("customName", flowTaskSmsResult.getCustomName());
                                templateParam.put("flowName", strs[0] + "【" + strs[1] + "】");

                                sysMessage = new SysMessage(flowTaskSmsResult.getCrmNo(), tsJobRemind.getCode(),
                                        MessageTypeEnum.BEFORE, flowTaskSmsResult.getType().name(), flowTaskSmsResult.getServiceId(), flowTaskSmsResult.getUserId(), content,tsJobRemind.getCreateId());
                            } else if (tsJobRemind.getRemindType() == JobTypeEnum.AFTER) {
                                content = MessageEnum.NOTICE_OF_DELAY_REMIND.getTemplate();
                                content = content.replaceAll("\\$\\{userName\\}", flowTaskSmsResult.getRealName());
                                content = content.replaceAll("\\$\\{serviceName\\}", flowTaskSmsResult.getServiceName());
                                content = content.replaceAll("\\$\\{customName\\}", flowTaskSmsResult.getCustomName());
                                content = content.replaceAll("\\$\\{flowName\\}", strs[0] + "【" + strs[1] + "】");

                                configKey = SystemConstant.SMS_SOP_AFTER_REMIND_CODE;
                                templateParam.put("serviceName", flowTaskSmsResult.getServiceName());
                                templateParam.put("customName", flowTaskSmsResult.getCustomName());
                                templateParam.put("flowName", strs[0] + "【" + strs[1] + "】");

                                sysMessage = new SysMessage(flowTaskSmsResult.getCrmNo(), tsJobRemind.getCode(),
                                        MessageTypeEnum.AFTER, flowTaskSmsResult.getType().name(), flowTaskSmsResult.getServiceId(), flowTaskSmsResult.getUserId(), content,tsJobRemind.getCreateId());
                            }
                            //发送消息
                            sysMessageService.saveSysMessage(Arrays.asList(sysMessage));

                            //发送短信
                            smsSendUtil.sendSms(flowTaskSmsResult.getMobileNumber(), configKey, templateParam);
                        }
                    } else if (tsJobRemind.getType() == JobQuartzTypeEnum.NOTICE) {//公告发送短信
                        if (tsJobRemind.getRemindType() == JobTypeEnum.AFTER) {
                            List<SysUser> sysUserList = sysUserService.list(new QueryWrapper<SysUser>().lambda().isNotNull(SysUser::getMobileNumber).eq(SysUser::getEnable, true));
                            for (SysUser s : sysUserList) {
                                Map<String, Object> templateParam = new HashMap<>();
                                templateParam.put("userName", s.getRealName());
                                templateParam.put("title", tsJobRemind.getObjName());
                                smsSendUtil.sendSms(s.getMobileNumber(), SystemConstant.SMS_NOTICE_CODE, templateParam);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(SystemConstant.LOG_ERROR, e);
        }
    }
}
