package com.ruoyi.project.pssr.controller;

import com.ruoyi.common.utils.StringUtils;
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.listener.pssr.ConfirmTaskCreateListener;
import com.ruoyi.project.pssr.domain.*;
import com.ruoyi.project.pssr.mapper.TPssrOverhaulPumpMapper;
import com.ruoyi.project.pssr.service.*;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

/**
 * 检修项目-泵Controller
 *
 * @author ssy
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/pssr/overhaulPump")
public class TPssrOverhaulPumpController extends BaseController {
    @Resource
    private TPssrOverhaulPumpMapper tPssrOverhaulPumpMapper;
    @Autowired
    private ITPssrFileService tPssrFileService;

    @Autowired
    private ITPssrTurndownService tPssrTurndownService;
    @Autowired
    private ITPssrOverhaulPumpService tPssrOverhaulPumpService;

    @Autowired
    private ITPssrOverhaulExchangerService tPssrOverhaulExchangerService;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;
    private String forShort = "jxxm-b";


    @PutMapping("/turnDownPump")
    public AjaxResult turnDownPump(@RequestBody List<TPssrOverhaulPump> tPssrOverhaulPump) {
        if (CollectionUtils.isNotEmpty(tPssrOverhaulPump)) {
            String userId = getUserId().toString();
            Long subId = tPssrOverhaulPump.get(0).getSubId();
            // 修改已选择数据的状态
            for (TPssrOverhaulPump item : tPssrOverhaulPump) {
                TPssrOverhaulPump blind = new TPssrOverhaulPump();
                blind.setId(item.getId());
                blind.setApproveStatus(1L);
                blind.setUpdatedate(new Date());
                blind.setUpdaterCode(getUserId().toString());
                tPssrOverhaulPumpService.updateTPssrOverhaulPump(blind);
                // 新增驳回原因数据
                TPssrTurndown turndown = new TPssrTurndown();
                turndown.setForShort(forShort);
                turndown.setSubId(item.getSubId());
                turndown.setItemId(item.getId());
                turndown.setReason(item.getReason());
                turndown.setCreatedate(new Date());
                turndown.setCreaterCode(getUserId().toString());
                tPssrTurndownService.insertTPssrTurndown(turndown);
            }
            // 查询当前流程
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(subId);

            try {
                runtimeService.deleteProcessInstance(approve.getProcessId(), "pssr1confirm");
                historyService.deleteHistoricProcessInstance(approve.getProcessId());
            } catch (Exception e) {
                logger.info("无运行时流程");
            }


            // 驳回 查询所有待审批的人员

            //查询所有确认人
            TPssrOverhaulExchanger exchanger = new TPssrOverhaulExchanger();
            exchanger.setSubId(approve.getSubId());
            exchanger.setApproveStatus(1L);
            TPssrOverhaulExchanger overhaul = tPssrOverhaulExchangerService.selectAllConfirmedPersonBySubId(exchanger);
            String confirmers = null;
            if (overhaul != null) {
                confirmers = overhaul.getConfirmedPerson();
            }
            logger.info("=======================confirmers:{}", confirmers);

            Set<String> confirmUsers1 = new HashSet<>();
            if (StringUtils.isNotEmpty(confirmers)) {
                confirmUsers1.addAll(Arrays.asList(confirmers.split(",")));
            }

            // 开始申请流程
            long businessKey = approve.getApproveId();
            //开始工作流、监听
            Authentication.setAuthenticatedUserId(userId);//设置当前申请人
            Map<String, Object> variables = new HashMap<>();
            variables.put("applyUser", userId);
            variables.put("confirmUsers", new ArrayList<>(confirmUsers1));
            variables.put("confirmTaskCreateListener", new ConfirmTaskCreateListener());//发送邮件
            variables.put("chargePerson", approve.getSubCharge());
            //采用key来启动流程定义并设置流程变量，返回流程实例
            ProcessInstance pi = runtimeService.startProcessInstanceByKey("pssr1confirm", String.valueOf(businessKey), variables);

            // 修改审批表和sub表
            approve.setProcessId(pi.getProcessInstanceId());
            approve.setApproveStatus(1L);
            approve.setUpdatedate(new Date());
            approve.setUpdaterCode(getUserId().toString());
            tPssrApproveService.updateTPssrApprove(approve);

            TPssrSubcontent subcontent = new TPssrSubcontent();
            subcontent.setId(approve.getSubId());
            subcontent.setApproveStatus(1L);
            subcontent.setUpdatedate(new Date());
            subcontent.setUpdaterCode(getUserId().toString());
            tPssrSubcontentService.updateTPssrSubcontent(subcontent);
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }


    /**
     * 查询检修项目-泵列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:overhaulPump:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrOverhaulPump tPssrOverhaulPump) {
        if ("1".equals(tPssrOverhaulPump.getConfirmedPerson())) {
            tPssrOverhaulPump.setConfirmedPerson(getUserId().toString());
        }
        startPage();
        List<TPssrOverhaulPump> list = tPssrOverhaulPumpService.selectTPssrOverhaulPumpList(tPssrOverhaulPump);
        list.forEach(item -> {
            
            List<TPssrFile> tPssrFiles = tPssrFileService.selectTPssrFileListByItem(item.getSubId(), item.getId(), forShort);
            item.setFileList(tPssrFiles);
            item.setFileNum((long) tPssrFiles.size());
            if (item.getApproveStatus() != 2)
                item.setReason(tPssrTurndownService.selectTPssrTurndownByItem(item.getSubId(), item.getId(), "jxxm-b"));
        });
        return getDataTable(list);
    }

    /**
     * 导出检修项目-泵列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:overhaulPump:export')")
    @Log(title = "检修项目-泵", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrOverhaulPump tPssrOverhaulPump) {
        List<TPssrOverhaulPump> list = tPssrOverhaulPumpService.selectTPssrOverhaulPumpList(tPssrOverhaulPump);
        ExcelUtil<TPssrOverhaulPump> util = new ExcelUtil<TPssrOverhaulPump>(TPssrOverhaulPump.class);
        return util.exportExcel(list, "overhaulPump");
    }

    /**
     * 获取检修项目-泵详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:overhaulPump:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TPssrOverhaulPump item = tPssrOverhaulPumpService.selectTPssrOverhaulPumpById(id);
        
            List<TPssrFile> tPssrFiles = tPssrFileService.selectTPssrFileListByItem(item.getSubId(), item.getId(), forShort);
            item.setFileList(tPssrFiles);
            item.setFileNum((long) tPssrFiles.size());
        if (item.getApproveStatus() != 2)
            item.setReason(tPssrTurndownService.selectTPssrTurndownByItem(item.getSubId(), item.getId(), "jxxm-b"));
        return AjaxResult.success(item);
    }

    /**
     * 新增检修项目-泵
     */
    @PreAuthorize("@ss.hasPermi('pssr:overhaulPump:add')")
    @Log(title = "检修项目-泵", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrOverhaulPump tPssrOverhaulPump) {
        tPssrOverhaulPump.setApproveStatus(0L);
        return toAjax(tPssrOverhaulPumpService.insertTPssrOverhaulPump(tPssrOverhaulPump));
    }

    /**
     * 修改检修项目-泵
     */
    @PreAuthorize("@ss.hasPermi('pssr:overhaulPump:edit')")
    @Log(title = "检修项目-泵", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrOverhaulPump tPssrOverhaulPump) {
        TPssrOverhaulPump entity = tPssrOverhaulPumpService.selectTPssrOverhaulPumpById(tPssrOverhaulPump.getId());
        if (entity.getApproveStatus() != 1 && entity.getApproveStatus() != 0) {
            return  AjaxResult.error("当前状态不可修改！");
        }
        tPssrFileService.updateFileRelevance(tPssrOverhaulPump.getFileIds(), "jxxm-b", tPssrOverhaulPump.getId(), tPssrOverhaulPump.getSubId());
        return toAjax(tPssrOverhaulPumpService.updateTPssrOverhaulPump(tPssrOverhaulPump));
    }

    /**
     * 修改检修项目-泵
     */
    @PreAuthorize("@ss.hasPermi('pssr:overhaulPump:edit')")
    @Log(title = "检修项目-泵", businessType = BusinessType.UPDATE)
    @PutMapping("/editBatch")
    public AjaxResult editb(@RequestBody TPssrOverhaulPump tPssrOverhaulPump) {
        return toAjax(tPssrOverhaulPumpMapper.updateTPssrOverhaulPumpByIds(tPssrOverhaulPump));
    }

    /**
     * 删除检修项目-泵
     */
    @PreAuthorize("@ss.hasPermi('pssr:overhaulPump:remove')")
    @Log(title = "检修项目-泵", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrOverhaulPumpService.deleteTPssrOverhaulPumpByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('pssr:overhaulPump:edit')")
    @Log(title = "检修项目-泵", businessType = BusinessType.UPDATE)
    @PutMapping("/confirmPump")
    public AjaxResult confirmPump(@RequestBody TPssrOverhaulPump tPssrOverhaulPump) {
        if (tPssrOverhaulPump.getIds() != null && tPssrOverhaulPump.getIds().length > 0) {
            for (Long id : tPssrOverhaulPump.getIds()) {
                TPssrOverhaulPump pump = tPssrOverhaulPumpService.selectTPssrOverhaulPumpById(id);
                pump.setCompletionDate(new Date());
                pump.setApproveStatus(2L);
                pump.setUpdatedate(new Date());
                pump.setUpdaterCode(String.valueOf(getUserId()));
                tPssrOverhaulPumpService.updateTPssrOverhaulPump(pump);
            }
        } else {
            TPssrOverhaulPump pump = new TPssrOverhaulPump();
            pump.setSubId(tPssrOverhaulPump.getSubId());
            pump.setConfirmedPerson(getUserId().toString());
            pump.setApproveStatus(1L);
            for (TPssrOverhaulPump overhaulPump : tPssrOverhaulPumpService.selectTPssrOverhaulPumpList(pump)) {
                overhaulPump.setCompletionDate(new Date());
                overhaulPump.setApproveStatus(2L);
                overhaulPump.setUpdatedate(new Date());
                overhaulPump.setUpdaterCode(String.valueOf(getUserId()));
                tPssrOverhaulPumpService.updateTPssrOverhaulPump(overhaulPump);
            }
        }
        //查询当前待审批的确认人
        TPssrOverhaulExchanger entity = new TPssrOverhaulExchanger();
        entity.setSubId(tPssrOverhaulPump.getSubId());
        entity.setApproveStatus(1L);
        TPssrOverhaulExchanger exchanger = tPssrOverhaulExchangerService.selectAllConfirmedPersonBySubId(entity);
        if (exchanger != null) {
            String confirmedPerson = exchanger.getConfirmedPerson();
            logger.info("===========confirmedPerson:{}", confirmedPerson);
            //如果当前用户还有待审批任务
            if (confirmedPerson.contains(getUserId().toString())) {
                return AjaxResult.success();
            }
        }
        //无待审批任务结束当前用户流程

        // 因为流程关系所以approve一定会有且只有一条数据
        TPssrApprove tPssrApprove = tPssrApproveService.selectTPssrApproveBySubId(tPssrOverhaulPump.getSubId());
        TPssrApproveController.handleConfirmApprove(tPssrApprove, getUserId().toString());
        return AjaxResult.success();
    }
}
