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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.yeejoin.amos.boot.biz.common.service.impl.WorkflowExcuteServiceImpl;
import com.yeejoin.amos.boot.biz.common.workflow.feign.WorkflowFeignService;
import com.yeejoin.amos.boot.module.common.biz.service.impl.OrgUsrServiceImpl;
import com.yeejoin.amos.boot.module.common.biz.utils.CommonResponseUtil;
import com.yeejoin.amos.boot.module.ugp.api.Enum.ProjectInitiationEnum;
import com.yeejoin.amos.boot.module.ugp.api.Util.CommonResponse;
import com.yeejoin.amos.boot.module.ugp.api.Util.HttpUtil;
import com.yeejoin.amos.boot.module.ugp.api.constants.XJConstant;
import com.yeejoin.amos.boot.module.ugp.api.dto.ProjectInitiationDto;
import com.yeejoin.amos.boot.module.ugp.api.entity.InstallNoticeMsg;
import com.yeejoin.amos.boot.module.ugp.api.entity.Project;
import com.yeejoin.amos.boot.module.ugp.api.entity.ProjectInitiation;
import com.yeejoin.amos.boot.module.ugp.api.entity.SuperviseRule;
import com.yeejoin.amos.boot.module.ugp.api.mapper.ProjectInitiationMapper;
import com.yeejoin.amos.boot.module.ugp.api.service.IProjectInitiationService;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.client.AgencyUserClient;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.rule.model.IdxProjectModel;
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.client.TaskClient;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import java.util.*;

@Service
public class ProjectInitiationServiceImpl extends BaseService<ProjectInitiationDto, ProjectInitiation, ProjectInitiationMapper> implements IProjectInitiationService {



    @Autowired
    ProjectInitiationServiceImpl projectInitiationService;

    @Autowired
    WorkflowExcuteServiceImpl workflowExcuteService;

    @Autowired
    WorkflowFeignService workflowFeignService;

    @Autowired
    InstallNoticeMsgServiceImpl installNoticeMsgService;

    @Autowired
    ProjectServiceImpl projectServiceImpl;

    @Autowired
    SuperviseRuleServiceImpl superviseRuleServiceImpl;

    @Autowired
    ProjectServiceImpl projectService;

    @Autowired
    OrgUsrServiceImpl orgUsrServiceImpl;

    private final Logger logger = LoggerFactory.getLogger(ProjectInitiationServiceImpl.class);

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

    private static String SMSCODE = "SMS_UGP_0001";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void start(Project project) {
        String instanceId = null;
        //启动流程
        try {
            ActWorkflowStartDTO dto = new ActWorkflowStartDTO();
            dto.setProcessDefinitionKey(processDefinitionKey);
            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("流程启动！");
            this.save(projectInitiation);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("流程启动失败："+e.getMessage());
        }
        //新增project表的流程id和流程状态
        project.setInstanceId(instanceId);
        project.setStatus(getFlowTaskName(instanceId));
        projectService.updateById(project);
        //审核条件
        String option = "0";
        if (true) {
            option = "1";
        }
        //执行项目立项流程
        execute(instanceId,project,option);
    }

    @Override
    @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 (ProjectInitiationEnum.平台审核.getName().equals(dataObject.getString("name"))) {
            if (true) {
                option = "1";
            }
        }

        if(ProjectInitiationEnum.监检员审核.getName().equals(dataObject.getString("name"))){
            if("1".equals(option)){
                projectInitiation.setTaskName(dataObject.getString("name")+"（流程结束！）");
            }
        }
        if(ProjectInitiationEnum.接受审查意见.getName().equals(dataObject.getString("name"))){
            projectInitiation.setTaskName(dataObject.getString("name")+"（流程结束！）");
        }

        if (ProjectInitiationEnum.告知申请.getName().equals(dataObject.getString("name"))) {
            if(!ValidationUtil.isEmpty(objectd)) {
                //设置短信发送的基本参数
                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());
                List<AgencyUserModel> agencyUserModelList = Privilege.agencyUserClient.queryByDepartmentId(Long.valueOf(orgUsrServiceImpl.getById(superviseRuleServiceImpl.getOne(wrapper).getSuperviseDeptId()).getAmosOrgId()), null, null, null).getResult();
                //遍历用户List，拿到用户手机号、userId,来发短信、存短信日志。
                for (AgencyUserModel agencyUserModel : agencyUserModelList) {
                    SmsRecordModel smsRecordModel = sendSmsMassage(SMSCODE, agencyUserModel.getMobile(), smsParams);
                    InstallNoticeMsg installNoticeMsg = new InstallNoticeMsg();
                    if (ValidationUtil.isEmpty(smsRecordModel)) {
                        continue;
                    }
                    installNoticeMsg.setContent(smsRecordModel.getSmsContent());
                    installNoticeMsg.setInstallNoticeId(smsRecordModel.getSequenceNbr());
                    installNoticeMsg.setTargetUnitId(Long.valueOf(smsRecordModel.getAgencyCode()));
                    installNoticeMsg.setTargetPersonId(Long.valueOf(agencyUserModel.getUserId()));
                    installNoticeMsg.setSendTime(smsRecordModel.getSendTime());
                    installNoticeMsgService.save(installNoticeMsg);
                }
            }
        }
        if ("监检科室分配".equals(dataObject.getString("name"))) {

        }
        if ("监检员分配".equals(dataObject.getString("name"))) {

        }
        if ("监检员审核".equals(dataObject.getString("name"))) {

        }

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

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

    /**
     * 获取流程当前任务名称
     * @param instanceId
     * @return
     */
    public String getFlowTaskName(String instanceId){
        JSONObject jsonObject = workflowFeignService.getTask(instanceId);
        if (ValidationUtil.isEmpty(jsonObject)) {
            return "";
        }
        return jsonObject.getJSONObject("data").getString("name");
    }

    public void updateProjectFlowStatus(String instanceId){
        LambdaQueryWrapper<Project> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Project::getInstanceId,instanceId);
        Project project = projectService.getOne(wrapper);
        project.setStatus(getFlowTaskName(instanceId));
        projectService.updateById(project);
    }
}
