package com.ruoyi.project.pssr.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
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.TPssrVesselMapper;
import com.ruoyi.project.pssr.service.*;
import com.ruoyi.project.sems.domain.TSpecdevYlrq;
import com.ruoyi.project.sems.mapper.TSpecdevYlrqMapper;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
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.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
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.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.*;

/**
 * 压力容器Controller
 *
 * @author ssy
 * @date 2024-11-07
 */
@RestController
@RequestMapping("/pssr/vessel")
public class TPssrVesselController extends BaseController {
    @Resource
    private TPssrVesselMapper tPssrVesselMapper;
    @Autowired
    private ITPssrFileService tPssrFileService;

    @Autowired
    private ITPssrTurndownService tPssrTurndownService;
    @Autowired
    private ITPssrVesselService tPssrVesselService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;
    @Resource
    private TSpecdevYlrqMapper tSpecdevYlrqMapper;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ITPssrPipeService tPssrPipeService;

    @Autowired
    private ISysUserService sysUserService;
    private String forShort = "ylrq";

    /**
     * 查询压力容器列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:vessel:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrVessel tPssrVessel) {
        try {
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(tPssrVessel.getSubId());
            if (approve != null) {
                ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
                TaskService taskService = processEngine.getTaskService();
                Task task = processEngine.getTaskService()//获取任务service
                        .createTaskQuery()//创建查询对象
                        .taskAssignee(getUserId().toString())
                        .processInstanceId(approve.getProcessId()).singleResult();
                if (task != null) {
                    if (task.getName().equals("确认人1")){
                        tPssrVessel.setConfirmer1(getUserId().toString());
                    }else if (task.getName().equals("确认人2")){
                       tPssrVessel.setConfirmer2(getUserId().toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("待办确认人查询报错：{}",e.getMessage());
        }
        startPage();
        List<TPssrVessel> list = tPssrVesselService.selectTPssrVesselList(tPssrVessel);
        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(), "ylrq"));
        });
        return getDataTable(list);
    }

    /**
     * 导出压力容器列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:vessel:export')")
    @Log(title = "压力容器", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrVessel tPssrVessel) {
        List<TPssrVessel> list = tPssrVesselService.selectTPssrVesselList(tPssrVessel);
        if (list.size() != 0) {
            return AjaxResult.success(exportTmpl(list));
        } else {
            return AjaxResult.error("暂无可导出数据");
        }
    }

    public String exportTmpl(List<TPssrVessel> list) {
        OutputStream out = null;
        String filename = null;
        try {
            String tempUrl = "static/word/pssr/ylrq.xlsx"; // 模板文件
            InputStream is = null;
            is = Thread.currentThread().getContextClassLoader().getResourceAsStream(tempUrl);
            XSSFWorkbook wb = null;
            wb = new XSSFWorkbook(is);
            XSSFSheet sheet = wb.getSheetAt(0);

            //填充数据
            int rowIndex = 4;
            int num = 1;

            Row originalRow = sheet.getRow(4);
            Cell originalcell = originalRow.getCell(0);
            // 获取单元格样式
            CellStyle originalStyle = originalcell.getCellStyle();

            for (TPssrVessel t : list) {
                Row row = sheet.createRow(rowIndex);
                row.setHeight((short) 800);
                row.createCell(0).setCellValue(num);
                row.createCell(1).setCellValue(t.getUnit());
                row.createCell(2).setCellValue(t.getVesselName());
                row.createCell(3).setCellValue(t.getVesselNo());
                row.createCell(4).setCellValue(t.getChecked());
                row.createCell(5).setCellValue(t.getRequire());
                row.createCell(6).setCellValue(t.getValidity());
                row.createCell(7);
                row.createCell(8);
                try {
                    SysUser sysUser1 = sysUserService.selectUserById(Long.valueOf(t.getConfirmer1()));
                    SysUser sysUser2 = sysUserService.selectUserById(Long.valueOf(t.getConfirmer2()));
                    String confirm1 = sysUser1.getSignUrl();
                    String confirm2 = sysUser2.getSignUrl();
                    ExcelUtils.insertPicture(wb, sheet, confirm1, row.getRowNum(), 7, 1, 1);
                    ExcelUtils.insertPicture(wb, sheet, confirm2, row.getRowNum(), 8, 1, 1);
                } catch (Exception e) {

                }
                row.createCell(9).setCellValue(DateUtils.dateTime(t.getConfirmationDate()));
                row.createCell(10).setCellValue(t.getRemarks());

                //渲染样式
                for (int i = 0; i < 11; i++) {
                    row.getCell(i).setCellStyle(originalStyle);
                }
                num++;
                rowIndex++;
            }
            filename = "PSSR_22_压力容器"  + ".xlsx";
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            wb.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return filename;
    }

    /**
     * 获取压力容器详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:vessel:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TPssrVessel item = tPssrVesselService.selectTPssrVesselById(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(), "ylrq"));
        return AjaxResult.success(item);
    }

    /**
     * 新增压力容器
     */
    @PreAuthorize("@ss.hasPermi('pssr:vessel:add')")
    @Log(title = "压力容器", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrVessel tPssrVessel) {
        if (StringUtils.isNotEmpty(tPssrVessel.getConfirmer1())&&tPssrVessel.getConfirmer1().equals(tPssrVessel.getConfirmer2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrVessel.setApproveStatus(0L);
        tPssrVessel.setCreatedate(new Date());
        tPssrVessel.setCreaterCode(getUserId().toString());
        return toAjax(tPssrVesselService.insertTPssrVessel(tPssrVessel));
    }

    //导入时判断更新或新增
    private int insertOrUpdate(TPssrVessel item) {
        TPssrVessel entity = new TPssrVessel();
        entity.setSubId(item.getSubId());
        entity.setVesselNo(item.getVesselNo());
        List<TPssrVessel> list = tPssrVesselService.selectTPssrVesselList(entity);
        if (CollectionUtils.isNotEmpty(list)) {
            item.setId(list.get(0).getId());
            return tPssrVesselService.updateTPssrVessel(item);
        } else {
            return tPssrVesselService.insertTPssrVessel(item);
        }
    }

    /**
     * 修改压力容器
     */
    @PreAuthorize("@ss.hasPermi('pssr:vessel:edit')")
    @Log(title = "压力容器", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrVessel tPssrVessel) {
        TPssrVessel entity = tPssrVesselService.selectTPssrVesselById(tPssrVessel.getId());
        if (entity.getApproveStatus() != 1 && entity.getApproveStatus() != 0) {
            return  AjaxResult.error("当前状态不可修改！");
        }
        if (tPssrVessel.getConfirmer1().equals(tPssrVessel.getConfirmer2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrFileService.updateFileRelevance(tPssrVessel.getFileIds(), "ylrq", tPssrVessel.getId(), tPssrVessel.getSubId());
        return toAjax(tPssrVesselService.updateTPssrVessel(tPssrVessel));
    }

    /**
     * 删除压力容器
     */
    @PreAuthorize("@ss.hasPermi('pssr:vessel:remove')")
    @Log(title = "压力容器", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrVesselService.deleteTPssrVesselByIds(ids));
    }

    /**
     * 批量修改压力容器
     */
    @PreAuthorize("@ss.hasPermi('pssr:vessel:edit')")
    @Log(title = "压力容器修改", businessType = BusinessType.UPDATE)
    @PutMapping("/editBatch")
    public AjaxResult editBatch(@RequestBody TPssrVessel tPssrVessel) {
        if (tPssrVessel.getConfirmer1().equals(tPssrVessel.getConfirmer2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        logger.info(JSON.toJSONString(tPssrVessel));
        return toAjax(tPssrVesselService.updateTPssrVesselByIds(tPssrVessel));
    }


    /**
     * 查询压力容器列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:vessel:add')")
    @GetMapping("/syncVessel")
    public AjaxResult syncVessel(TPssrVessel tPssrVessel) {
        TSpecdevYlrq tSpecdevYlrq = new TSpecdevYlrq();
        TPssrSubcontent subcontent = tPssrSubcontentService.selectTPssrSubcontentById(tPssrVessel.getSubId());
        //删除老数据
        tPssrVesselService.deleteTPssrVesselBySubId(tPssrVessel.getSubId());
        List<TSpecdevYlrq> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(subcontent.getUnit())) {
            for (String unit : subcontent.getUnit().split(",")) {
                tSpecdevYlrq.setPlantCode("BCC");
                tSpecdevYlrq.setDevno(unit + "-");

                Date now = new Date(); //当前日期
                for (TSpecdevYlrq t : tSpecdevYlrqMapper.selectTSpecdevYlrqListForPssr(tSpecdevYlrq)) {


                    TPssrVessel vessel = new TPssrVessel();
                    vessel.setWarnFlag(0l);
                    //判断是否过期
                    if(t.getNextWarnDate().before(now)) {
                        vessel.setWarnFlag(1l);
                    }

                    vessel.setUnit(unit);
                    vessel.setVesselName(t.getDevname());
                    vessel.setVesselNo(t.getDevno());
                    vessel.setSubId(tPssrVessel.getSubId());

                    vessel.setChecked("✔");
                    vessel.setRequire("✔");
                    vessel.setValidity("✔");

                    vessel.setApproveStatus(0L);
                    vessel.setCreatedate(new Date());
                    vessel.setCreaterCode(getUserId().toString());
                    tPssrVesselService.insertTPssrVessel(vessel);
                }
            }
        }
        return AjaxResult.success();
    }


    /**
     * 确认压力容器
     */
    @PreAuthorize("@ss.hasPermi('pssr:vessel:edit')")
    @Log(title = "确认压力容器", businessType = BusinessType.UPDATE)
    @PutMapping("/confirmVessel")
    public AjaxResult confirmVessel(@RequestBody TPssrVessel tPssrVessel) {
        long queryStatus = 0;
        long approveStatus = 0;
        Date date = null;
        TPssrVessel vessel = new TPssrVessel();
        if (tPssrVessel.getTaskType() == 4) {
            //确认人1确认
            queryStatus = 1;
            approveStatus = 3;
            vessel.setConfirmer1(getUserId().toString());
            date = new Date();
        } else if (tPssrVessel.getTaskType() == 5) {
            //确认人2确认
            queryStatus = 3;
            approveStatus = 2;
            vessel.setConfirmer2(getUserId().toString());
            date = new Date();
        }
        if (tPssrVessel.getIds() != null && tPssrVessel.getIds().length > 0) {
            for (Long id : tPssrVessel.getIds()) {
                vessel = tPssrVesselService.selectTPssrVesselById(id);
                vessel.setConfirmationDate(new Date());
                vessel.setApproveStatus(approveStatus);
                vessel.setUpdatedate(new Date());
                vessel.setUpdaterCode(String.valueOf(getUserId()));
                tPssrVesselService.updateTPssrVessel(vessel);
            }
        } else {
            vessel.setSubId(tPssrVessel.getSubId());
            vessel.setApproveStatus(queryStatus);
            for (TPssrVessel item : tPssrVesselService.selectTPssrVesselList(vessel)) {
                item.setConfirmationDate(new Date());
                item.setApproveStatus(approveStatus);
                item.setUpdatedate(new Date());
                item.setUpdaterCode(String.valueOf(getUserId()));
                tPssrVesselService.updateTPssrVessel(item);
            }
        }
        //查询当前待审批的确认人
        TPssrPipe entity = new TPssrPipe();
        entity.setSubId(tPssrVessel.getSubId());
        entity.setApproveStatus(queryStatus);
        TPssrPipe tPssrPipe = tPssrPipeService.selectAllConfirmedPersonBySubId(entity);
        if (tPssrPipe != null) {
            //如果当前用户还有待审批任务
            if (tPssrVessel.getTaskType() == 4 && StringUtils.isNotEmpty(tPssrPipe.getConfirmer1())) {
                if (tPssrPipe.getConfirmer1().contains(getUserId().toString())) {
                    return AjaxResult.success();
                }
            }

            if (tPssrVessel.getTaskType() == 5 && StringUtils.isNotEmpty(tPssrPipe.getConfirmer2())) {
                if (tPssrPipe.getConfirmer2().contains(getUserId().toString())) {
                    return AjaxResult.success();
                }
            }
        }
        //无待审批任务结束当前用户流程

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


    /**
     * 驳回压力容器
     */
    @PutMapping("/turnDownVessel")
    public AjaxResult turnDownVessel(@RequestBody List<TPssrVessel> tPssrVessel) {
        if (CollectionUtils.isNotEmpty(tPssrVessel)) {
            String userId = getUserId().toString();
            Long subId = tPssrVessel.get(0).getSubId();
            // 修改已选择数据的状态
            for (TPssrVessel item : tPssrVessel) {
                TPssrVessel blind = new TPssrVessel();
                blind.setId(item.getId());
                blind.setApproveStatus(1L);
                blind.setUpdatedate(new Date());
                blind.setUpdaterCode(getUserId().toString());
                tPssrVesselService.updateTPssrVessel(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(), "pssr2confirm");
                historyService.deleteHistoricProcessInstance(approve.getProcessId());
            } catch (Exception e) {
                logger.info("无运行时流程");
            }

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

            //查询确认人
            TPssrPipe entity = new TPssrPipe();
            entity.setSubId(subId);
            entity.setApproveStatus(1L);
            TPssrPipe tPssrPipe = tPssrPipeService.selectAllConfirmedPersonBySubId(entity);
            String confirmer1s = null;
            String confirmer2s = null;
            if (tPssrPipe != null) {
                confirmer1s = tPssrPipe.getConfirmer1();
                confirmer2s = tPssrPipe.getConfirmer2();
            }
            logger.info("=======================confirmer1s:{}", confirmer1s);
            logger.info("=======================confirmer2s:{}", confirmer2s);

            Set<String> confirmerUsers1 = new HashSet<>();
            Set<String> confirmerUsers2 = new HashSet<>();
            if (StringUtils.isNotEmpty(confirmer1s)) {
                confirmerUsers1.addAll(Arrays.asList(confirmer1s.split(",")));
            }
            if (StringUtils.isNotEmpty(confirmer2s)) {
                confirmerUsers2.addAll(Arrays.asList(confirmer2s.split(",")));
            }

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