package com.yeejoin.amos.boot.module.ugp.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeejoin.amos.boot.biz.common.bo.ReginParams;
import com.yeejoin.amos.boot.biz.common.workflow.feign.WorkflowFeignService;
import com.yeejoin.amos.boot.module.common.api.entity.OrgUsr;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.ugp.api.Enum.ProblemProcessEnum;
import com.yeejoin.amos.boot.module.ugp.api.Enum.SMSEnum;
import com.yeejoin.amos.boot.module.ugp.api.entity.*;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.amos.feign.systemctl.model.SmsRecordModel;
import com.yeejoin.amos.feign.workflow.Workflow;
import com.yeejoin.amos.feign.workflow.model.ActWorkflowStartDTO;
import com.yeejoin.amos.feign.workflow.model.AjaxResult;
import com.yeejoin.amos.feign.workflow.model.TaskResultDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Dell
 */
@Service
public class ProblemInitiationServiceImpl {

    @Autowired
    WorkflowFeignService workflowFeignService;

    @Autowired
    ProjectServiceImpl projectServiceImpl;

    @Autowired
    SuperviseRuleServiceImpl superviseRuleServiceImpl;

    @Autowired
    RectifyMsgServiceImpl rectifyMsgServiceImpl;

    @Autowired
    OrgUsrServiceImpl orgUsrServiceImpl;

    @Autowired
    ProjectInitiationServiceImpl projectInitiationService;

    @Autowired
    QualityProblemServiceImpl qualityProblemService;


    @Value("${params.work.flow.problemDefinitionKey}")
    private String problemDefinitionKey;

    @Value("supervisionRoleId")
    private String supervisionRoleId;

    @Value("installationRoleId")
    private String installationRoleId;

    public String start(QualityProblem qualityProblem) {
        String instanceId = null;
        //启动流程
        try {
            ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            dto.setProcessDefinitionKey(problemDefinitionKey);
            dto.setBusinessKey("1");
            AjaxResult ajaxResult = Workflow.taskClient.startByVariable(dto);
            instanceId = ((Map)ajaxResult.get("data")).get("id").toString();
            ProjectInitiation projectInitiation = new ProjectInitiation();
            projectInitiation.setInstanceId(instanceId);
            projectInitiation.setTaskName("流程启动！");
            projectInitiationService.save(projectInitiation);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("流程启动失败："+e.getMessage());
        }
        qualityProblem.setInstanceId(instanceId);
        qualityProblem.setStatus(projectInitiationService.getFlowTaskName(instanceId));
        qualityProblemService.updateById(qualityProblem);
        sendSms(JSONObject.parseObject(JSONObject.toJSONString(qualityProblem)), SMSEnum.质量问题短信.getCode());
        return instanceId;
    }


    public void execute(String instanceId,QualityProblem objectd, String option){
        JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(objectd));
        JSONObject jsonObject = workflowFeignService.getTask(instanceId);
        ProjectInitiation projectInitiation = new ProjectInitiation();
        projectInitiation.setInstanceId(instanceId);
        projectInitiation.setContext(JSON.toJSONString(objectd));
        JSONObject dataObject = jsonObject.getJSONObject("data");
        projectInitiation.setTaskId(dataObject.getString("id"));
        projectInitiation.setTaskName(dataObject.getString("name"));

        if (ProblemProcessEnum.重大问题发送短信.getName().equals(dataObject.getString("name"))) {
            if(!ValidationUtil.isEmpty(objectd)) {
                sendSms(object, SMSEnum.重大质量问题短信.getCode());
            }
        }

        if (ProblemProcessEnum.超期整改发送短信.getName().equals(dataObject.getString("name"))) {
            if(!ValidationUtil.isEmpty(objectd)) {
                sendSms(object, SMSEnum.超期整改短信.getCode());
            }
        }

        if (ProblemProcessEnum.重大问题整改完成发送短信.getName().equals(dataObject.getString("name"))) {
            if(!ValidationUtil.isEmpty(objectd)) {
                sendSms(object, SMSEnum.重大质量问题短信.getCode());
            }
        }


        try {
            //组装信息
            TaskResultDTO dto = new TaskResultDTO();
            dto.setResult(option);
            dto.setResultCode("select");
            dto.setTaskId(projectInitiation.getTaskId());
            HashMap<String, Object> var = new HashMap<>();
            var.put("select", option);
            dto.setVariable(var);
            //执行流程
            Workflow.taskClient.completeByTask(projectInitiation.getTaskId(),dto);
            //保存日志
            projectInitiationService.save(projectInitiation);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("任务完成失败："+e.getMessage());
        } finally {
            //更新problem中的status字段，表示当前流程下一个执行的任务
            updateProBlemFlowStatus(instanceId);
            QualityProblem quality = qualityProblemService.getById(objectd.getSequenceNbr());
            objectd.setStatus(quality.getStatus());
        }
    }


    public void sendSms(JSONObject object, String smsCode){
        Long sequenceNbr = object.getLong("sequenceNbr");
        if(SMSEnum.项目安装告知申请.getCode().equals(smsCode)){
            //设置短信发送的基本参数
            HashMap<String, String> smsParams = new HashMap();
            smsParams.put("smsCode", smsCode);
            smsParams.put("projectName", object.getString("projectName"));
            smsParams.put("problemDesc", object.getString("problemDesc"));
            //条件构造器 通过项目id查出来的项目详情信息中的区域代码，在监管区域规则表中拿到详细信息中的监察部门id，在使用监察部门id拿到平台的监察部门id
            LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SuperviseRule::getAdminRegionCode, projectServiceImpl.getById(object.getLong("projectId")).getInstallRegionCode());
            String noticeUnitId = orgUsrServiceImpl.getById(superviseRuleServiceImpl.getOne(wrapper).getSuperviseDeptId()).getAmosOrgId();
            sendMessage(sequenceNbr,noticeUnitId,smsParams,smsCode,supervisionRoleId);
        }else if(SMSEnum.项目立项驳回短信.getCode().equals(smsCode)) {
            //设置短信发送的基本参数
            HashMap<String, String> smsParams = new HashMap();
            smsParams.put("smsCode", smsCode);
            smsParams.put("projectName", object.getString("projectName"));
            smsParams.put("reviewInfo", object.getString("reviewInfo"));
            //给监察发短信
            LambdaQueryWrapper<SuperviseRule> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SuperviseRule::getAdminRegionCode, projectServiceImpl.getById(object.getLong("projectId")).getInstallRegionCode());
            String supervisionUnitId = orgUsrServiceImpl.getById(superviseRuleServiceImpl.getOne(wrapper).getSuperviseDeptId()).getAmosOrgId();
            sendMessage(sequenceNbr,supervisionUnitId,smsParams,smsCode,supervisionRoleId);
            //给安装发短信
            String installationUnitId = orgUsrServiceImpl.getById(projectServiceImpl.getById(object.getLong("projectId")).getInstallationUnitId()).getAmosOrgId();
            sendMessage(sequenceNbr,installationUnitId,smsParams,smsCode,installationRoleId);
        }

    }


    /**
     * 发送短信
     * @param sequenceNbr 任务id（项目/问题）
     * @param noticeUnitId 平台目标企业id
     * @param smsParams 短信参数
     * @param smsCode 短信模板
     * @param roleId 角色id
     */
    public void sendMessage(Long sequenceNbr,String noticeUnitId,HashMap<String, String> smsParams,String smsCode,String roleId){
        //向noticeUnitId的部门发送短信
        List<AgencyUserModel> agencyUserModelList = Privilege.agencyUserClient.queryByRoleId(roleId,null).getResult();
        //遍历用户List，拿到用户手机号、userId,来发短信、存短信日志。
        for (AgencyUserModel agencyUserModel : agencyUserModelList) {
            boolean bool = false;
            List<CompanyModel> companyModelList = agencyUserModel.getCompanys();
            for (CompanyModel companyModel : companyModelList) {
                bool = companyModel.getSequenceNbr().equals(noticeUnitId);
                if(bool){
                    break;
                }
            }
            if (bool) {
                LambdaQueryWrapper<OrgUsr> wrapperQueryWrapper = new LambdaQueryWrapper<>();
                wrapperQueryWrapper.eq(OrgUsr::getAmosOrgId,agencyUserModel.getSequenceNbr());

                SmsRecordModel smsRecordModel = sendSmsMassage(smsCode, agencyUserModel.getMobile(), smsParams);
                RectifyMsg rectifyMsg = new RectifyMsg();
                if (ValidationUtil.isEmpty(smsRecordModel)) {
                    continue;
                }
                rectifyMsg.setContent(smsRecordModel.getSmsContent());
                rectifyMsg.setProblemId(sequenceNbr);
                rectifyMsg.setNoticeUnitId(Long.valueOf(noticeUnitId));
                rectifyMsg.setMsgReceiver(orgUsrServiceImpl.getOne(wrapperQueryWrapper).getSequenceNbr());
                rectifyMsg.setSendTime(smsRecordModel.getSendTime());
                rectifyMsgServiceImpl.save(rectifyMsg);
            }
        }
    }

    public SmsRecordModel sendSmsMassage(String smsCode, String mobile, HashMap<String, String> smsParams){
        SmsRecordModel smsRecordModel = new SmsRecordModel();

        if(!ValidationUtil.isEmpty(mobile)){
            smsParams.put("smsCode",smsCode);
            smsParams.put("mobile",mobile);
            smsRecordModel = Systemctl.smsClient.sendCommonSms(smsParams).getResult();
        }
        return smsRecordModel;
    }


    public void updateProBlemFlowStatus(String instanceId){
        LambdaQueryWrapper<QualityProblem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(QualityProblem::getInstanceId,instanceId);
        QualityProblem qualityProblem = qualityProblemService.getOne(wrapper);
        qualityProblem.setStatus(projectInitiationService.getFlowTaskName(instanceId));
        qualityProblemService.updateById(qualityProblem);
    }

    public void updateProblemStatus(QualityProblem qualityProblem,Long sequenceNbr){
        QualityProblem quality = qualityProblemService.getById(sequenceNbr);
        qualityProblem.setStatus(quality.getStatus());
    }
}
