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.TCommonuseBicycle;
import com.ruoyi.project.patrol.commonuse.service.ITCommonuseBicycleService;
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 javax.servlet.http.HttpServletResponse;
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-09
 */
@RestController
@RequestMapping("/commonuse/bicycle")
public class TCommonuseBicycleController extends BaseController {
    @Autowired
    private ITCommonuseBicycleService tCommonuseBicycleService;

    @Autowired
    private ITPatrolPlanService tPatrolPlanService;

    @Autowired
    private ITPatrolIssuesService tPatrolIssuesService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询自行车列表
     */
    @PreAuthorize("@ss.hasPermi('commonuse:bicycle:list')")
    @GetMapping("/list")
    public TableDataInfo list(TCommonuseBicycle tCommonuseBicycle) {
        startPage();
        if (StringUtils.isEmpty(tCommonuseBicycle.getIssuesFlag()))
            tCommonuseBicycle.setIssuesFlag("0");
        List<TCommonuseBicycle> list = tCommonuseBicycleService.selectTCommonuseBicycleList(tCommonuseBicycle);
        return getDataTable(list);
    }

    /**
     * 导出自行车列表
     */
    
    @Log(title = "自行车", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public AjaxResult export(TCommonuseBicycle tCommonuseBicycle) {
        try {
            tCommonuseBicycle.setIssuesFlag("0");
            List<TCommonuseBicycle> list = tCommonuseBicycleService.selectTCommonuseBicycleList(tCommonuseBicycle);
            XSSFWorkbook workbook = new XSSFWorkbook();
            // 创建工作簿
            XSSFSheet sheet = workbook.createSheet();
            // 设置列宽
            sheet.setColumnWidth(0, 2500);
            sheet.setColumnWidth(1, 2500);
            sheet.setColumnWidth(2, 2500);
            sheet.setColumnWidth(3, 2500);
            sheet.setColumnWidth(4, 2500);
            sheet.setColumnWidth(5, 2500);
            sheet.setColumnWidth(6, 2500);
            sheet.setColumnWidth(7, 2500);
            sheet.setColumnWidth(8, 2500);
            sheet.setColumnWidth(9, 2500);
            sheet.setColumnWidth(10, 2500);
            sheet.setColumnWidth(11, 2500);
            sheet.setColumnWidth(12, 2500);
            sheet.setColumnWidth(13, 2500);
            sheet.setColumnWidth(14, 2500);
            sheet.setColumnWidth(15, 2500);
            sheet.setColumnWidth(16, 2500);

            //第一行
            XSSFRow row1 = sheet.createRow(0);
            row1.createCell(0).setCellValue("CBP-6.3.0-SCFSH-020.24  Rev:04  2021/10/01");
            ExcelUtils.createVoidCell(1, 16, row1);
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 16));//合并
            //第二行
            XSSFRow row2 = sheet.createRow(1);
            row2.createCell(0).setCellValue("自行车检查记录");
            row2.setHeightInPoints(30);
            ExcelUtils.createVoidCell(1, 16, row2);
            sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 16));
            //第三行
            XSSFRow row3 = sheet.createRow(2);
            row3.createCell(0).setCellValue("年度：" + tCommonuseBicycle.getYear());
            ExcelUtils.createVoidCell(1, 16, row3);
            row3.createCell(1).setCellValue("检查频率：1次/3月");
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 1, 16));
            //第四行
            XSSFRow row4 = sheet.createRow(3);
            row4.createCell(1).setCellValue("检查内容");
            sheet.addMergedRegion(new CellRangeAddress(3, 3, 1, 16));
            sheet.addMergedRegion(new CellRangeAddress(2, 3, 0, 0));
            //第五行
            XSSFRow row5 = sheet.createRow(4);
            row5.setHeightInPoints(80);
            row5.createCell(0).setCellValue("自行车编号");
            row5.createCell(1).setCellValue("外观检查完好");
            row5.createCell(2).setCellValue("前后轮车胎气压正常");
            row5.createCell(3).setCellValue("脚蹬无破损");
            row5.createCell(4).setCellValue("前后手刹完好，功能正常");
            row5.createCell(5).setCellValue("车铃铛完好，能正常使用");
            row5.createCell(6).setCellValue("自行车链条完好");
            row5.createCell(7).setCellValue("反光贴正常");
            row5.createCell(8).setCellValue("自行车支架完好");
            row5.createCell(9).setCellValue("车坐垫完好，无损坏");
            row5.createCell(10).setCellValue("前后轮挡泥板完好");
            row5.createCell(11).setCellValue("前后轮车辐条完好");
            row5.createCell(12).setCellValue("前后轮钢圈完好");
            row5.createCell(13).setCellValue("车锁完好，功能正常");
            row5.createCell(14).setCellValue("自行车编号清晰，无污损");
            row5.createCell(15).setCellValue("自行车后座支架完好，无松动");
            row5.createCell(16).setCellValue("检查人");
            Long planId = null;
            //遍历数组赋值
            for (int i = 0; i < list.size(); i++) {
                TCommonuseBicycle bicycle = list.get(i);
                planId = bicycle.getPlanId();
                XSSFRow row = sheet.createRow(5 + i);
                row.createCell(0).setCellValue(bicycle.getDevNo());
                row.createCell(1).setCellValue("1".equals(bicycle.getAppearance()) ? "√" : bicycle.getAppearance());
                row.createCell(2).setCellValue("1".equals(bicycle.getNormobaria()) ? "√" : bicycle.getNormobaria());
                row.createCell(3).setCellValue("1".equals(bicycle.getPedalCondition()) ? "√" : bicycle.getPedalCondition());
                row.createCell(4).setCellValue("1".equals(bicycle.getHandbrakeIntact()) ? "√" : bicycle.getHandbrakeIntact());
                row.createCell(5).setCellValue("1".equals(bicycle.getBellIntact()) ? "√" : bicycle.getBellIntact());
                row.createCell(6).setCellValue("1".equals(bicycle.getHingeIntact()) ? "√" : bicycle.getHingeIntact());
                row.createCell(7).setCellValue("1".equals(bicycle.getNormalReflector()) ? "√" : bicycle.getNormalReflector());
                row.createCell(8).setCellValue("1".equals(bicycle.getSupportIntact()) ? "√" : bicycle.getSupportIntact());
                row.createCell(9).setCellValue("1".equals(bicycle.getCushionIntact()) ? "√" : bicycle.getCushionIntact());
                row.createCell(10).setCellValue("1".equals(bicycle.getFenderIntact()) ? "√" : bicycle.getFenderIntact());
                row.createCell(11).setCellValue("1".equals(bicycle.getSpokeStripIntact()) ? "√" : bicycle.getSpokeStripIntact());
                row.createCell(12).setCellValue("1".equals(bicycle.getSteelRingIntact()) ? "√" : bicycle.getSteelRingIntact());
                row.createCell(13).setCellValue("1".equals(bicycle.getLockIntact()) ? "√" : bicycle.getLockIntact());
                row.createCell(14).setCellValue("1".equals(bicycle.getClearlyNumbered()) ? "√" : bicycle.getClearlyNumbered());
                row.createCell(15).setCellValue("1".equals(bicycle.getSupportNoLoose()) ? "√" : bicycle.getSupportNoLoose());
                XSSFCell cell10 = row.createCell(16);
                if (StringUtils.isNotEmpty(bicycle.getUpdaterCode())) {
                    SysUser sysUser = sysUserService.selectUserById(Long.valueOf(bicycle.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 = 5 + list.size();
            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, 8, 1, 1);
            ExcelUtils.createVoidCell(1, 16, row28);
            sheet.addMergedRegion(new CellRangeAddress(nextRowNum, nextRowNum, 1, 16));
            // 下一行
            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, 16, row29);
            sheet.addMergedRegion(new CellRangeAddress(nextRowNum, nextRowNum, 1, 16));
            // 设置单元格样式
            // 文字居中，自动换行，四周边框
            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) {
                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, 16, row30);
            sheet.addMergedRegion(new CellRangeAddress(nextRowNum, nextRowNum, 0, 16));

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

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

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

            //返回
            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:bicycle:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tCommonuseBicycleService.selectTCommonuseBicycleById(id));
    }

    /**
     * 获取自行车详细信息
     */
    @PreAuthorize("@ss.hasPermi('commonuse:bicycle:query')")
    @GetMapping(value = "/info")
    public AjaxResult getInfo(TCommonuseBicycle tCommonuseBicycle) {
        if (StringUtils.isNull(tCommonuseBicycle.getDevNo()) || StringUtils.isNull(tCommonuseBicycle.getPlanId())) {
            return AjaxResult.error("位置或计划id不能为空！");
        }
        TCommonuseBicycle item = new TCommonuseBicycle();
        item.setPlanId(tCommonuseBicycle.getPlanId());
        item.setPrecision(tCommonuseBicycle.getDevNo());
        item.setIssuesFlag("0");
        List<TCommonuseBicycle> list = tCommonuseBicycleService.selectTCommonuseBicycleList(item);
        if (CollectionUtils.isNotEmpty(list))
            return AjaxResult.success(list.get(0));
        return AjaxResult.error("此设备不在当前巡检计划中!");
    }

    /**
     * 新增自行车
     */
    @PreAuthorize("@ss.hasPermi('commonuse:bicycle:add')")
    @Log(title = "自行车", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TCommonuseBicycle tCommonuseBicycle) {
        return toAjax(tCommonuseBicycleService.insertTCommonuseBicycle(tCommonuseBicycle));
    }

    /**
     * 修改自行车
     */
    @PreAuthorize("@ss.hasPermi('commonuse:bicycle:edit')")
    @Log(title = "自行车", businessType = BusinessType.UPDATE)
    @PutMapping
    @RepeatSubmit
    public AjaxResult edit(@RequestBody TCommonuseBicycle tCommonuseBicycle) {
        tCommonuseBicycle.setUpdatedate(new Date());
        tCommonuseBicycle.setUpdaterCode(getUserId().toString());
        tCommonuseBicycle.setCheckStatus("1");
        tCommonuseBicycle.setCheckDate(new Date());
        TCommonuseBicycle item = tCommonuseBicycleService.selectTCommonuseBicycleById(tCommonuseBicycle.getId());
        TPatrolPlan tPatrolPlan = tPatrolPlanService.selectTPatrolPlanById(tCommonuseBicycle.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.isNotEquals(tCommonuseBicycle.getAppearance(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getNormobaria(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getPedalCondition(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getHandbrakeIntact(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getBellIntact(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getHingeIntact(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getNormalReflector(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getSupportIntact(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getCushionIntact(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getFenderIntact(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getSpokeStripIntact(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getSteelRingIntact(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getLockIntact(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getSupportNoLoose(), "1")
                || StringUtils.isNotEquals(tCommonuseBicycle.getClearlyNumbered(), "1")) {
            tCommonuseBicycle.setIssuesStatus("1");
            tCommonuseBicycle.setCheckStatus("0");
            tCommonuseBicycleService.updateTCommonuseBicycle(tCommonuseBicycle);
            tCommonuseBicycle.setIssuesFlag("1");
            tCommonuseBicycle.setCheckStatus("1");
            tCommonuseBicycle.setCreatedate(new Date());
            tCommonuseBicycle.setCreaterCode(getUserId().toString());
            tCommonuseBicycle.setDevNo(item.getDevNo());
            tCommonuseBicycleService.insertTCommonuseBicycle(tCommonuseBicycle);
            TPatrolIssues tPatrolIssues = new TPatrolIssues();
            tPatrolIssues.setPatrolType("21");
            tPatrolIssues.setDevDescribe(tCommonuseBicycle.getDevNo());
            tPatrolIssues.setLinkId(tCommonuseBicycle.getId());
            tPatrolIssues.setStatus(0L);
            tPatrolIssuesService.insertTPatrolIssues(tPatrolIssues);
        } else {
            if ("1".equals(item.getIssuesStatus())) {
                TPatrolIssues tPatrolIssues = new TPatrolIssues();
                tPatrolIssues.setPatrolType("21");
                tPatrolIssues.setDevDescribe(item.getDevNo());
                tPatrolIssues.setCreatedate(new Date());
                for (TPatrolIssues patrolIssues : tPatrolIssuesService.selectTPatrolIssuesList(tPatrolIssues)) {
                    patrolIssues.setStatus(1L);
                    tPatrolIssuesService.updateTPatrolIssues(patrolIssues);
                }
            }
            tCommonuseBicycle.setIssuesStatus("0");
            tCommonuseBicycleService.updateTCommonuseBicycle(tCommonuseBicycle);
        }
        return AjaxResult.success();
    }

    /**
     * 删除自行车
     */
    @PreAuthorize("@ss.hasPermi('commonuse:bicycle:remove')")
    @Log(title = "自行车", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tCommonuseBicycleService.deleteTCommonuseBicycleByIds(ids));
    }
}
