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.module.common.api.entity.OrgUsr;
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.Enum.SMSEnum;
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.*;
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
    InstallNoticeMsgServiceImpl installNoticeMsgService;

    @Autowired
    ProjectServiceImpl projectServiceImpl;

    @Autowired
    SuperviseRuleServiceImpl superviseRuleServiceImpl;

    @Autowired
    ProjectServiceImpl projectService;

    @Autowired
    OrgUsrServiceImpl orgUsrServiceImpl;

    @Autowired
    RectifyMsgServiceImpl rectifyMsgServiceImpl;

    @Autowired
    ProblemInitiationServiceImpl problemInitiationService;

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

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

    @Override
    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
    public void execute(String instanceId,Object objectd, String option){
        JSONObject object = JSONObject.parseObject(JSONObject.toJSONString(objectd));
        AjaxResult ajaxResult = Workflow.taskClient.getTask(instanceId);
        JSONObject dataObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
        ProjectInitiation projectInitiation = new ProjectInitiation();
        projectInitiation.setInstanceId(instanceId);
        projectInitiation.setContext(JSON.toJSONString(objectd));
        projectInitiation.setTaskId(dataObject.getString("id"));
        projectInitiation.setTaskName(dataObject.getString("name"));

        if (ProjectInitiationEnum.平台审核.getName().equals(dataObject.getString("name"))) {
        }

        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(!ValidationUtil.isEmpty(objectd)) {
                problemInitiationService.sendSms(object, SMSEnum.项目立项驳回短信.getCode());
            }
        }

        if (ProjectInitiationEnum.告知申请.getName().equals(dataObject.getString("name"))) {
            if(!ValidationUtil.isEmpty(objectd)) {
                problemInitiationService.sendSms(object, SMSEnum.项目安装告知申请.getCode());
            }
        }

        if (ProjectInitiationEnum.项目关闭.getName().equals(dataObject.getString("name"))) {
            if(!ValidationUtil.isEmpty(objectd)) {
                problemInitiationService.sendSms(object, SMSEnum.项目立项驳回短信.getCode());
            }
        }


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

    /**
     * 获取流程当前任务名称
     * @param instanceId
     * @return
     */
    public String getFlowTaskName(String instanceId){
        AjaxResult ajaxResult = Workflow.taskClient.getTask(instanceId);
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(ajaxResult.get("data")));
        String taskName = "流程结束！";
        try {
            taskName=jsonObject.getString("name");
        }catch (Exception e) {}
        return taskName;
    }

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


}
