package com.ruoyi.project.patrol.commonuse.controller;

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.interceptor.annotation.RepeatSubmit;
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.patrol.commonuse.domain.TCommonuseManholeCover;
import com.ruoyi.project.patrol.commonuse.service.ITCommonuseManholeCoverService;
import com.ruoyi.project.patrol.patrol.domain.TPatrolIssues;
import com.ruoyi.project.patrol.patrol.domain.TPatrolPlan;
import com.ruoyi.project.patrol.patrol.service.ITPatrolIssuesService;
import com.ruoyi.project.patrol.patrol.service.ITPatrolPlanService;
import com.ruoyi.project.system.domain.SysUser;
import com.ruoyi.project.system.service.ISysUserService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
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 java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 地井盖Controller
 *
 * @author admin
 * @date 2023-11-08
 */
@RestController
@RequestMapping("/commonuse/cover")
public class TCommonuseManholeCoverController extends BaseController {
    @Autowired
    private ITCommonuseManholeCoverService tCommonuseManholeCoverService;

    @Autowired
    private ITPatrolPlanService tPatrolPlanService;

    @Autowired
    private ITPatrolIssuesService tPatrolIssuesService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询地井盖列表
     */
    @PreAuthorize("@ss.hasPermi('commonuse:cover:list')")
    @GetMapping("/list")
    public TableDataInfo list(TCommonuseManholeCover tCommonuseManholeCover) {
        startPage();
        if (StringUtils.isEmpty(tCommonuseManholeCover.getIssuesFlag()))
            tCommonuseManholeCover.setIssuesFlag("0");
        List<TCommonuseManholeCover> list = tCommonuseManholeCoverService.selectTCommonuseManholeCoverList(tCommonuseManholeCover);
        return getDataTable(list);
    }

    /**
     * 导出地井盖列表
     */
    
    @Log(title = "地井盖", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(TCommonuseManholeCover tCommonuseManholeCover) {
        try {
            tCommonuseManholeCover.setIssuesFlag("0");
            List<TCommonuseManholeCover> list = tCommonuseManholeCoverService.selectTCommonuseManholeCoverList(tCommonuseManholeCover);
            XSSFWorkbook workbook = new XSSFWorkbook();
            // 创建工作簿
            XSSFSheet sheet = workbook.createSheet();
            // 设置列宽
            sheet.setColumnWidth(0, 2500);
            sheet.setColumnWidth(1, 2500);
            sheet.setColumnWidth(2, 4000);
            sheet.setColumnWidth(3, 2500);
            sheet.setColumnWidth(4, 2500);
            sheet.setColumnWidth(5, 2500);
            sheet.setColumnWidth(6, 2500);
            sheet.setColumnWidth(7, 2500);
            sheet.setColumnWidth(8, 4000);
            sheet.setColumnWidth(9, 2500);
            sheet.setColumnWidth(10, 2500);
            sheet.setColumnWidth(11, 2500);
            ;
            //第一行
            XSSFRow row1 = sheet.createRow(0);
            row1.createCell(0).setCellValue("CBP-6.3.0-SCFSH-020.25  Rev:04  2021/10/01");
            ExcelUtils.createVoidCell(1, 11, row1);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 11));//合并
            //第二行
            XSSFRow row2 = sheet.createRow(1);
            row2.createCell(0).setCellValue("地井盖检查记录");
            row2.setHeightInPoints(30);
            ExcelUtils.createVoidCell(1, 11, row2);
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 11));
            //第三行
            XSSFRow row3 = sheet.createRow(2);
            row3.createCell(0).setCellValue("年度：" + tCommonuseManholeCover.getYear());
            ExcelUtils.createVoidCell(1, 5, row3);
            row3.createCell(6).setCellValue("检查频率：1次/六个月");
            ExcelUtils.createVoidCell(7, 11, row3);
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 5));
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 6, 11));
            //第四行
            XSSFRow row4 = sheet.createRow(3);
            row4.createCell(0).setCellValue("序号");
            row4.createCell(1).setCellValue("位号");
            row4.createCell(2).setCellValue("位置");
            row4.createCell(3).setCellValue("检查内容");
            row4.createCell(6).setCellValue("序号");
            row4.createCell(7).setCellValue("位号");
            row4.createCell(8).setCellValue("位置");
            row4.createCell(9).setCellValue("检查内容");
            ExcelUtils.createVoidCell(10, 11, row4);
            sheet.addMergedRegion(new CellRangeAddress(3, 3, 3, 5));
            sheet.addMergedRegion(new CellRangeAddress(3, 3, 9, 11));
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 0, 0));
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 1, 1));
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 2, 2));
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 6, 6));
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 7, 7));
            sheet.addMergedRegion(new CellRangeAddress(3, 4, 8, 8));
            //第五行
            XSSFRow row5 = sheet.createRow(4);
            row5.setHeightInPoints(30);
            row5.createCell(3).setCellValue("地井盖是否缺失");
            row5.createCell(4).setCellValue("地井盖外观");
            row5.createCell(5).setCellValue("检查人");
            row5.createCell(9).setCellValue("地井盖是否缺失");
            row5.createCell(10).setCellValue("地井盖外观");
            row5.createCell(11).setCellValue("检查人");
            ExcelUtils.createVoidCell(0, 1, row5);
            ExcelUtils.createVoidCell(6, 7, row5);
            Long planId = null;
            int n = 0;
            int m = 5;
            boolean br = false;
            //遍历数组赋值
            for (int i = 0; i < list.size(); i++) {
                if (list.size() / 2 == i) {
                    n = 6;
                    br = true;
                }
                TCommonuseManholeCover cover = list.get(i);
                planId = cover.getPlanId();
                XSSFRow row;
                if (br) {
                    row = sheet.getRow(m);
                    m++;
                } else {
                    row = sheet.createRow(5 + i);
                }
                row.createCell(n).setCellValue(i+1);
                row.createCell(1 + n).setCellValue(cover.getDevNo());
                row.createCell(2 + n).setCellValue(cover.getPosition());
                row.createCell(3 + n).setCellValue("1".equals(cover.getDeficiency()) ? "√" : cover.getDeficiency());
                row.createCell(4 + n).setCellValue("1".equals(cover.getAppearance()) ? "√" : cover.getAppearance());
                XSSFCell cell10 = row.createCell(5 + n);
                if (StringUtils.isNotEmpty(cover.getUpdaterCode())) {
                    SysUser sysUser = sysUserService.selectUserById(Long.valueOf(cover.getUpdaterCode()));
                    cell10.setCellValue(sysUser == null ? "" : sysUser.getNickName());
                }
            }
            String confirmed = "";
            Date confirmedDate = null;
            TPatrolPlan tPatrolPlan = tPatrolPlanService.selectTPatrolPlanById(planId);
            if (Objects.nonNull(tPatrolPlan) && Objects.nonNull(tPatrolPlan.getConfirmed())) {
                SysUser sysUser = sysUserService.selectUserById(Long.valueOf(tPatrolPlan.getConfirmed()));            if (sysUser!=null) {
                confirmed = sysUser.getSignUrl();
                confirmedDate = tPatrolPlan.getConfirmDate();
            }
            }
            // 循环后下一行
            int nextRowNum = m;
            XSSFRow row28 = sheet.createRow(nextRowNum);
            row28.setHeightInPoints(30);
            XSSFCell row28Cell1 = row28.createCell(0);
            row28Cell1.setCellValue("签名");
            if (StringUtils.isNotEmpty(confirmed))
                ExcelUtils.insertPicture(workbook, sheet, confirmed, nextRowNum, 7, 1, 1);
            ExcelUtils.createVoidCell(1, 11, row28);
            sheet.addMergedRegion(new CellRangeAddress(nextRowNum, nextRowNum, 1, 11));
            // 下一行
            nextRowNum++;
            XSSFRow row29 = sheet.createRow(nextRowNum);
            row29.setHeightInPoints(30);
            XSSFCell row29Cell1 = row29.createCell(0);
            row29Cell1.setCellValue("日期");
            row29.createCell(1).setCellValue(confirmedDate != null ? new SimpleDateFormat("yyyy-MM-dd").format(confirmedDate) : "");
            ExcelUtils.createVoidCell(2, 11, row29);
            sheet.addMergedRegion(new CellRangeAddress(nextRowNum, nextRowNum, 1, 11));
            // 下一行
            nextRowNum++;
            XSSFRow rowbz = sheet.createRow(nextRowNum);
            rowbz.setHeightInPoints(30);
            XSSFCell rowbzCell1 = rowbz.createCell(0);
            rowbzCell1.setCellValue("备注");
            ExcelUtils.createVoidCell(1, 11, rowbz);
            sheet.addMergedRegion(new CellRangeAddress(nextRowNum, nextRowNum, 1, 11));
            // 设置单元格样式
            // 文字居中，自动换行，四周边框
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.CENTER);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            style.setWrapText(true);
            style.setBorderTop(BorderStyle.THIN);
            style.setBorderBottom(BorderStyle.THIN);
            style.setBorderLeft(BorderStyle.THIN);
            style.setBorderRight(BorderStyle.THIN);
            for (Row row : sheet) {
                row.setHeightInPoints(30);
                if (row.getRowNum() == 0) {
                    continue;
                }
                for (Cell cell : row) {
                    cell.setCellStyle(style);
                }

            }
            nextRowNum++;
            XSSFRow row30 = sheet.createRow(nextRowNum);
            row30.createCell(0).setCellValue("说明：");
            ExcelUtils.createVoidCell(1, 11, row30);
            sheet.addMergedRegion(new CellRangeAddress(nextRowNum, nextRowNum, 0, 11));

            nextRowNum++;
            XSSFRow row31 = sheet.createRow(nextRowNum);
            row31.createCell(0).setCellValue("1.检查正常打“√”。");
            ExcelUtils.createVoidCell(1, 11, row31);
            sheet.addMergedRegion(new CellRangeAddress(nextRowNum, nextRowNum, 0, 11));

            nextRowNum++;
            XSSFRow row32 = sheet.createRow(nextRowNum);
            row32.createCell(0).setCellValue("2.检查有不正常情况打“X”，并记录存在问题，处理结果及完成时间。");
            ExcelUtils.createVoidCell(1, 11, row32);
            sheet.addMergedRegion(new CellRangeAddress(nextRowNum, nextRowNum, 0, 11));

            nextRowNum++;
            XSSFRow row33 = sheet.createRow(nextRowNum);
            row33.createCell(0).setCellValue("3. 检查频率为每六个月检查维护一次。");
            ExcelUtils.createVoidCell(1, 11, row33);
            sheet.addMergedRegion(new CellRangeAddress(nextRowNum, nextRowNum, 0, 11));

            //返回
            String fileName = ExcelUtil.encodingFilename("main");
            OutputStream os = Files.newOutputStream(Paths.get(ExcelUtil.getAbsoluteFile(fileName)));
            workbook.write(os);
            workbook.close();
            return AjaxResult.success(fileName);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取地井盖详细信息
     */
    @PreAuthorize("@ss.hasPermi('commonuse:cover:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tCommonuseManholeCoverService.selectTCommonuseManholeCoverById(id));
    }

    /**
     * 获取地井盖详细信息
     */
    @PreAuthorize("@ss.hasPermi('commonuse:cover:query')")
    @GetMapping(value = "/info")
    public AjaxResult getInfo(TCommonuseManholeCover tCommonuseManholeCover) {
        if (StringUtils.isEmpty(tCommonuseManholeCover.getDevNo()) || StringUtils.isNull(tCommonuseManholeCover.getPlanId())) {
            return AjaxResult.error("位号或计划id不能为空！");
        }
        TCommonuseManholeCover item = new TCommonuseManholeCover();
        item.setPlanId(tCommonuseManholeCover.getPlanId());
        item.setPrecision(tCommonuseManholeCover.getDevNo());
        item.setIssuesFlag("0");
        List<TCommonuseManholeCover> list = tCommonuseManholeCoverService.selectTCommonuseManholeCoverList(item);
        if (CollectionUtils.isNotEmpty(list))
            return AjaxResult.success(list.get(0));
        return AjaxResult.error("此设备不在当前巡检计划中!");
    }

    /**
     * 新增地井盖
     */
    @PreAuthorize("@ss.hasPermi('commonuse:cover:add')")
    @Log(title = "地井盖", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TCommonuseManholeCover tCommonuseManholeCover) {
        return toAjax(tCommonuseManholeCoverService.insertTCommonuseManholeCover(tCommonuseManholeCover));
    }

    /**
     * 修改地井盖
     */
    @PreAuthorize("@ss.hasPermi('commonuse:cover:edit')")
    @Log(title = "地井盖", businessType = BusinessType.UPDATE)
    @PutMapping
    @RepeatSubmit
    public AjaxResult edit(@RequestBody TCommonuseManholeCover tCommonuseManholeCover) {
        tCommonuseManholeCover.setUpdatedate(new Date());
        tCommonuseManholeCover.setUpdaterCode(getUserId().toString());
        tCommonuseManholeCover.setCheckStatus("1");
        tCommonuseManholeCover.setCheckDate(new Date());
        TCommonuseManholeCover item = tCommonuseManholeCoverService.selectTCommonuseManholeCoverById(tCommonuseManholeCover.getId());
        TPatrolPlan tPatrolPlan = tPatrolPlanService.selectTPatrolPlanById(tCommonuseManholeCover.getPlanId());
        if (tPatrolPlan.getStatus()==1){
            return AjaxResult.error("当前选择的计划已确认！");
        }
        if (!"1".equals(item.getCheckStatus())) {
            tPatrolPlan.setUncheckedNum(tPatrolPlan.getUncheckedNum() - 1);
            tPatrolPlan.setCheckedNum(tPatrolPlan.getCheckedNum() + 1);
            tPatrolPlanService.updateTPatrolPlan(tPatrolPlan);
        }
        if ((StringUtils.isNotEmpty(tCommonuseManholeCover.getAppearance()) && !"1".equals(tCommonuseManholeCover.getAppearance())) ||
                (StringUtils.isNotEmpty(tCommonuseManholeCover.getDeficiency()) && !"1".equals(tCommonuseManholeCover.getDeficiency()))) {
            tCommonuseManholeCover.setIssuesStatus("1");
            tCommonuseManholeCover.setCheckStatus("0");
            tCommonuseManholeCoverService.updateTCommonuseManholeCover(tCommonuseManholeCover);
            tCommonuseManholeCover.setIssuesFlag("1");
            tCommonuseManholeCover.setCheckStatus("1");
            tCommonuseManholeCover.setCreatedate(new Date());
            tCommonuseManholeCover.setCreaterCode(getUserId().toString());
            tCommonuseManholeCover.setDevNo(item.getDevNo());
            tCommonuseManholeCover.setPosition(item.getPosition());
            tCommonuseManholeCoverService.insertTCommonuseManholeCover(tCommonuseManholeCover);
            TPatrolIssues tPatrolIssues = new TPatrolIssues();
            tPatrolIssues.setPatrolType("22");
            tPatrolIssues.setDevDescribe(tCommonuseManholeCover.getDevNo() + " " + tCommonuseManholeCover.getPosition());
            tPatrolIssues.setLinkId(tCommonuseManholeCover.getId());
            tPatrolIssues.setStatus(0L);
            tPatrolIssuesService.insertTPatrolIssues(tPatrolIssues);
        } else {
            if ("1".equals(item.getIssuesStatus())) {
                TPatrolIssues tPatrolIssues = new TPatrolIssues();
                tPatrolIssues.setPatrolType("22");
                tPatrolIssues.setDevDescribe(item.getDevNo()+" "+item.getPosition());
                tPatrolIssues.setCreatedate(new Date());
                for (TPatrolIssues patrolIssues : tPatrolIssuesService.selectTPatrolIssuesList(tPatrolIssues)) {
                    patrolIssues.setStatus(1L);
                    tPatrolIssuesService.updateTPatrolIssues(patrolIssues);
                }
            }
            tCommonuseManholeCover.setIssuesStatus("0");
            tCommonuseManholeCoverService.updateTCommonuseManholeCover(tCommonuseManholeCover);
        }
        return AjaxResult.success();
    }

    /**
     * 删除地井盖
     */
    @PreAuthorize("@ss.hasPermi('commonuse:cover:remove')")
    @Log(title = "地井盖", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tCommonuseManholeCoverService.deleteTCommonuseManholeCoverByIds(ids));
    }
}
