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.TPssrPumpFillMapper;
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.*;
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.*;
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.*;

/**
 * 机泵润滑油加注确认清单Controller
 *
 * @author ssy
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/pssr/pumpFill")
public class TPssrPumpFillController extends BaseController {
    @Resource
     private TPssrPumpFillMapper tPssrPumpFillMapper;
    @Autowired
    private ITPssrFileService tPssrFileService;

    @Autowired
    private ITPssrTurndownService tPssrTurndownService;
    @Autowired
    private ITPssrPumpFillService tPssrPumpFillService;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private HistoryService historyService;

    @Autowired
    private ISysUserService sysUserService;
    private String forShort = "jb-f";

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysUserService userService;

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('pssr:pumpFill: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<TPssrPumpFill> list = new ArrayList<TPssrPumpFill>();
        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();
                TPssrPumpFill entity = new TPssrPumpFill();
                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.setUnit(cellValue);
                    } else if (j == 1) {
                        entity.setDevNo(cellValue);
                    } else if (j == 2) {
                        entity.setLubricatingPart(cellValue);
                    } else if (j == 3) {
                        entity.setConfirmer1(cellValue);
                    } else if (j == 4) {
                        entity.setConfirmer2(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 (TPssrPumpFill 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:pumpFill:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrPumpFill tPssrPumpFill) {
        try {
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(tPssrPumpFill.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")){
                        tPssrPumpFill.setConfirmer1(getUserId().toString());
                    }else if (task.getName().equals("确认人2")){
                       tPssrPumpFill.setConfirmer2(getUserId().toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("待办确认人查询报错：{}",e.getMessage());
        }
        startPage();
        List<TPssrPumpFill> list = tPssrPumpFillService.selectTPssrPumpFillList(tPssrPumpFill);
        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(), "jb-f"));
        });
        return getDataTable(list);
    }

    /**
     * 导出机泵润滑油加注确认清单列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:pumpFill:export')")
    @Log(title = "机泵润滑油加注确认清单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrPumpFill tPssrPumpFill) {
        List<TPssrPumpFill> list = tPssrPumpFillService.selectTPssrPumpFillList(tPssrPumpFill);
        if (list.size() != 0) {
            return AjaxResult.success(exportTmpl(list));
        } else {
            return AjaxResult.error("暂无可导出数据");
        }
    }

    public String exportTmpl(List<TPssrPumpFill> list) {
        OutputStream out = null;
        String filename = null;
        try {
            String tempUrl = "static/word/pssr/jbrhy.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 (TPssrPumpFill 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.getDevNo());
                row.createCell(3).setCellValue(t.getLubricatingPart());
                row.createCell(4).setCellValue(t.getFillingComplete());
                row.createCell(5).setCellValue(t.getLubricatingLeak());
                row.createCell(6).setCellValue(t.getLiquidNormal());
                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_20_机泵_机泵润滑油加注确认清单"  + ".xlsx";
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            wb.close();

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

    /**
     * 获取机泵润滑油加注确认清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:pumpFill:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TPssrPumpFill item = tPssrPumpFillService.selectTPssrPumpFillById(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(), "jb-f"));
        return AjaxResult.success(item);
    }

    /**
     * 新增机泵润滑油加注确认清单
     */
    @PreAuthorize("@ss.hasPermi('pssr:pumpFill:add')")
    @Log(title = "机泵润滑油加注确认清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrPumpFill tPssrPumpFill) {
        if (StringUtils.isNotEmpty(tPssrPumpFill.getConfirmer1())&&tPssrPumpFill.getConfirmer1().equals(tPssrPumpFill.getConfirmer2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrPumpFill.setApproveStatus(0L);
        tPssrPumpFill.setCreatedate(new Date());
        tPssrPumpFill.setCreaterCode(String.valueOf(getUserId()));
        return toAjax(tPssrPumpFillService.insertTPssrPumpFill(tPssrPumpFill));
    }

    //导入时判断更新或新增
    private int insertOrUpdate(TPssrPumpFill item) {
        TPssrPumpFill entity = new TPssrPumpFill();
        entity.setSubId(item.getSubId());
        entity.setDevNo(item.getDevNo());
        List<TPssrPumpFill> list = tPssrPumpFillService.selectTPssrPumpFillList(entity);
        if (CollectionUtils.isNotEmpty(list)) {
            item.setId(list.get(0).getId());
            return tPssrPumpFillService.updateTPssrPumpFill(item);
        } else {
            return tPssrPumpFillService.insertTPssrPumpFill(item);
        }
    }

    /**
     * 修改机泵润滑油加注确认清单
     */
    @PreAuthorize("@ss.hasPermi('pssr:pumpFill:edit')")
    @Log(title = "机泵润滑油加注确认清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrPumpFill tPssrPumpFill) {
        TPssrPumpFill entity = tPssrPumpFillService.selectTPssrPumpFillById(tPssrPumpFill.getId());
        if (entity.getApproveStatus() != 1 && entity.getApproveStatus() != 0) {
            return  AjaxResult.error("当前状态不可修改！");
        }
        if (tPssrPumpFill.getConfirmer1().equals(tPssrPumpFill.getConfirmer2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrFileService.updateFileRelevance(tPssrPumpFill.getFileIds(), "jb-f", tPssrPumpFill.getId(), tPssrPumpFill.getSubId());
        return toAjax(tPssrPumpFillService.updateTPssrPumpFill(tPssrPumpFill));
    }

    /**
     * 修改机泵润滑油加注确认清单
     */
    @PreAuthorize("@ss.hasPermi('pssr:pumpFill:edit')")
    @Log(title = "机泵润滑油加注确认清单", businessType = BusinessType.UPDATE)
    @PutMapping("/editBatch")
    public AjaxResult editb(@RequestBody TPssrPumpFill tPssrPumpFill) {
        if (tPssrPumpFill.getConfirmer1().equals(tPssrPumpFill.getConfirmer2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrPumpFillMapper.updateTPssrPumpFillByIds(tPssrPumpFill));
    }
    /**
     * 删除机泵润滑油加注确认清单
     */
    @PreAuthorize("@ss.hasPermi('pssr:pumpFill:remove')")
    @Log(title = "机泵润滑油加注确认清单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrPumpFillService.deleteTPssrPumpFillByIds(ids));
    }

    /**
     * 确认人身防护
     */
    @PreAuthorize("@ss.hasPermi('pssr:pumpFill:edit')")
    @Log(title = "人身防护", businessType = BusinessType.UPDATE)
    @PutMapping("/confirmPumpFill")
    public AjaxResult confirmPumpFill(@RequestBody TPssrPumpFill tPssrPumpFill) {
        long queryStatus = 0;
        long approveStatus = 0;
        Date date = null;
        TPssrPumpFill pumpFill = new TPssrPumpFill();
        if (tPssrPumpFill.getTaskType() == 4) {
            //确认人1确认
            queryStatus = 1;
            approveStatus = 3;
            pumpFill.setConfirmer1(getUserId().toString());
            date = new Date();
        } else if (tPssrPumpFill.getTaskType() == 5) {
            //确认人2确认
            queryStatus = 3;
            approveStatus = 2;
            pumpFill.setConfirmer2(getUserId().toString());
            date = new Date();
        }
        if (tPssrPumpFill.getIds() != null && tPssrPumpFill.getIds().length > 0) {
            for (Long id : tPssrPumpFill.getIds()) {
                pumpFill = tPssrPumpFillService.selectTPssrPumpFillById(id);
                if (pumpFill.getConfirmationDate() == null && tPssrPumpFill.getTaskType() == 5) {
                    pumpFill.setConfirmationDate(new Date());
                }
                pumpFill.setApproveStatus(approveStatus);
                pumpFill.setUpdatedate(new Date());
                pumpFill.setUpdaterCode(String.valueOf(getUserId()));
                tPssrPumpFillService.updateTPssrPumpFill(pumpFill);
            }
        } else {
            pumpFill.setSubId(tPssrPumpFill.getSubId());
            pumpFill.setApproveStatus(queryStatus);
            for (TPssrPumpFill item : tPssrPumpFillService.selectTPssrPumpFillList(pumpFill)) {
                if (tPssrPumpFill.getTaskType() == 5) {
                    item.setConfirmationDate(new Date());
                }
                item.setApproveStatus(approveStatus);
                item.setUpdatedate(new Date());
                item.setUpdaterCode(String.valueOf(getUserId()));
                tPssrPumpFillService.updateTPssrPumpFill(item);
            }
        }
        //查询当前待审批的确认人
        TPssrPumpFill entity = new TPssrPumpFill();
        entity.setSubId(tPssrPumpFill.getSubId());
        entity.setApproveStatus(queryStatus);
        TPssrPumpFill queryData = tPssrPumpFillService.selectAllConfirmedPersonBySubId(entity);
        if (queryData != null) {
            //如果当前用户还有待审批任务
            if (tPssrPumpFill.getTaskType() == 4 && StringUtils.isNotEmpty(queryData.getConfirmer1())) {
                if (queryData.getConfirmer1().contains(getUserId().toString())) {
                    return AjaxResult.success();
                }
            }

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

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


    /**
     * 驳回人身防护
     */
    @PutMapping("/turnDownPumpFill")
    public AjaxResult turnDownPumpFill(@RequestBody List<TPssrPumpFill> tPssrPumpFill) {
        if (CollectionUtils.isNotEmpty(tPssrPumpFill)) {
            String userId = getUserId().toString();
            Long subId = tPssrPumpFill.get(0).getSubId();
            // 修改已选择数据的状态
            for (TPssrPumpFill item : tPssrPumpFill) {
                TPssrPumpFill blind = new TPssrPumpFill();
                blind.setId(item.getId());
                blind.setApproveStatus(1L);
                blind.setUpdatedate(new Date());
                blind.setUpdaterCode(getUserId().toString());
                tPssrPumpFillService.updateTPssrPumpFill(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("无运行时流程");
            }

            // 驳回 查询所有待审批的人员
            // 查询确认人
            TPssrPumpFill entity = new TPssrPumpFill();
            entity.setSubId(subId);
            entity.setApproveStatus(1L);
            TPssrPumpFill queryData = tPssrPumpFillService.selectAllConfirmedPersonBySubId(entity);
            String confirmer1s = null;
            String confirmer2s = null;
            if (queryData != null) {
                confirmer1s = queryData.getConfirmer1();
                confirmer2s = queryData.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();
    }
}
