package com.ruoyi.project.reliability.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.ITIntactGjService;
import com.ruoyi.project.intact.service.ITIntactGylService;
import com.ruoyi.project.intact.service.ITIntactPumpService;
import com.ruoyi.project.intact.service.ITIntactYsjService;
import com.ruoyi.project.reliability.domain.TKekaoMgList;
import com.ruoyi.project.reliability.mapper.TKekaoApproveMapper;
import com.ruoyi.project.reliability.service.ITKekaoMgListService;
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.project.reliability.domain.TKekaoApprove;
import com.ruoyi.project.reliability.service.ITKekaoApproveService;
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-07-08
 */
@RestController
@RequestMapping("/reliability/approve")
public class TKekaoApproveController extends BaseController
{
    @Autowired
    private ITKekaoApproveService tKekaoApproveService;

    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ITKekaoMgListService itKekaoMgListService;
    @Resource
    private TKekaoApproveMapper tKekaoApproveMapper;
    @Autowired
    private ISysUserService sysUserService;
    /**
     * 查询可靠性管理申请列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:approve:list')")
    @GetMapping("/list")
    public TableDataInfo list(TKekaoApprove tKekaoApprove)
    {
        startPage();
        List<TKekaoApprove> list = tKekaoApproveService.selectTKekaoApproveList(tKekaoApprove);
        return getDataTable(list);
    }

    /**
     * 历史申请列表
     */
    @RequestMapping("/hisApprovelist")
    public AjaxResult hisTKekaoApprovelist(@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<TKekaoApprove> list = tKekaoApproveMapper.selectList(new QueryWrapper<TKekaoApprove>().apply(sql).orderByDesc("CREATTIME")
        );
        for (TKekaoApprove t : list
        ) {
            SysUser userEntity = sysUserService.selectUserById(t.getUserId());
            t.setUserName(userEntity.getNickName());
        }
        return AjaxResult.success(list);
    }


    /**
     * 导出可靠性管理申请列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:approve:export')")
    @Log(title = "可靠性管理申请", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TKekaoApprove tKekaoApprove)
    {
        List<TKekaoApprove> list = tKekaoApproveService.selectTKekaoApproveList(tKekaoApprove);
        ExcelUtil<TKekaoApprove> util = new ExcelUtil<TKekaoApprove>(TKekaoApprove.class);
        return util.exportExcel(list, "approve");
    }

    /**
     * 获取可靠性管理申请详细信息
     */
    @PreAuthorize("@ss.hasPermi('reliability:approve:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tKekaoApproveService.selectTKekaoApproveById(id));
    }

    /**
     * 新增可靠性管理申请
     */
    @PreAuthorize("@ss.hasPermi('reliability:approve:add')")
    @Log(title = "可靠性管理申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TKekaoApprove tKekaoApprove)
    {
        logger.info(JSON.toJSONString(tKekaoApprove));
        Long userid = getUserId();
        tKekaoApprove.setUserId(userid);
        //审批编号
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String data = sdf.format(dt) + userid;
        tKekaoApprove.setApNo(data);
        tKekaoApproveService.insertTKekaoApprove(tKekaoApprove);

        //申请的设备id  直接作为 可靠性清单实体的id主键来查询
        String[] ids = tKekaoApprove.getDevId().split(",");
        for (String i : ids
        ) {
            TKekaoMgList tKekaoMgList = itKekaoMgListService.getById(i);
            tKekaoMgList.setApproveStatus(tKekaoApprove.getApproveType());
            tKekaoMgList.setImplementDate(new Date());
            itKekaoMgListService.updateById(tKekaoMgList);
        }

        long bussniseeKey = tKekaoApprove.getId();
        Authentication.setAuthenticatedUserId(userid.toString());
        //开始工作流、监听
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyUser", userid.toString());
        variables.put("kkxjl", tKekaoApprove.getKkxjl().toString());

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

    /**
     * 任务详情
     */
    @RequestMapping("/info/{id}")
//    @RequiresPermissions("approve:tapprove:info")
    public AjaxResult info(@PathVariable("id") Long id) {
        TKekaoApprove tKekaoApprove = tKekaoApproveService.selectTKekaoApproveById(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 (tKekaoApprove.getApproveType() == 7) {
            ids = tKekaoApprove.getReportId().split(",");
        }else if (tKekaoApprove.getApproveType() == 8) {
            ids = tKekaoApprove.getMonthId().split(",");
        }else {
            ids = tKekaoApprove.getDevId().split(",");
        }
        List<Object> devList = new ArrayList<>();
        if (tKekaoApprove.getDevType() != null && tKekaoApprove.getApproveType() != 7) {
            for (String i : ids
            ) {
                TKekaoMgList tKekaoMgList = itKekaoMgListService.getById(i);
                devList.add(tKekaoMgList);
            }

        }

        tKekaoApprove.setDevList(devList);
        return AjaxResult.success(tKekaoApprove);
    }

    /**
     * 审核处理
     */
    @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();
            TKekaoApprove approveEntity = tKekaoApproveService.selectTKekaoApproveById(Long.parseLong(approveId));
            approveEntity.setGovDate(devTask.getGovDate());
            tKekaoApproveService.updateTKekaoApprove(approveEntity);
           /* for (TApproverFile t : devTask.getGovFiles()
            ) {
                t.setApproveId(Long.parseLong(approveId));
                t.setFileType(2l);
                tApproverFileService.save(t);
            }*/
        }
        return AjaxResult.success();
    }

    /**
     * 修改可靠性管理申请
     */
    @PreAuthorize("@ss.hasPermi('reliability:approve:edit')")
    @Log(title = "可靠性管理申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TKekaoApprove tKekaoApprove)
    {
        return toAjax(tKekaoApproveService.updateTKekaoApprove(tKekaoApprove));
    }

    /**
     * 删除可靠性管理申请
     */
    @PreAuthorize("@ss.hasPermi('reliability:approve:remove')")
    @Log(title = "可靠性管理申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tKekaoApproveService.deleteTKekaoApproveByIds(ids));
    }
}
