package com.ruoyi.project.sems.his.controller;

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

import com.alibaba.fastjson.JSON;
import com.ruoyi.project.approve.damain.DevTask;
import com.ruoyi.project.sems.domain.*;
import com.ruoyi.project.sems.his.domain.*;
import com.ruoyi.project.sems.his.service.*;
import com.ruoyi.project.sems.service.*;
import org.activiti.engine.*;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
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.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
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;

/**
 * 特种设备变更申请Controller
 *
 * @author ruoyi
 * @date 2021-09-02
 */
@RestController
@RequestMapping("sems/his/modify")
public class TApproveSpecModifyController extends BaseController
{
    @Autowired
    private ITApproveSpecModifyService tApproveSpecModifyService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private HistoryService historyService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ITSpecdevDtService tSpecdevDtService;
    @Autowired
    private ITSpecdevDzsbService tSpecdevDzsbService;
    @Autowired
    private ITSpecdevGlService tSpecdevGlService;
    @Autowired
    private ITSpecdevYlgdService tSpecdevYlgdService;
    @Autowired
    private ITSpecdevYlrqService tSpecdevYlrqService;
    @Autowired
    private ITSpecdevCcService tSpecdevCcService;
    @Autowired
    private ITApproverFileService tApproverFileService;
    @Autowired
    private ITSpechiYlrqService tSpechiYlrqService;
    @Autowired
    private ITSpechiYlgdService tSpechiYlgdService;
    @Autowired
    private ITSpechiGlService tSpechiGlService;
    @Autowired
    private ITSpechiDzsbService tSpechiDzsbService;
    @Autowired
    private ITSpechiCcService tSpechiCcService;
    @Autowired
    private ITSpechiDtService tSpechiDtService;

    @Autowired
    private ITSpecCheckService tSpecCheckService;
    /**
     * 查询特种设备变更申请列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TApproveSpecModify tApproveSpecModify)
    {
        startPage();
        List<TApproveSpecModify> list = tApproveSpecModifyService.selectTApproveSpecModifyList(tApproveSpecModify);
        return getDataTable(list);
    }

    /**
     * 导出特种设备变更申请列表
     */
    @Log(title = "特种设备变更申请", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TApproveSpecModify tApproveSpecModify)
    {
        List<TApproveSpecModify> list = tApproveSpecModifyService.selectTApproveSpecModifyList(tApproveSpecModify);
        ExcelUtil<TApproveSpecModify> util = new ExcelUtil<TApproveSpecModify>(TApproveSpecModify.class);
        return util.exportExcel(list, "modify");
    }

    /**
     * 获取特种设备变更申请详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tApproveSpecModifyService.selectTApproveSpecModifyById(id));
    }

    /**
     * 获取特种设备变更申请详细信息
     */
    @GetMapping(value = "info/{id}")
    public AjaxResult info(@PathVariable("id") Long id)
    {
        TApproveSpecModify tApprove = tApproveSpecModifyService.selectTApproveSpecModifyById(id);
        String[] ids;
        ids = tApprove.getDevId().split(",");
        List<Object> devList = new ArrayList<>();
        switch (Integer.parseInt(tApprove.getDevType().toString())) {
            case 1:
                for (String i : ids
                ) {
                    TSpecdevYlrq ylrqEntity = tSpecdevYlrqService.getById(i);
                    devList.add(ylrqEntity);
                }
                break;
            case 2:
                for (String i : ids
                ) {
                    TSpecdevYlgd ylgdEntity = tSpecdevYlgdService.getById(i);
                    devList.add(ylgdEntity);
                }
                break;
            case 3:
                for (String i : ids
                ) {
                    TSpecdevDzsb dzsbEntity = tSpecdevDzsbService.getById(i);
                    devList.add(dzsbEntity);
                }
                break;
            case 4:
                for (String i : ids
                ) {
                    TSpecdevGl glEntity = tSpecdevGlService.getById(i);
                    devList.add(glEntity);
                }
                break;
            case 5:
                for (String i : ids
                ) {
                    TSpecdevDt dtEntity = tSpecdevDtService.getById(i);
                    devList.add(dtEntity);
                }
                break;
            case 6:
                for (String i : ids
                ) {
                    TSpecdevCc ccEntity = tSpecdevCcService.getById(i);
                    devList.add(ccEntity);
                }
                break;
            case 7:
                for (String i : ids
                ) {
//                        TOtherTankEntity tankEntity = tOtherTankService.getById(i);
//                        devList.add(tankEntity);
                }
        }
        tApprove.setDevList(devList);
        return AjaxResult.success(tApprove);
    }

    /**
     * 新增特种设备变更申请
     */
    @Log(title = "特种设备变更申请", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TApproveSpecModify tApproveSpecModify)
    {
        Long userid = getUserId();
        tApproveSpecModify.setUserId(userid);
//        tApproveSpecModify.setApNo(tApproveSpecModify.getHisId().toString());
        //审批编号
        Date dt = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
        String data = sdf.format(dt) + userid;
        tApproveSpecModify.setApNo(data);
        //
        Authentication.setAuthenticatedUserId(userid.toString());
        tApproveSpecModifyService.insertTApproveSpecModify(tApproveSpecModify);
        long bussniseeKey = tApproveSpecModify.getId();
        String[] ids;
        ids = tApproveSpecModify.getDevId().split(",");
        switch (Integer.parseInt(tApproveSpecModify.getDevType().toString())){
            case 1:
                for (String i : ids
                ) {
                    TSpecdevYlrq ylrqEntity = tSpecdevYlrqService.getById(i);
                    ylrqEntity.setApproveStatus(tApproveSpecModify.getApproveType()+ 19);
                    ylrqEntity.setApproveTime(new Date());
                    tSpecdevYlrqService.updateById(ylrqEntity);
                }
                break;
            case 2:
                for (String i : ids
                ) {
                    TSpecdevYlgd ylgdEntity = tSpecdevYlgdService.getById(i);
                    ylgdEntity.setApproveStatus(tApproveSpecModify.getApproveType() + 19);
                    ylgdEntity.setApproveTime(new Date());
                    tSpecdevYlgdService.updateById(ylgdEntity);
                }
                break;
            case 3:
                for (String i : ids
                ) {
                    TSpecdevDzsb dzsbEntity = tSpecdevDzsbService.getById(i);
                    dzsbEntity.setApproveStatus(tApproveSpecModify.getApproveType()+ 19);
                    dzsbEntity.setApproveTime(new Date());
                    tSpecdevDzsbService.updateById(dzsbEntity);
                }
                break;
            case 4:
                for (String i : ids
                ) {
                    TSpecdevGl glEntity = tSpecdevGlService.getById(i);
                    glEntity.setApproveStatus(tApproveSpecModify.getApproveType()+ 19);
                    glEntity.setApproveTime(new Date());
                    tSpecdevGlService.updateById(glEntity);
                }
                break;
            case 5:
                for (String i : ids
                ) {
                    TSpecdevDt dtEntity = tSpecdevDtService.getById(i);
                    dtEntity.setApproveStatus(tApproveSpecModify.getApproveType()+ 19);
                    dtEntity.setApproveTime(new Date());
                    tSpecdevDtService.updateById(dtEntity);
                }
                break;
            case 6:
                for (String i : ids
                ) {
                    TSpecdevCc ccEntity = tSpecdevCcService.getById(i);
                    ccEntity.setApproveStatus(tApproveSpecModify.getApproveType()+ 19);
                    ccEntity.setApproveTime(new Date());
                    tSpecdevCcService.updateById(ccEntity);
                }
                break;
    }
        //开始工作流、监听
        Map<String, Object> variables = new HashMap<>();
        variables.put("applyUser", userid.toString());
        variables.put("wxjlusers", tApproveSpecModify.getWxjl());
        //采用key来启动流程定义并设置流程变量，返回流程实例
        ProcessInstance pi = runtimeService.startProcessInstanceByKey("modifySpecProcess", String.valueOf(bussniseeKey), variables);
        logger.info("流程部署id：" + pi.getDeploymentId());
        logger.info("流程定义id：" + pi.getProcessDefinitionId());
        logger.info("流程实例id：" + pi.getProcessInstanceId());
        tApproveSpecModify.setProcessId(pi.getProcessInstanceId());
        return AjaxResult.success();
    }

    /**
     * 审核处理
     */
    @Log(title = "特种设备审核处理", businessType = BusinessType.UPDATE)
    @PutMapping("/handle")
    public AjaxResult handle(@RequestBody DevTask devTask) {
        //流程审批意见
        String symbol= "";
        if (devTask.getComment() != "") {
            symbol = "，";
        }
        //使用任务服务完成任务(提交任务)
        String taskId = devTask.getTaskId();
        // 使用任务id,获取任务对象，获取流程实例id
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        //利用任务对象，获取流程实例id
        String processInstancesId = task.getProcessInstanceId();
        TApproveSpecModify tApproveSpecModify = tApproveSpecModifyService.selectTApproveSpecModifyById(Long.parseLong(devTask.getBusinessKey()));
        if (devTask.getCondition().equals("1")) {
            devTask.setComment("通过" + symbol + devTask.getComment());
            String[] ids;
            ids = tApproveSpecModify.getDevId().split(",");
            switch (Integer.parseInt(tApproveSpecModify.getDevType().toString())){
                case 1://修改压力容器台账
                    for (String i : ids
                    ) {
                        TSpecdevYlrq ylrqEntity = tSpecdevYlrqService.getById(i);
                        ylrqEntity.setApproveStatus(0l);
                        tSpecdevYlrqService.updateById(ylrqEntity);
                        //修改
                        TSpecCheck tc = new TSpecCheck();
                        tc.setDevType(1l);
                        tc.setCheckUnit(ylrqEntity.getCheckUnit());
                        tc.setDevId(ylrqEntity.getId());
                        tc.setNextWarnDate(ylrqEntity.getNextWarnDate());
                        tc.setReportNo(ylrqEntity.getReportNo());
                        tc.setWarnDate(ylrqEntity.getWarnDate());
                        tc.setYearNextWarnDate(ylrqEntity.getYearNextWarnDate());
                        tc.setYearWarnDate(ylrqEntity.getYearWarnDate());
                        tc.setYearReportNo(ylrqEntity.getReportNo());
                        tc.setSafeClass(ylrqEntity.getSafeClass());
                        tSpecCheckService.insertTSpecCheck(tc);

                        if (tApproveSpecModify.getApproveType() == 1) {
                            logger.info(JSON.toJSONString(tApproveSpecModify));
                            TSpechiYlrq hientity = tSpechiYlrqService.selectTSpechiYlrqById(Long.parseLong(tApproveSpecModify.getDevId()));
                            logger.info(JSON.toJSONString(hientity));
                            tSpecdevYlrqService.updateTSpecdevYlrqByHi(hientity);
                        }else {
                            tSpecdevYlrqService.deleteTSpecdevYlrqById(Long.parseLong(i));
                        }
                    }
                    break;
                case 2://修改压力管道台账
                    for (String i : ids
                    ) {
                        TSpecdevYlgd ylgdEntity = tSpecdevYlgdService.getById(i);
                        ylgdEntity.setApproveStatus(0l);
                        tSpecdevYlgdService.updateById(ylgdEntity);
                        //修改
                        TSpecCheck tc = new TSpecCheck();
                        tc.setDevType(2l);
                        tc.setCheckUnit(ylgdEntity.getCheckUnit());
                        tc.setDevId(ylgdEntity.getId());
                        tc.setNextWarnDate(ylgdEntity.getNextWarnDate());
                        tc.setReportNo(ylgdEntity.getReportNo());
                        tc.setWarnDate(ylgdEntity.getWarnDate());
                        tc.setYearNextWarnDate(ylgdEntity.getYearNextWarnDate());
                        tc.setYearWarnDate(ylgdEntity.getYearWarnDate());
                        tc.setYearReportNo(ylgdEntity.getReportNo());
                        tc.setSafeClass(ylgdEntity.getSafeClass());
                        tSpecCheckService.insertTSpecCheck(tc);
                        if (tApproveSpecModify.getApproveType() == 1) {
                            TSpechiYlgd hientity = tSpechiYlgdService.selectTSpechiYlgdById(Long.parseLong(tApproveSpecModify.getDevId()));
                            tSpecdevYlgdService.updateTSpecdevYlgdByHi(hientity);
                        }else {
                            tSpecdevYlgdService.deleteTSpecdevYlgdById(Long.parseLong(i));
                        }
                    }
                    break;
                case 3://修改吊装设备台账
                    for (String i : ids
                    ) {
                        TSpecdevDzsb dzsbEntity = tSpecdevDzsbService.getById(i);
                        dzsbEntity.setApproveStatus(0l);
                        tSpecdevDzsbService.updateById(dzsbEntity);
                        TSpecCheck tc = new TSpecCheck();
                        tc.setDevType(3l);
                        tc.setCheckUnit(dzsbEntity.getCheckUnit());
                        tc.setDevId(dzsbEntity.getId());
                        tc.setNextWarnDate(dzsbEntity.getNextWarnDate());
                        tc.setReportNo(dzsbEntity.getReportNo());
                        tc.setWarnDate(dzsbEntity.getWarnDate());
                        tSpecCheckService.insertTSpecCheck(tc);
                        if (tApproveSpecModify.getApproveType() == 1){
                            TSpechiDzsb hientity = tSpechiDzsbService.selectTSpechiDzsbById(Long.parseLong(tApproveSpecModify.getDevId()));
                            tSpecdevDzsbService.updateTSpecdevDzsbByHi(hientity);
                        } else {
                            tSpecdevDzsbService.deleteTSpecdevDzsbById(Long.parseLong(i));
                        }
                    }
                    break;
                case 4://修改锅炉台账
                    for (String i : ids
                    ) {
                        TSpecdevGl glEntity = tSpecdevGlService.getById(i);
                        glEntity.setApproveStatus(0l);
                        tSpecdevGlService.updateById(glEntity);
                        TSpecCheck tc = new TSpecCheck();
                        tc.setDevType(4l);
                        tc.setCheckUnit(glEntity.getCheckUnit());
                        tc.setDevId(glEntity.getId());
                        tc.setNextWarnDate(glEntity.getNextWarnDate());
                        tc.setReportNo(glEntity.getReportNo());
                        tc.setWarnDate(glEntity.getWarnDate());
                        tc.setOutWarnDate(glEntity.getOutWarnDate());
                        tc.setOutReportNo(glEntity.getOutReportNo());
                        tc.setOutCheckConclusion(glEntity.getOutCheckConclusion());
                        tc.setOutNextWarnDate(glEntity.getOutNextWarnDate());
                        tSpecCheckService.insertTSpecCheck(tc);
                        if (tApproveSpecModify.getApproveType() == 1){
                            TSpechiGl hientity = tSpechiGlService.selectTSpechiGlById(Long.parseLong(tApproveSpecModify.getDevId()));
                            tSpecdevGlService.updateTSpecdevGlByHi(hientity);
                        } else {
                            tSpecdevGlService.deleteTSpecdevGlById(Long.parseLong(i));
                        }
                    }
                    break;
                case 5://修改电梯台账
                    for (String i : ids
                    ) {
                        TSpecdevDt dtEntity = tSpecdevDtService.getById(i);
                        dtEntity.setApproveStatus(0l);
                        tSpecdevDtService.updateById(dtEntity);
                        TSpecCheck tc = new TSpecCheck();
                        tc.setDevType(5l);
                        tc.setCheckUnit(dtEntity.getCheckUnit());
                        tc.setDevId(dtEntity.getId());
                        tc.setNextWarnDate(dtEntity.getNextWarnDate());
                        tc.setReportNo(dtEntity.getReportNo());
                        tc.setWarnDate(dtEntity.getWarnDate());
                        tSpecCheckService.insertTSpecCheck(tc);
                        if (tApproveSpecModify.getApproveType() == 1){
                            TSpechiDt hientity = tSpechiDtService.selectTSpechiDtById(Long.parseLong(tApproveSpecModify.getDevId()));
                            tSpecdevDtService.updateTSpecdevDtByHi(hientity);
                        } else {
                            tSpecdevDtService.deleteTSpecdevDtById(Long.parseLong(i));
                        }
                    }
                    break;
                case 6://修改叉车台账
                    for (String i : ids
                    ) {
                        TSpecdevCc ccEntity = tSpecdevCcService.getById(i);
                        ccEntity.setApproveStatus(0l);
                        tSpecdevCcService.updateById(ccEntity);
                        TSpecCheck tc = new TSpecCheck();
                        tc.setDevType(6l);
                        tc.setCheckUnit(ccEntity.getCheckUnit());
                        tc.setDevId(ccEntity.getId());
                        tc.setNextWarnDate(ccEntity.getNextWarnDate());
                        tc.setReportNo(ccEntity.getReportNo());
                        tc.setWarnDate(ccEntity.getWarnDate());
                        tSpecCheckService.insertTSpecCheck(tc);
                        if (tApproveSpecModify.getApproveType() == 1){
                            TSpechiCc hientity = tSpechiCcService.selectTSpechiCcById(Long.parseLong(tApproveSpecModify.getDevId()));
                            tSpecdevCcService.updateTSpecdevCcByHi(hientity);
                        } else {
                            tSpecdevCcService.deleteTSpecdevCcById(Long.parseLong(i));
                        }
                    }
                    break;
            }
        }else if (devTask.getCondition().equals("0")) {
            devTask.setComment("未通过" + symbol + devTask.getComment());
            String[] ids;
            ids = tApproveSpecModify.getDevId().split(",");
            switch (Integer.parseInt(tApproveSpecModify.getDevType().toString())){
                case 1:
                    for (String i : ids
                    ) {
                        TSpecdevYlrq ylrqEntity = tSpecdevYlrqService.getById(i);
                        ylrqEntity.setApproveStatus(0l);
                        tSpecdevYlrqService.updateById(ylrqEntity);
                    }
                    break;
                case 2:
                    for (String i : ids
                    ) {
                        TSpecdevYlgd ylgdEntity = tSpecdevYlgdService.getById(i);
                        ylgdEntity.setApproveStatus(0l);
                        tSpecdevYlgdService.updateById(ylgdEntity);
                    }
                    break;
                case 3:
                    for (String i : ids
                    ) {
                        TSpecdevDzsb dzsbEntity = tSpecdevDzsbService.getById(i);
                        dzsbEntity.setApproveStatus(0l);
                        tSpecdevDzsbService.updateById(dzsbEntity);
                    }
                    break;
                case 4:
                    for (String i : ids
                    ) {
                        TSpecdevGl glEntity = tSpecdevGlService.getById(i);
                        glEntity.setApproveStatus(0l);
                        tSpecdevGlService.updateById(glEntity);
                    }
                    break;
                case 5:
                    for (String i : ids
                    ) {
                        TSpecdevDt dtEntity = tSpecdevDtService.getById(i);
                        dtEntity.setApproveStatus(0l);
                        tSpecdevDtService.updateById(dtEntity);
                    }
                    break;
                case 6:
                    for (String i : ids
                    ) {
                        TSpecdevCc ccEntity = tSpecdevCcService.getById(i);
                        ccEntity.setApproveStatus(0l);
                        tSpecdevCcService.updateById(ccEntity);
                    }
                    break;
            }
        }
        System.out.println(processInstancesId);
        Map<String, Object> param = new HashMap<>();
        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);
     return AjaxResult.success();
    }

    /**
     * 修改特种设备变更申请
     */
    @Log(title = "特种设备变更申请", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TApproveSpecModify tApproveSpecModify)
    {
        return toAjax(tApproveSpecModifyService.updateTApproveSpecModify(tApproveSpecModify));
    }

    /**
     * 删除特种设备变更申请
     */
    @PreAuthorize("@ss.hasPermi('his:modify:remove')")
    @Log(title = "特种设备变更申请", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tApproveSpecModifyService.deleteTApproveSpecModifyByIds(ids));
    }
}
