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.pssr.domain.*;
import com.ruoyi.project.pssr.mapper.TPssrBlindMapper;
import com.ruoyi.project.pssr.service.*;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysUserService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
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 org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 盲板Controller
 *
 * @author ssy
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/pssr/blind")
public class TPssrBlindController extends BaseController {
    @Autowired
    private ITPssrFileService tPssrFileService;

    @Resource
    private TPssrBlindMapper tPssrBlindMapper;

    @Autowired
    private ITPssrTurndownService tPssrTurndownService;
    @Autowired
    private ITPssrBlindService tPssrBlindService;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysUserService userService;

    private String forShort = "mb";

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('pssr:blind:add')")
    @PostMapping("/importData")
    public AjaxResult importInterlockData(MultipartFile file, Long subId) throws IOException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<Integer>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TPssrBlind> list = new ArrayList<TPssrBlind>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 2; i <= rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TPssrBlind entity = new TPssrBlind();
                entity.setDeptId(userService.selectUserById(getUserId()).getDeptId());
                entity.setSubId(subId);
                entity.setApproveStatus(0L);
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    String cellValue = ExcelUtils.getCellValue(cell);
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        entity.setUnitNo(cellValue);
                    } else if (j == 1) {
                        entity.setBlindNo(cellValue);
                    } else if (j == 2) {
                        entity.setIsoType(cellValue);
                    } else if (j == 3) {
                        entity.setBlindSize(cellValue);
                    } else if (j == 4) {
                        entity.setPressureRate(cellValue);
                    } else if (j == 5) {
                        entity.setBlindType(cellValue);
                    } else if (j == 6) {
                        entity.setMedium(cellValue);
                    } else if (j == 7) {
                        entity.setFigure(cellValue);
                    } else if (j == 8) {
                        entity.setPidNo(cellValue);
                    } else if (j == 9) {
                        entity.setLocation(cellValue);
                    } else if (j == 10) {
                        entity.setStartupStatus(cellValue);
                    }else if (j == 11) {
                        entity.setInConfirm1(cellValue);
                    }else if (j == 12) {
                        entity.setInConfirm2(cellValue);
                    }
                }
                entity.setCreaterCode(userId.toString());
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TPssrBlind t : list
        ) {
            failNum++;
            try {
                this.add(t);
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                failRow.add(failNum + 1);
            }
        }
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" + String.valueOf(successNumber));
        logger.info("failNumber:" + String.valueOf(failNumber));
        logger.info("failRow:" + String.valueOf(failRow));
        return AjaxResult.success("导入成功行数：" + String.valueOf(successNumber));
    }

    /**
     * 查询盲板列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:blind:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrBlind tPssrBlind) {
        try {
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(tPssrBlind.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")){
                        tPssrBlind.setInConfirm1(getUserId().toString());
                    }else if (task.getName().equals("确认人2")){
                       tPssrBlind.setInConfirm2(getUserId().toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("待办确认人查询报错：{}",e.getMessage());
        }
        startPage();
        List<TPssrBlind> list = tPssrBlindService.selectTPssrBlindList(tPssrBlind);
        if (list.size() > 0) {
            //线程池
            ExecutorService executorService = Executors.newFixedThreadPool(30);
            final CountDownLatch latch = new CountDownLatch(list.size()); //相同线程数量的计数
            for (TPssrBlind item : list
            ) {
                executorService.submit(() -> {
                    try {
                        
            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-fm"));
                    } catch (Exception e) {
                        logger.error("e:", e);
                    } finally {
                        latch.countDown(); //线程计数
                    }
                });
            }
            try {
                latch.await(); //线程计数完毕后继续执行
            } catch (InterruptedException e) {
                logger.error("e", e);
            }
            executorService.shutdown();
        }
        return getDataTable(list);
    }

    /**
     * 导出盲板列表
     */
    @Log(title = "盲板", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrBlind tPssrBlind) {
        List<TPssrBlind> list = tPssrBlindService.selectTPssrBlindList(tPssrBlind);
        if (list.size() != 0) {
            return AjaxResult.success(exportTmpl(list));
        } else {
            return AjaxResult.error("暂无可导出数据");
        }
    }

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

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

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

            for (TPssrBlind t : list) {
                Row row = sheet.createRow(rowIndex);
                row.setHeight((short) 800);
                row.createCell(0).setCellValue(num);
                row.createCell(1).setCellValue(t.getUnitNo());
                row.createCell(2).setCellValue(t.getBlindNo());
                row.createCell(3).setCellValue(t.getIsoType());
                row.createCell(4).setCellValue(t.getBlindSize());
                row.createCell(5).setCellValue(t.getPressureRate());
                row.createCell(6).setCellValue(t.getBlindType());
                row.createCell(7).setCellValue(t.getMedium());
                row.createCell(8).setCellValue(t.getFigure());
                row.createCell(9).setCellValue(t.getPidNo());
                row.createCell(10).setCellValue(t.getLocation());
                row.createCell(11).setCellValue(t.getStartupStatus());
                row.createCell(12).setCellValue(t.getActualStatus());
                row.createCell(13).setCellValue(t.getSatisfy());
                row.createCell(14);
                row.createCell(15);
                try {
                    SysUser sysUser1 = sysUserService.selectUserById(Long.valueOf(t.getInConfirm1()));
                    SysUser sysUser2 = sysUserService.selectUserById(Long.valueOf(t.getInConfirm2()));
                    String confirm1 = sysUser1.getSignUrl();
                    String confirm2 = sysUser2.getSignUrl();
                    ExcelUtils.insertPicture(wb, sheet, confirm1, row.getRowNum(), 14, 1, 1);
                    ExcelUtils.insertPicture(wb, sheet, confirm2, row.getRowNum(), 15, 1, 1);
                } catch (Exception e) {

                }
                row.createCell(16).setCellValue(DateUtils.dateTime(t.getInstallDate()));
                row.createCell(17).setCellValue(t.getRemarks());


                //渲染样式
                for (int i = 0; i < 18; i++) {
                    row.getCell(i).setCellStyle(originalStyle);
                }
                num++;
                rowIndex++;
            }
            filename = "PSSR_04_盲板" + ".xlsx";
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            wb.close();
            is.close();
            out.close();

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

    /**
     * 获取盲板详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:blind:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TPssrBlind item = tPssrBlindService.selectTPssrBlindById(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(), forShort));
        return AjaxResult.success(item);
    }

    /**
     * 新增盲板
     */
    @PreAuthorize("@ss.hasPermi('pssr:blind:add')")
    @Log(title = "盲板", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrBlind tPssrBlind) {
        if (StringUtils.isNotEmpty(tPssrBlind.getInConfirm1()) && tPssrBlind.getInConfirm1().equals(tPssrBlind.getInConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrBlind.setApproveStatus(0L);
        return toAjax(tPssrBlindService.insertTPssrBlind(tPssrBlind));
    }

    //导入时判断更新或新增
    private int insertOrUpdate(TPssrBlind item) {
        TPssrBlind entity = new TPssrBlind();
        entity.setSubId(item.getSubId());
        entity.setPipelineNo(item.getPipelineNo());
        List<TPssrBlind> list = tPssrBlindService.selectTPssrBlindList(entity);
        if (CollectionUtils.isNotEmpty(list)) {
            item.setId(list.get(0).getId());
            return tPssrBlindService.updateTPssrBlind(item);
        }else {
            return tPssrBlindService.insertTPssrBlind(item);

        } }

    /**
     * 修改盲板
     */
    @PreAuthorize("@ss.hasPermi('pssr:blind:edit')")
    @Log(title = "盲板", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrBlind tPssrBlind) {
        TPssrBlind entity = tPssrBlindService.selectTPssrBlindById(tPssrBlind.getId());
        if (entity.getApproveStatus() != 1 && entity.getApproveStatus() != 0) {
            return  AjaxResult.error("当前状态不可修改！");
        }
        if (tPssrBlind.getInConfirm1().equals(tPssrBlind.getInConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        if (StringUtils.isNotEmpty(tPssrBlind.getStartupStatus()) && StringUtils.isEmpty(tPssrBlind.getActualStatus())) {
            tPssrBlind.setActualStatus(tPssrBlind.getStartupStatus());
        } else if (StringUtils.isEmpty(tPssrBlind.getStartupStatus()) && StringUtils.isNotEmpty(tPssrBlind.getActualStatus())) {
            tPssrBlind.setStartupStatus(tPssrBlind.getActualStatus());
        }

        if(StringUtils.isNotEmpty(tPssrBlind.getStartupStatus())&&tPssrBlind.getStartupStatus().equals(tPssrBlind.getActualStatus())){
            tPssrBlind.setSatisfy("✔");
        }else{
            tPssrBlind.setSatisfy("✖");
        }
        tPssrFileService.updateFileRelevance(tPssrBlind.getFileIds(), forShort, tPssrBlind.getId(), tPssrBlind.getSubId());
        return toAjax(tPssrBlindService.updateTPssrBlind(tPssrBlind));
    }

    /**
     * 修改盲板
     */
    @PreAuthorize("@ss.hasPermi('pssr:blind:edit')")
    @Log(title = "盲板", businessType = BusinessType.UPDATE)
    @PutMapping("/editBatch")
    public AjaxResult editb(@RequestBody TPssrBlind tPssrBlind) {
        if (tPssrBlind.getInConfirm1().equals(tPssrBlind.getInConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrBlindMapper.updateTPssrBlindByIds(tPssrBlind));
    }

    /**
     * 删除盲板
     */
    @PreAuthorize("@ss.hasPermi('pssr:blind:remove')")
    @Log(title = "盲板", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrBlindService.deleteTPssrBlindByIds(ids));
    }


    /**
     * 确认盲板
     */
    @PreAuthorize("@ss.hasPermi('pssr:blind:edit')")
    @Log(title = "盲板", businessType = BusinessType.UPDATE)
    @PutMapping("/confirmBlind")
    public AjaxResult confirmBlind(@RequestBody TPssrBlind tPssrBlind) {
        // 修改盲板状态
        if (tPssrBlind.getIds() != null && tPssrBlind.getIds().length > 0) {
            for (Long id : tPssrBlind.getIds()) {
                TPssrBlind item = tPssrBlindService.selectTPssrBlindById(id);
                if (tPssrBlind.getTaskType() == 4) {
                    item.setApproveStatus(3L);
                } else if (tPssrBlind.getTaskType() == 5) {
                    item.setApproveStatus(2L);
                    if (item.getInstallDate() == null) {
                        item.setInstallDate(new Date());
                    }
                }
                tPssrBlindService.updateTPssrBlind(item);
            }
        } else {
            TPssrBlind blind = new TPssrBlind();
            blind.setSubId(tPssrBlind.getSubId());
            blind.setCurrentUser(getUserId().toString());
            if (tPssrBlind.getTaskType() == 4) {
                blind.setApproveStatus(1L);
                blind.setInConfirm1(getUserId().toString());
            } else if (tPssrBlind.getTaskType() == 5) {
                blind.setApproveStatus(3L);
                blind.setInConfirm2(getUserId().toString());
            }
            for (TPssrBlind item : tPssrBlindService.selectTPssrBlindList(blind)) {
                if (tPssrBlind.getTaskType() == 4) {
                    item.setApproveStatus(3L);
                } else if (tPssrBlind.getTaskType() == 5) {
                    item.setApproveStatus(2L);
                    if (item.getInstallDate() == null) {
                        item.setInstallDate(new Date());
                    }
                }
                tPssrBlindService.updateTPssrBlind(item);
            }
        }
        //查询当前待审批的确认人
        TPssrBlind entity = new TPssrBlind();
        entity.setSubId(tPssrBlind.getSubId());
        if (tPssrBlind.getTaskType() == 4) {
            entity.setApproveStatus(1L);
        } else if (tPssrBlind.getTaskType() == 5) {
            entity.setApproveStatus(3L);
        }
        long status = 1;
        boolean flag = false;
        for (TPssrBlind item : tPssrBlindService.selectTPssrBlindList(entity)) {
            item.setTaskType(tPssrBlind.getTaskType());
            if (tPssrBlind.getTaskType() == 4) {
                if (item.getInConfirm1().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            } else if (tPssrBlind.getTaskType() == 5) {
                if (item.getInConfirm2().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            }
        }

        TPssrSubcontent tPssrSubcontent = new TPssrSubcontent();
        tPssrSubcontent.setId(tPssrBlind.getSubId());
        tPssrSubcontent.setApproveStatus(status);
        tPssrSubcontentService.updateTPssrSubcontent(tPssrSubcontent);

        //无待审批任务结束当前用户流程

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

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

            ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
            TaskService taskService = processEngine.getTaskService();
            Task task = processEngine.getTaskService()//获取任务service
                    .createTaskQuery()//创建查询对象
                    .taskAssignee(userId)
                    .processInstanceId(approve.getProcessId()).singleResult();
            String taskId = task.getId();

            // 驳回 查询所有待审批的人员
            TPssrBlind blind = new TPssrBlind();
            blind.setSubId(subId);
            blind.setApproveStatus(1L);
            Set<String> installer = new HashSet<>();
            Set<String> remover = new HashSet<>();
            for (TPssrBlind item : tPssrBlindService.selectTPssrBlindList(blind)) {
                installer.add(item.getInConfirm1());
                remover.add(item.getInConfirm2());
            }


            //处理流程节点
            Map<String, Object> param = new HashMap<>();
            param.put("condition", 1);
            param.put("confirmUsers1", new ArrayList<>(installer));
            param.put("confirmUsers2", new ArrayList<>(remover));
            //认领任务
            processEngine.getTaskService().claim(taskId, userId);
            taskService.addComment(taskId, approve.getProcessId(), "驳回");
            taskService.complete(taskId, param);

            // 修改审批表和sub表
            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();
    }

}
