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.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.ProjectInitiationEnum;
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.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 io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.parsing.Problem;
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;

    private static String SMSCODE = "SMS_UGP_0002";

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

    @Transactional(rollbackFor = Exception.class)
    public String start() {
        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());
        }
        updateProBlemFlowStatus(instanceId);
        return instanceId;
    }


    @Transactional(rollbackFor = Exception.class)
    public void execute(String instanceId,Object 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);
            }
        }


        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);
        }
    }


    public void sendSms(JSONObject object){
        //设置短信发送的基本参数
        HashMap<String, String> smsParams = new HashMap();
//        smsParams.put("smsCode", SMSCODE);
//        smsParams.put("companyName", object.getString("installationUnit"));
//        smsParams.put("projectName", object.getString("name"));
        //条件构造器 通过项目id查出来的项目详情信息中的区域代码，在监管区域规则表中拿到详细信息中的监察部门id，在使用监察部门id查找到该部门下的用户List。
        QueryWrapper<SuperviseRule> wrapper = new QueryWrapper<>();
        wrapper.eq("admin_region_code", projectServiceImpl.getById(object.getLong("projectId")).getInstallRegionCode());
        String noticeUnitId = orgUsrServiceImpl.getById(superviseRuleServiceImpl.getOne(wrapper).getSuperviseDeptId()).getAmosOrgId();
        List<AgencyUserModel> agencyUserModelList = Privilege.agencyUserClient.queryByDepartmentId(Long.valueOf(noticeUnitId), null, null, null).getResult();
        //遍历用户List，拿到用户手机号、userId,来发短信、存短信日志。
        for (AgencyUserModel agencyUserModel : agencyUserModelList) {
            LambdaQueryWrapper<OrgUsr> wrapperQueryWrapper = new LambdaQueryWrapper<>();
            wrapperQueryWrapper.eq(OrgUsr::getAmosOrgCode,agencyUserModel.getUserId());

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

    @Transactional(rollbackFor = Exception.class)
    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);
    }
}
