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.TPssrAirtightMapper;
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.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 气密Controller
 *
 * @author ssy
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/pssr/airtight")
public class TPssrAirtightController extends BaseController {
    @Autowired
    private ITPssrFileService tPssrFileService;

    @Autowired
    private ITPssrTurndownService tPssrTurndownService;
    @Autowired
    private ITPssrAirtightService tPssrAirtightService;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private ITPssrSubcontentService tPssrSubcontentService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysUserService userService;

    @Resource
    private TPssrAirtightMapper tPssrAirtightMapper;

    private String forShort = "qm";

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('pssr:airtight: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<TPssrAirtight> list = new ArrayList<TPssrAirtight>();
        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();
                TPssrAirtight entity = new TPssrAirtight();
                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.setSystemName(cellValue);
                    }else if (j == 2) {
                        entity.setAirtightMedium(cellValue);
                    }else if (j == 3) {
                        entity.setAirtightPressure(cellValue);
                    }else if (j == 4) {
                        entity.setStandard(cellValue);
                    }else if (j == 5) {
                        entity.setConfirm1(cellValue);
                    }else if (j == 6) {
                        entity.setConfirm2(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 (TPssrAirtight 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:airtight:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrAirtight tPssrAirtight) {
        try {
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(tPssrAirtight.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")){
                        tPssrAirtight.setConfirm1(getUserId().toString());
                    }else if (task.getName().equals("确认人2")){
                       tPssrAirtight.setConfirm2(getUserId().toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("待办确认人查询报错：{}",e.getMessage());
        }
        startPage();
        List<TPssrAirtight> list = tPssrAirtightService.selectTPssrAirtightList(tPssrAirtight);
        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(), forShort));
        });
        return getDataTable(list);
    }

    /**
     * 导出气密列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:airtight:export')")
    @Log(title = "气密", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrAirtight tPssrAirtight) {
        List<TPssrAirtight> list = tPssrAirtightService.selectTPssrAirtightList(tPssrAirtight);
        if (list.size() != 0) {
            return AjaxResult.success(exportTmpl(list));
        } else {
            return AjaxResult.error("暂无可导出数据");
        }
    }

    /**
     * 获取气密详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:airtight:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TPssrAirtight item = tPssrAirtightService.selectTPssrAirtightById(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:airtight:add')")
    @Log(title = "气密", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrAirtight tPssrAirtight) {
        if (StringUtils.isNotEmpty(tPssrAirtight.getConfirm1())&&tPssrAirtight.getConfirm1().equals(tPssrAirtight.getConfirm2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrAirtight.setApproveStatus(0L);
        check(tPssrAirtight);
        return toAjax(tPssrAirtightService.insertTPssrAirtight(tPssrAirtight));
    }

    //导入时判断更新或新增
    private int insertOrUpdate(TPssrAirtight item) {
        TPssrAirtight entity = new TPssrAirtight();
        entity.setSubId(item.getSubId());
        entity.setSystemName(item.getSystemName());
        List<TPssrAirtight> list = tPssrAirtightService.selectTPssrAirtightList(entity);
        if (CollectionUtils.isNotEmpty(list)) {
            item.setId(list.get(0).getId());
            return tPssrAirtightService.updateTPssrAirtight(item);
        }else{
            return tPssrAirtightService.insertTPssrAirtight(item);
        }
    }

    private void check(TPssrAirtight tPssrAirtight){
        try {
            String initialPressure = tPssrAirtight.getInitialPressure();//初始压力
            String finalPressure = tPssrAirtight.getFinalPressure();//最终压力
            //泄漏率=(初始压力-最终压力)/初始压力*100%
            BigDecimal leakageRate = new BigDecimal(initialPressure).subtract(new BigDecimal(finalPressure))
                    .divide(new BigDecimal(initialPressure), 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            tPssrAirtight.setLeakageRate(String.valueOf(leakageRate.doubleValue()));//设置泄漏率
            if (leakageRate.compareTo(new BigDecimal(tPssrAirtight.getStandard())) <= 0) {//判断是否满足标准
                tPssrAirtight.setUptoStandard("是");
            } else {
                tPssrAirtight.setUptoStandard("否");
            }
        } catch (Exception e) {
            tPssrAirtight.setUptoStandard("否");
        }
    }

    /**
     * 修改气密
     */
    @PreAuthorize("@ss.hasPermi('pssr:airtight:edit')")
    @Log(title = "气密", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrAirtight tPssrAirtight) {
        TPssrAirtight entity = tPssrAirtightService.selectTPssrAirtightById(tPssrAirtight.getId());
        if (entity.getApproveStatus() != 1 && entity.getApproveStatus() != 0) {
            return  AjaxResult.error("当前状态不可修改！");
        }
        if (tPssrAirtight.getConfirm1().equals(tPssrAirtight.getConfirm2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        check(tPssrAirtight);
        tPssrFileService.updateFileRelevance(tPssrAirtight.getFileIds(), forShort, tPssrAirtight.getId(), tPssrAirtight.getSubId());
        return toAjax(tPssrAirtightService.updateTPssrAirtight(tPssrAirtight));
    }

    /**
     * 修改气密
     */
    @PreAuthorize("@ss.hasPermi('pssr:airtight:edit')")
    @Log(title = "气密", businessType = BusinessType.UPDATE)
    @PutMapping("/editBatch")
    public AjaxResult editBatch(@RequestBody TPssrAirtight tPssrAirtight) {
        if (tPssrAirtight.getConfirm1().equals(tPssrAirtight.getConfirm2())){
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrAirtightMapper.updateTPssrAirtightByIds(tPssrAirtight));
    }


    /**
     * 删除气密
     */
    @PreAuthorize("@ss.hasPermi('pssr:airtight:remove')")
    @Log(title = "气密", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrAirtightService.deleteTPssrAirtightByIds(ids));
    }

    /**
     * 确认气密
     */
    @PreAuthorize("@ss.hasPermi('pssr:airtight:edit')")
    @Log(title = "气密", businessType = BusinessType.UPDATE)
    @PutMapping("/confirmAirtight")
    public AjaxResult confirmAirtight(@RequestBody TPssrAirtight tPssrAirtight) {
        long queryStatus = 0;
        long approveStatus = 0;
        Date date = null;
        TPssrAirtight lock = new TPssrAirtight();
        if (tPssrAirtight.getTaskType() == 4) {
            //拆锁确认
            queryStatus = 1;
            approveStatus = 3;
            date = new Date();
            lock.setConfirm1(getUserId().toString());
        } else if (tPssrAirtight.getTaskType() == 5) {
            //上锁确认
            queryStatus = 3;
            approveStatus = 2;
            date = new Date();
            lock.setConfirm2(getUserId().toString());
        }
        // 修改状态
        if (tPssrAirtight.getIds() != null && tPssrAirtight.getIds().length > 0) {
            for (Long id : tPssrAirtight.getIds()) {
                TPssrAirtight item = tPssrAirtightService.selectTPssrAirtightById(id);
                if (item.getUptoStandard().equals("否")){
                    return AjaxResult.error("气密检查不合格，请重新确认！");
                }
                item.setApproveStatus(approveStatus);
                if (queryStatus == 3) {
                    item.setConfirmationDate(date);
                }
                tPssrAirtightService.updateTPssrAirtight(item);
            }
        } else {
            lock.setSubId(tPssrAirtight.getSubId());
            lock.setApproveStatus(queryStatus);
            for (TPssrAirtight item : tPssrAirtightService.selectTPssrAirtightList(lock)) {
                if (item.getUptoStandard().equals("否")){
                    return AjaxResult.error("气密检查不合格，请重新确认！");
                }
                if (queryStatus == 3) {
                    item.setConfirmationDate(date);
                }
                item.setApproveStatus(approveStatus);
                tPssrAirtightService.updateTPssrAirtight(item);
            }
        }
        //查询当前待审批的确认人
        TPssrAirtight entity = new TPssrAirtight();
        entity.setSubId(tPssrAirtight.getSubId());
        entity.setApproveStatus(queryStatus);
        for (TPssrAirtight item : tPssrAirtightService.selectTPssrAirtightList(entity)) {
            if (tPssrAirtight.getTaskType() == 4) {
                if (item.getConfirm1().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            } else if (tPssrAirtight.getTaskType() == 5) {
                if (item.getConfirm2().equals(getUserId().toString())) {
                    return AjaxResult.success();
                }
            }
        }

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

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

    }

    /**
     * 驳回气密
     */
    @PutMapping("/turnDownAirtight")
    public AjaxResult turnDownAirtight(@RequestBody List<TPssrAirtight> tPssrAirtights) {
        if (CollectionUtils.isNotEmpty(tPssrAirtights)) {
            Long subId = tPssrAirtights.get(0).getSubId();
            String userId = getUserId().toString();
            // 修改已选择数据的状态
            for (TPssrAirtight tPssrAirtight : tPssrAirtights) {
                TPssrAirtight blind = new TPssrAirtight();
                blind.setId(tPssrAirtight.getId());
                blind.setApproveStatus(1L);
                blind.setUpdatedate(new Date());
                blind.setUpdaterCode(getUserId().toString());
                tPssrAirtightService.updateTPssrAirtight(blind);
                // 新增驳回原因数据
                TPssrTurndown turndown = new TPssrTurndown();
                turndown.setForShort(forShort);
                turndown.setSubId(tPssrAirtight.getSubId());
                turndown.setItemId(tPssrAirtight.getId());
                turndown.setReason(tPssrAirtight.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();

            // 驳回 查询所有待审批的人员
            TPssrAirtight blind = new TPssrAirtight();
            blind.setSubId(subId);
            blind.setApproveStatus(1L);
            Set<String> installer = new HashSet<>();
            Set<String> remover = new HashSet<>();
            for (TPssrAirtight item : tPssrAirtightService.selectTPssrAirtightList(blind)) {

                // 安装人员
                installer.add(item.getConfirm1());

                //拆除人员
                remover.add(item.getConfirm2());
            }


            //处理流程节点
            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();
    }

    public String exportTmpl(List<TPssrAirtight> list) {
        OutputStream out = null;
        String filename = null;
        try {
            String tempUrl = "static/word/pssr/qm.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 (TPssrAirtight 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.getSystemName());
                row.createCell(3).setCellValue(t.getAirtightMedium());
                row.createCell(4).setCellValue(t.getAirtightPressure());
                row.createCell(5).setCellValue(t.getInitialPressure());
                row.createCell(6).setCellValue(t.getFinalPressure());
                row.createCell(7).setCellValue(t.getLeakageRate() + "%");
                row.createCell(8).setCellValue(t.getStandard());
                row.createCell(9).setCellValue(t.getUptoStandard());
                row.createCell(10);
                row.createCell(11);
                try {
                    SysUser sysUser = sysUserService.selectUserById(Long.valueOf(t.getConfirm1()));
                    SysUser sysUser2 = sysUserService.selectUserById(Long.valueOf(t.getConfirm2()));
                    String confirm1 = sysUser.getSignUrl();
                    String confirm2 = sysUser2.getSignUrl();
                    ExcelUtils.insertPicture(wb, sheet, confirm1, row.getRowNum(), 10, 1, 1);
                    ExcelUtils.insertPicture(wb, sheet, confirm2, row.getRowNum(), 11, 1, 1);
                } catch (Exception e) {

                }
                row.createCell(12).setCellValue(DateUtils.dateTime(t.getConfirmationDate()));
                row.createCell(13).setCellValue(t.getRemarks());


                //渲染样式
                for (int i = 0; i < 14; i++) {
                    row.getCell(i).setCellStyle(originalStyle);
                }
                num++;
                rowIndex++;
            }
            filename = "PSSR_08_气密"  + ".xlsx";
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            wb.close();

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