package com.ruoyi.project.intact.controller;

import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.project.approve.damain.DevTask;
import com.ruoyi.project.intact.domain.*;
import com.ruoyi.project.intact.mapper.TIntactApproveMapper;
import com.ruoyi.project.intact.service.*;
import com.ruoyi.project.listener.semsApprove.*;
import com.ruoyi.project.sems.domain.*;
import com.ruoyi.project.sems.mapper.TApproveMapper;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.history.HistoricTaskInstanceQuery;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.annotation.Resource;

/**
 * 设备完整性申请Controller
 *
 * @author ruoyi
 * @date 2022-06-24
 */
@RestController
@RequestMapping("/intact/approve")
public class TIntactApproveController extends BaseController
{
    @Autowired
    private ITIntactApproveService tIntactApproveService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private ITIntactGjService tIntactGjService;
    @Autowired
    private ITIntactGylService  tIntactGylService;
    @Autowired
    private ITIntactPumpService tIntactPumpService;
    @Autowired
    private ITIntactYsjService tIntactYsjService;
    @Autowired
    private TaskService taskService;
    @Resource
    private TIntactApproveMapper tIntactApproveMapper;
    @Autowired
    private ISysUserService sysUserService;
    /**
     * 查询设备完整性申请列表
     */
    @PreAuthorize("@ss.hasPermi('intact:approve:list')")
    @GetMapping("/list")
    public TableDataInfo list(TIntactApprove tIntactApprove)
    {
        startPage();
        List<TIntactApprove> list = tIntactApproveService.selectTIntactApproveList(tIntactApprove);
        return getDataTable(list);
    }

    /**
     * 历史申请列表
     */
    @RequestMapping("/hisApprovelist")
    public AjaxResult hisTintactApprovelist(@RequestParam Map<String, Object> params) {
        String sql = params.get("devId") + " in (SELECT REGEXP_SUBSTR (DEV_ID, '[^,]+', 1,rownum) from dual connect by rownum<=LENGTH (DEV_ID) - LENGTH (regexp_replace(DEV_ID, ',', ''))+1 )";
        List<TIntactApprove> list = tIntactApproveMapper.selectList(new QueryWrapper<TIntactApprove>().apply(sql).orderByDesc("CREATTIME")
        );
        for (TIntactApprove t : list
        ) {
            SysUser userEntity = sysUserService.selectUserById(t.getUserId());
            t.setUserName(userEntity.getNickName());
        }
        return AjaxResult.success(list);
    }


    /**
     * 导出设备完整性申请列表
     */
    @PreAuthorize("@ss.hasPermi('intact:approve:export')")
    @Log(title = "设备完整性申请", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TIntactApprove tIntactApprove)
    {
        List<TIntactApprove> list = tIntactApproveService.selectTIntactApproveList(tIntactApprove);
        ExcelUtil<TIntactApprove> util = new ExcelUtil<TIntactApprove>(TIntactApprove.class);
        return util.exportExcel(list, "approve");
    }

    /**
     * 获取设备完整性申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('intact:approve:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tIntactApproveService.selectTIntactApproveById(id));
    }

    /**
     * 新增设备完整性申请
     */

    @Log(title = "设备完整性申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TIntactApprove tIntactApprove)
    {
        logger.info(JSON.toJSONString(tIntactApprove));
        Long userid = getUserId();
        tIntactApprove.setUserId(userid);
        //审批编号
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String data = sdf.format(dt) + userid;
        tIntactApprove.setApNo(data);
        tIntactApproveService.insertTIntactApprove(tIntactApprove);
       /* if (tIntactApprove.getFiles().size() > 0) {
            for (TApproverFile t : tIntactApprove.getFiles()
            ) {
                t.setApproveId(tIntactApprove.getId());
                t.setFileType(1l);
                tIntactApproveService.save(t);
            }    设备变更提交文件，暂时不用
        }*/
        String[] ids = tIntactApprove.getDevId().split(",");
        switch (Integer.parseInt(tIntactApprove.getDevType().toString())) {
            case 1:
                for (String i : ids
                ) {
                    TIntactPump pumpEntity = tIntactPumpService.getById(i);
                    pumpEntity.setApproveStatus(tIntactApprove.getApproveType());
                    pumpEntity.setApproveTime(new Date());
                    tIntactPumpService.updateById(pumpEntity);
                }
                break;
            case 2:
                for (String i : ids
                ) {
                    TIntactGj gjEntity = tIntactGjService.getById(i);
                    gjEntity.setApproveStatus(tIntactApprove.getApproveType());
                    gjEntity.setApproveTime(new Date());
                    tIntactGjService.updateById(gjEntity);
                }
                break;
            case 3:
                for (String i : ids
                ) {
                    TIntactYsj ysjEntity = tIntactYsjService.getById(i);
                    ysjEntity.setApproveStatus(tIntactApprove.getApproveType());
                    ysjEntity.setApproveTime(new Date());
                    tIntactYsjService.updateById(ysjEntity);
                }
                break;
            case 4:
                for (String i : ids
                ) {
                    TIntactGyl gylEntity = tIntactGylService.getById(i);
                    gylEntity.setApproveStatus(tIntactApprove.getApproveType());
                    gylEntity.setApproveTime(new Date());
                    tIntactGylService.updateById(gylEntity);
                }
                break;

        }
        long bussniseeKey = tIntactApprove.getId();
        Authentication.setAuthenticatedUserId(userid.toString());
        //开始工作流、监听
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyUser", userid.toString());
        variables.put("gyzjusers", tIntactApprove.getGyzj().toString());
     /*   variables.put("specEndSucessListener", new SpecEndSucessListener());
        variables.put("specEndFaileListener", new SpecEndFaileListener());
        variables.put("gyzjTaskCreateListener", new GyzjTaskCreateListener());
        variables.put("ctmTaskCreateListener", new CtmTaskCreateListener());*/

        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("intactChangeApplicationProcess", String.valueOf(bussniseeKey), variables);
        logger.info("流程部署id：" + pi.getDeploymentId());
        logger.info("流程定义id：" + pi.getProcessDefinitionId());
        logger.info("流程实例id：" + pi.getProcessInstanceId());
        tIntactApprove.setProcessId(pi.getProcessInstanceId());
        tIntactApproveService.updateTIntactApprove(tIntactApprove);
        return AjaxResult.success();
    }

    /**
     * 任务详情
     */
    @RequestMapping("/info/{id}")
//    @RequiresPermissions("approve:tapprove:info")
    public AjaxResult info(@PathVariable("id") Long id) {
        TIntactApprove tIntactApprove = tIntactApproveService.selectTIntactApproveById(id);
      /*  List<TApproverFile> files = tApproverFileService.list(new QueryWrapper<TApproverFile>().eq("APPROVE_ID", id).eq("FILE_TYPE", 1));
        tApprove.setFiles(files);
        List<TApproverFile> govfiles = tApproverFileService.list(new QueryWrapper<TApproverFile>().eq("APPROVE_ID", id).eq("FILE_TYPE", 2));
        tApprove.setGovFiles(govfiles);*/
        String[] ids = null;
        if (tIntactApprove.getApproveType() == 7) {
            ids = tIntactApprove.getReportId().split(",");
        }else if (tIntactApprove.getApproveType() == 8) {
            ids = tIntactApprove.getMonthId().split(",");
        }else {
            ids = tIntactApprove.getDevId().split(",");
        }
        List<Object> devList = new ArrayList<>();
        if (tIntactApprove.getDevType() != null && tIntactApprove.getApproveType() != 7) {
            switch (Integer.parseInt(tIntactApprove.getDevType().toString())) {
                case 1:
                    for (String i : ids
                    ) {
                        TIntactPump pumpEntity = tIntactPumpService.getById(i);
                        devList.add(pumpEntity);
                    }
                    break;
                case 2:
                    for (String i : ids
                    ) {
                        TIntactGj gjEntity = tIntactGjService.getById(i);
                        devList.add(gjEntity);
                    }
                    break;
                case 3:
                    for (String i : ids
                    ) {
                        TIntactYsj dysjEntity = tIntactYsjService.getById(i);
                        devList.add(dysjEntity);
                    }
                    break;
                case 4:
                    for (String i : ids
                    ) {
                        TIntactGyl gylntity = tIntactGylService.getById(i);
                        devList.add(gylntity);
                    }
                    break;

            }
        }
      /*  switch (Integer.parseInt(tIntactApprove.getApproveType().toString())) {
            case 7:
                switch (tIntactApprove.getDevType().toString()) {
                    case "1":
                        for (String i : ids
                        ) {
                            TReportYlrq reportYlrqEntity = tReportYlrqService.selectTReportYlrqById(Long.parseLong(i));
                            reportYlrqEntity.setDevEntity(tSpecdevYlrqService.getById(reportYlrqEntity.getDevId()));
                            devList.add(reportYlrqEntity);
                        }
                        break;
                    case "2":
                        for (String i : ids
                        ) {
                            TReportYlgd reportYlgdEntity = tReportYlgdService.selectTReportYlgdById(Long.parseLong(i));
                            reportYlgdEntity.setDevEntity(tSpecdevYlgdService.getById(reportYlgdEntity.getDevId()));
                            devList.add(reportYlgdEntity);
                        }
                }
                break;
            case 8:
                for (String i : ids
                ) {
                    TReportMonth reportMonthEntity = tReportMonthService.selectTReportMonthById(Long.parseLong(i));
                    devList.add(reportMonthEntity);
                    tApprove.setDevType(0l);
                }
        }*/
        tIntactApprove.setDevList(devList);
        return AjaxResult.success(tIntactApprove);
    }

    /**
     * 审核处理
     */
    @Log(title = "设备完整性变更提交审核处理", businessType = BusinessType.UPDATE)
    @PutMapping("/handle")
    public AjaxResult handle(@RequestBody DevTask devTask) {
        Map<String, Object> param = new HashMap<>();
        //流程审批意见
        String symbol= "";
        if (devTask.getComment() != "") {
            symbol = "，";
        }
        if (devTask.getCondition().equals("1")) {
            /* devTask.setComment("通过" + symbol + devTask.getComment());*/
            devTask.setComment("批准" + symbol + devTask.getComment());
        }else if (devTask.getCondition().equals("0")) {
            devTask.setComment("未通过" + symbol + devTask.getComment());
        }
        //使用任务服务完成任务(提交任务)
        String taskId = devTask.getTaskId();
        // 使用任务id,获取任务对象，获取流程实例id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //利用任务对象，获取流程实例id
        String processInstancesId = task.getProcessInstanceId();
        System.out.println(processInstancesId);
        //年度报告申请检查人员会签判断
        if (task.getName().equals("工艺总监")) {
            //获取当前任务流转列表
            HistoricTaskInstanceQuery htiq = historyService.createHistoricTaskInstanceQuery();
            List<HistoricTaskInstance> htiLists = htiq.processInstanceId(processInstancesId).finished().orderByHistoricTaskInstanceEndTime().asc().list();
            List<DevTask> devTaskList = new ArrayList<>();
            if (htiLists.size() > 0) {
                for (HistoricTaskInstance hi : htiLists
                ) {
                    List<Comment> commentList = taskService.getTaskComments(hi.getId());
                    DevTask dev = new DevTask();
                    if (commentList.size() > 0) {
                        dev.setComment(commentList.get(0).getFullMessage());
                    }
                    devTaskList.add(dev);
                }
            }
            if (devTaskList.size() == 2) {
                for (DevTask d : devTaskList) {
                    if (d.getComment().substring(0, 1).equals("未")) {
                        devTask.setCondition("0");
                    }
                }
            }
        }
        param.put("condition", devTask.getCondition());
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        //认领任务
        processEngine.getTaskService()//
                .claim(taskId, getUserId().toString());
//        Authentication.setAuthenticatedUserId("cmc"); // 添加批注时候的审核人
        taskService.addComment(taskId, processInstancesId, devTask.getComment());
        //业务监听处理
//        tApproveService.handleApprove(task ,devTask);
        taskService.complete(taskId, param);

        //添加回执信息
        if (devTask.getGovFiles().size() > 0) {
            HistoricProcessInstance pi = processEngine.getHistoryService()
                    .createHistoricProcessInstanceQuery().processInstanceId(processInstancesId).singleResult();
            String approveId = pi.getBusinessKey();
            TIntactApprove approveEntity = tIntactApproveService.selectTIntactApproveById(Long.parseLong(approveId));
            approveEntity.setGovDate(devTask.getGovDate());
            tIntactApproveService.updateTIntactApprove(approveEntity);
           /* for (TApproverFile t : devTask.getGovFiles()
            ) {
                t.setApproveId(Long.parseLong(approveId));
                t.setFileType(2l);
                tApproverFileService.save(t);
            }*/
        }
        return AjaxResult.success();
    }

    /**
     * 修改设备完整性申请
     */
    @PreAuthorize("@ss.hasPermi('intact:approve:edit')")
    @Log(title = "设备完整性申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TIntactApprove tIntactApprove)
    {
        return toAjax(tIntactApproveService.updateTIntactApprove(tIntactApprove));
    }

    /**
     * 删除设备完整性申请
     */
    @PreAuthorize("@ss.hasPermi('intact:approve:remove')")
    @Log(title = "设备完整性申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tIntactApproveService.deleteTIntactApproveByIds(ids));
    }
}
