package com.ruoyi.project.approve.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.http.HttpContextUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
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.framework.web.page.TableDataInfo;
import com.ruoyi.project.apply.domain.TApplyOfflinevalve;
import com.ruoyi.project.apply.domain.TApplySafetychange;
import com.ruoyi.project.apply.service.ITApplyOfflinevalveService;
import com.ruoyi.project.apply.service.ITApplySafetychangeService;
import com.ruoyi.project.approve.damain.DevProcess;
import com.ruoyi.project.approve.damain.DevTask;
import com.ruoyi.project.common.service.ITCommonfileService;
import com.ruoyi.project.ehs.domain.TApproveAccident;
import com.ruoyi.project.ehs.domain.TApproveDanger;
import com.ruoyi.project.ehs.service.ITApproveAccidentService;
import com.ruoyi.project.ehs.service.ITApproveDangerService;
import com.ruoyi.project.intact.domain.TApproveMaintenance;
import com.ruoyi.project.intact.domain.TIntactApprove;
import com.ruoyi.project.intact.service.ITApproveMaintenanceService;
import com.ruoyi.project.intact.service.ITIntactApproveService;
import com.ruoyi.project.invoice.domain.TApproveReserveInvoice;
import com.ruoyi.project.invoice.service.ITApproveReserveInvoiceService;
import com.ruoyi.project.listener.EndSucessListener;
import com.ruoyi.project.listener.ExecutorTaskCreateListener;
import com.ruoyi.project.listener.RecorderTaskCreateListener;
import com.ruoyi.project.listener.VerificationTaskCreateListener;
import com.ruoyi.project.production.domain.TSaiApply;
import com.ruoyi.project.production.service.ITSaiApplyService;
import com.ruoyi.project.pssr.domain.TPssrApprove;
import com.ruoyi.project.pssr.service.ITPssrApproveService;
import com.ruoyi.project.reliability.domain.TKekaoApprove;
import com.ruoyi.project.reliability.service.ITKekaoApproveService;
import com.ruoyi.project.sems.domain.TApprove;
import com.ruoyi.project.sems.his.domain.TApproveSpecModify;
import com.ruoyi.project.sems.his.service.ITApproveSpecModifyService;
import com.ruoyi.project.sems.safecheck.domain.TSpecWeekcheck;
import com.ruoyi.project.sems.safecheck.service.ITSpecWeekcheckService;
import com.ruoyi.project.sems.service.ITApproveService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.domain.SysUserRole;
import com.ruoyi.project.system.service.ISysUserService;
import com.ruoyi.project.training.bccnew.domain.TTsApprove;
import com.ruoyi.project.training.bccnew.service.ITTsApproveService;
import com.ruoyi.project.training.spec.domain.TStApprove;
import com.ruoyi.project.training.spec.service.ITStApproveService;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.FlowNode;
import org.activiti.bpmn.model.Process;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
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.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.runtime.ProcessInstanceQuery;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 隐患申请Controller
 *
 * @author ruoyi
 * @date 2021-02-20
 */
@RestController
@RequestMapping("/approve")
public class TApproveController extends BaseController {
    @Autowired
    private ITApproveDangerService tApproveDangerService;

    @Autowired
    private ITApproveAccidentService tApproveAccidentService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ITCommonfileService tCommonfileService;
    @Autowired
    private ITApproveService tApproveService;
    @Autowired
    private ITApproveSpecModifyService tApproveSpecModifyService;
    @Autowired
    private ITStApproveService tStApproveService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ITApproveMaintenanceService tApproveMaintenanceService;
    @Autowired
    private ITIntactApproveService tIntactApproveService;
    @Autowired
    private ITKekaoApproveService tKekaoApproveService;
    @Autowired
    private ITApproveReserveInvoiceService tApproveReserveInvoiceService;

    @Autowired
    private ITApplyOfflinevalveService tApplyOfflinevalveService;

    @Autowired
    private ITApplySafetychangeService tApplySafetychangeService;

    @Autowired
    private ITSaiApplyService tSaiApplyService;
    @Autowired
    private ITSpecWeekcheckService tSpecWeekcheckService;
    @Autowired
    private ITTsApproveService tTsApproveService;
    @Autowired
    private ITPssrApproveService tPssrApproveService;



    /**
     * 我的申请列表
     */
    @GetMapping("/unfinishedApproveList")
    public TableDataInfo approvelist(@RequestParam Map<String, Object> params) {
        // 初始化流程引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        // 创建流程实例查询
        ProcessInstanceQuery query = processEngine.getRuntimeService().createProcessInstanceQuery();
        String[] array = {"myProcess", "semsAddDelProcess", "yearProcess", "monthProcess", "yearProcess", "semsWeekcheck"};
        List<String> processInstanceIds = new ArrayList<>(Arrays.asList(array));

        // 查询未结束的流程实例
        List<HistoricProcessInstance> historicProcessInstanceList =
                historyService.createHistoricProcessInstanceQuery().unfinished().processDefinitionKeyIn(processInstanceIds)
                       .orderByProcessInstanceStartTime().desc()//参与者，组任务查询
                        .listPage(PageUtils.getStart(params), Integer.parseInt((String) params.get("pageSize")));
        Long count = historyService.createHistoricProcessInstanceQuery().unfinished().processDefinitionKeyIn(processInstanceIds)
                .count();
        logger.info(JSON.toJSONString(historicProcessInstanceList));
        //整合我的申请数据
        // 打印未结束的流程实例信息
        for (HistoricProcessInstance instance : historicProcessInstanceList) {
            System.out.println("流程实例ID: " + instance.getId());
            System.out.println("流程定义ID: " + instance.getProcessDefinitionId());
            System.out.println("流程实例启动时间: " + instance.getStartTime());
        }
        //整合我的申请数据
        List<DevProcess> list = new ArrayList<>();
        if (historicProcessInstanceList.size() > 0)
            for (HistoricProcessInstance h : historicProcessInstanceList
            ) {
                HistoricProcessInstance pi = processEngine.getHistoryService()
                        .createHistoricProcessInstanceQuery().processInstanceId(h.getId()).singleResult();
                logger.info(JSON.toJSONString(pi));
                if (pi == null) {
                    continue;
                }
                DevProcess devProcess = new DevProcess();
                logger.info("审批类型" + pi.getProcessDefinitionName());
                try {
                    if (pi.getProcessDefinitionName().equals("特种设备审核")) {
                        TApprove approve = tApproveService.selectTApproveById(Long.parseLong(h.getBusinessKey()));
                        devProcess.setSpecApprove(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("年度检查报告申请")) {
                        TApprove approve = tApproveService.selectTApproveById(Long.parseLong(h.getBusinessKey()));
                        devProcess.setSpecApprove(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("月度检查")) {
                        TApprove approve = tApproveService.selectTApproveById(Long.parseLong(h.getBusinessKey()));
                        devProcess.setSpecApprove(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("设备修改/删除审核") || pi.getProcessDefinitionName().equals("设备新增/删除审核")) {
                        TApproveSpecModify approve = tApproveSpecModifyService.selectTApproveSpecModifyById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveSpecModify(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("事件审批流程")) {
                        TApproveDanger approveDanger = tApproveDangerService.selectTApproveDangerById(Long.parseLong(h.getBusinessKey()));
                        devProcess.settApprove(approveDanger);
                        devProcess.setApNo(approveDanger.getApproveNo());
                    } else if (pi.getProcessDefinitionName().equals("重大隐患审批流程") || pi.getProcessDefinitionName().equals("普通隐患审批流程")) {
                        TApproveDanger approveDanger = tApproveDangerService.selectTApproveDangerById(Long.parseLong(h.getBusinessKey()));
                        devProcess.settApprove(approveDanger);
                        devProcess.setApNo(approveDanger.getApproveNo());
                    } else if (pi.getProcessDefinitionName().equals("专项培训计划审核")) {
                        TStApprove approve = tStApproveService.selectTStApproveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("设备维修审批流程")) {
                        TApproveMaintenance approve = tApproveMaintenanceService.selectTApproveMaintenanceById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("设备变更申请")) {
                        TIntactApprove approve = tIntactApproveService.selectTIntactApproveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("可靠性管理申请")) {
                        TKekaoApprove approve = tKekaoApproveService.selectTKekaoApproveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("预约开票审批流程")) {
                        TApproveReserveInvoice approve = tApproveReserveInvoiceService.selectTApproveReserveInvoiceById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("安全阀离线/切出申请流程")) {
                        TApplyOfflinevalve approve = tApplyOfflinevalveService.selectTApplyOfflinevalveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("组织保护措施状态变更申请流程")) {
                        TApplySafetychange approve = tApplySafetychangeService.selectTApplySafetychangeById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    } else if (pi.getProcessDefinitionName().equals("SAI开项申请流程")) {
                        TSaiApply approve = tSaiApplyService.selectTSaiApplyById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApproveObject(approve);
                        devProcess.setApNo(approve.getApNo());
                    }else if (pi.getProcessDefinitionName().equals("每周安全排查报告")) {
                        TSpecWeekcheck t = tSpecWeekcheckService.selectTSpecWeekcheckById(Long.parseLong(pi.getBusinessKey()));
                        SysUser user = sysUserService.selectUserById(Long.valueOf(t.getCreaterCode()));
                        devProcess.setApNo(t.getId().toString());
                        devProcess.setApName(user.getNickName());
                        devProcess.setApproveObject(t);
                    }else if (pi.getProcessDefinitionName().equals("导师带徒经理审批")) {
                        TTsApprove t = tTsApproveService.selectTTsApproveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApNo(t.getApNo());
                        devProcess.setApproveObject(t);
                    }else if (pi.getProcessDefinitionName().equals("导师带徒学员成绩不合格审批")) {
                        TTsApprove t = tTsApproveService.selectTTsApproveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApNo(t.getApNo());
                        devProcess.setApproveObject(t);
                    } else if (pi.getProcessDefinitionName().contains("PSSR")) {
                        TPssrApprove t = tPssrApproveService.selectTPssrApproveById(Long.parseLong(pi.getBusinessKey()));
                        devProcess.setApNo(t.getApNo());
                        devProcess.setApproveObject(t);
                    }
                } catch (Exception e) {
                    logger.error(e.toString());
                }
                devProcess.setBusinessKey(pi.getBusinessKey());
                devProcess.setProcessCreateTime(pi.getStartTime());
                devProcess.setProcessId(pi.getId());
                devProcess.setProcessName(pi.getProcessDefinitionName());

                if (pi.getEndActivityId() != null) {
                    devProcess.setEnd(true);
                } else {
                    devProcess.setEnd(false);
                }
                logger.info("devProcess:" + devProcess);
                list.add(devProcess);
            }
        return getDataTable(list , count);
    }

    /**
     * 中止任务
     */
    @RequestMapping("/cancelApprove/{id}")
    public AjaxResult info(@PathVariable("id") Long id) {
        Task currentTask = taskService.createTaskQuery().processInstanceId(id.toString()).singleResult();

        Map<String, Object> param = new HashMap<>();
        param.put("condition", "0");
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        TaskService taskService = processEngine.getTaskService();
        //认领任务
        taskService.setAssignee(currentTask.getId(), getUserId().toString());
//        processEngine.getTaskService()//
//                .claim(currentTask.getId(), getUserId().toString());
//        Authentication.setAuthenticatedUserId("cmc"); // 添加批注时候的审核人
        taskService.addComment(currentTask.getId(), id.toString(), "中止");
        //业务监听处理
//        tApproveService.handleApprove(task ,devTask);
        taskService.complete(currentTask.getId(), param);
// 移动到最后一个节点，这里假设最后一个节点的ID是 "endEvent"
//        runtimeService.createChangeActivityStateBuilder()
//                .processInstanceId(processInstanceId)
//                .moveActivityIdTo("endEvent")
//                .changeState();

        return AjaxResult.success();
    }


}
