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.TPssrApprove;
import com.ruoyi.project.pssr.domain.TPssrFile;
import com.ruoyi.project.pssr.domain.TPssrSafetyBrust;
import com.ruoyi.project.pssr.mapper.TPssrSafetyBrustMapper;
import com.ruoyi.project.pssr.service.ITPssrApproveService;
import com.ruoyi.project.pssr.service.ITPssrFileService;
import com.ruoyi.project.pssr.service.ITPssrSafetyBrustService;
import com.ruoyi.project.pssr.service.ITPssrTurndownService;
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.ArrayList;
import java.util.List;

/**
 * 安全设施-爆破片Controller
 *
 * @author ssy
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/pssr/safetyBrust")
public class TPssrSafetyBrustController extends BaseController {
    @Resource
    private TPssrSafetyBrustMapper tPssrSafetyBrustMapper;
    @Autowired
    private ITPssrFileService tPssrFileService;

    @Autowired
    private ITPssrApproveService tPssrApproveService;

    @Autowired
    private ITPssrTurndownService tPssrTurndownService;
    @Autowired
    private ITPssrSafetyBrustService tPssrSafetyBrustService;

    @Autowired
    private ISysUserService sysUserService;
    private String forShort = "aqss-bt";

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysUserService userService;

    /**
     * 批量导入
     */
    @PreAuthorize("@ss.hasPermi('pssr:safetyBrust: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<TPssrSafetyBrust> list = new ArrayList<TPssrSafetyBrust>();
        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();
                TPssrSafetyBrust entity = new TPssrSafetyBrust();
                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.setSafetyDev(cellValue);
                    } else if (j == 3) {
                        entity.setInstallLocation(cellValue);
                    } else if (j == 4) {
                        entity.setSetPressure(cellValue);
                    } else if (j == 5) {
                        entity.setConfirmer1(cellValue);
                    } else if (j == 6) {
                        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 (TPssrSafetyBrust 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:safetyBrust:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrSafetyBrust tPssrSafetyBrust) {
        try {
            TPssrApprove approve = tPssrApproveService.selectTPssrApproveBySubId(tPssrSafetyBrust.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")) {
                        tPssrSafetyBrust.setConfirmer1(getUserId().toString());
                    } else if (task.getName().equals("确认人2")) {
                        tPssrSafetyBrust.setConfirmer2(getUserId().toString());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("待办确认人查询报错：{}", e.getMessage());
        }
        startPage();
        List<TPssrSafetyBrust> list = tPssrSafetyBrustService.selectTPssrSafetyBrustList(tPssrSafetyBrust);
        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(), "aqss-bt"));
        });
        return getDataTable(list);
    }

    /**
     * 导出安全设施-爆破片列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:safetyBrust:export')")
    @Log(title = "安全设施-爆破片", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrSafetyBrust tPssrSafetyBrust) {
        List<TPssrSafetyBrust> list = tPssrSafetyBrustService.selectTPssrSafetyBrustList(tPssrSafetyBrust);
        if (list.size() != 0) {
            return AjaxResult.success(exportTmpl(list));
        } else {
            return AjaxResult.error("暂无可导出数据");
        }
    }

    public String exportTmpl(List<TPssrSafetyBrust> list) {
        OutputStream out = null;
        String filename = null;
        try {
            String tempUrl = "static/word/pssr/aqssbpp.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 (TPssrSafetyBrust 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.getSafetyDev());
                row.createCell(4).setCellValue(t.getInstallLocation());
                row.createCell(5).setCellValue(t.getInstallAccuracy());
                row.createCell(6).setCellValue(t.getRightDirection());
                row.createCell(7).setCellValue(t.getPutUse());
                row.createCell(8).setCellValue(t.getSetPressure());
                row.createCell(9).setCellValue(t.getUniformPressure());
                row.createCell(10).setCellValue(t.getIs0kpa());
                row.createCell(11);
                row.createCell(12);
                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(), 11, 1, 1);
                    ExcelUtils.insertPicture(wb, sheet, confirm2, row.getRowNum(), 12, 1, 1);
                } catch (Exception e) {

                }
                row.createCell(13).setCellValue(DateUtils.dateTime(t.getConfirmationTime()));
                row.createCell(14).setCellValue(t.getRemarks());

                //渲染样式
                for (int i = 0; i < 15; i++) {
                    row.getCell(i).setCellStyle(originalStyle);
                }
                num++;
                rowIndex++;
            }
            filename = "PSSR_14_安全设施_爆破片" + ".xlsx";
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(filename));
            wb.write(out);
            wb.close();

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

    /**
     * 获取安全设施-爆破片详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:safetyBrust:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        TPssrSafetyBrust item = tPssrSafetyBrustService.selectTPssrSafetyBrustById(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(), "aqss-bt"));
        return AjaxResult.success(item);
    }

    /**
     * 新增安全设施-爆破片
     */
    @PreAuthorize("@ss.hasPermi('pssr:safetyBrust:add')")
    @Log(title = "安全设施-爆破片", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrSafetyBrust tPssrSafetyBrust) {
        if (StringUtils.isNotEmpty(tPssrSafetyBrust.getConfirmer1()) && tPssrSafetyBrust.getConfirmer1().equals(tPssrSafetyBrust.getConfirmer2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrSafetyBrust.setApproveStatus(0L);
        return toAjax(tPssrSafetyBrustService.insertTPssrSafetyBrust(tPssrSafetyBrust));
    }

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

    /**
     * 修改安全设施-爆破片
     */
    @PreAuthorize("@ss.hasPermi('pssr:safetyBrust:edit')")
    @Log(title = "安全设施-爆破片", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrSafetyBrust tPssrSafetyBrust) {
        TPssrSafetyBrust entity = tPssrSafetyBrustService.selectTPssrSafetyBrustById(tPssrSafetyBrust.getId());
        if (entity.getApproveStatus() != 1 && entity.getApproveStatus() != 0) {
            return  AjaxResult.error("当前状态不可修改！");
        }
        if (tPssrSafetyBrust.getConfirmer1().equals(tPssrSafetyBrust.getConfirmer2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        tPssrFileService.updateFileRelevance(tPssrSafetyBrust.getFileIds(), "aqss-bt", tPssrSafetyBrust.getId(), tPssrSafetyBrust.getSubId());
        return toAjax(tPssrSafetyBrustService.updateTPssrSafetyBrust(tPssrSafetyBrust));
    }

    /**
     * 修改安全设施-爆破片
     */
    @PreAuthorize("@ss.hasPermi('pssr:safetyBrust:edit')")
    @Log(title = "安全设施-爆破片", businessType = BusinessType.UPDATE)
    @PutMapping("/editBatch")
    public AjaxResult editb(@RequestBody TPssrSafetyBrust tPssrSafetyBrust) {
        if (tPssrSafetyBrust.getConfirmer1().equals(tPssrSafetyBrust.getConfirmer2())) {
            return AjaxResult.error("确认人不能为同一人，请重新选择！");
        }
        return toAjax(tPssrSafetyBrustMapper.updateTPssrSafetyBrustByIds(tPssrSafetyBrust));
    }

    /**
     * 删除安全设施-爆破片
     */
    @PreAuthorize("@ss.hasPermi('pssr:safetyBrust:remove')")
    @Log(title = "安全设施-爆破片", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrSafetyBrustService.deleteTPssrSafetyBrustByIds(ids));
    }
}
