package com.cpms.project.asset.controller;

import com.cpms.common.annotation.Log;
import com.cpms.common.core.controller.BaseController;
import com.cpms.common.core.domain.AjaxResult;
import com.cpms.common.core.page.TableDataInfo;
import com.cpms.common.enums.BusinessType;
import com.cpms.common.utils.DateUtils;
import com.cpms.common.utils.StringUtils;
import com.cpms.common.utils.poi.ExcelUtil;
import com.cpms.project.asset.domain.TLeakagePoints;
import com.cpms.project.asset.domain.TLeakagePointsPatrol;
import com.cpms.project.asset.domain.TLeakagePointsRecord;
import com.cpms.project.asset.service.ITLeakagePointsPatrolService;
import com.cpms.project.asset.service.ITLeakagePointsRecordService;
import com.cpms.project.asset.service.ITLeakagePointsService;
import com.cpms.system.service.ISysDictDataService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Pattern;

/**
 * 漏点巡检Controller
 *
 * @author admin
 * @date 2024-04-01
 */
@RestController
@RequestMapping("/asset/pointPatrol")
public class TLeakagePointsPatrolController extends BaseController {
    @Autowired
    private ITLeakagePointsPatrolService tLeakagePointsPatrolService;

    @Autowired
    private ITLeakagePointsRecordService tLeakagePointsRecordService;

    @Autowired
    private ITLeakagePointsService tLeakagePointsService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 查询漏点巡检列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TLeakagePointsPatrol tLeakagePointsPatrol) {
        startPage();
        if (tLeakagePointsPatrol.getCheckDateM() == null) {
            tLeakagePointsPatrol.setCheckDateM(new Date());
        }
        List<TLeakagePointsPatrol> list = tLeakagePointsPatrolService.selectTLeakagePointsPatrolList(tLeakagePointsPatrol);
        if (CollectionUtils.isNotEmpty(list)) {
            TLeakagePointsRecord record = new TLeakagePointsRecord();
            record.setPatrolId(list.get(0).getId());
            list.get(0).setRecords(tLeakagePointsRecordService.selectTLeakagePointsRecordList(record));
        }
        return getDataTable(list);
    }

    @GetMapping("/getTeams/{today}")
    public AjaxResult getTeams(@PathVariable String today) {
        String regex = "^[^a-zA-Z]*$";
        Pattern pattern = Pattern.compile(regex);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //  以2024年6月5日为基准计算
        Calendar calendar = Calendar.getInstance();
        calendar.set(2024, Calendar.JUNE, 5);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date time = calendar.getTime();
        logger.info("==============time:{}", sdf.format(time));
        Date date;
        if (StringUtils.isNotEmpty(today) && pattern.matcher(today).matches()) {
            date = DateUtils.parseDate(today);
        } else {
            date = new Date();
        }
        calendar.setTime(date);
        calendar.set(Calendar.HOUR, 1);
        calendar.set(Calendar.MINUTE, 1);
        calendar.set(Calendar.SECOND, 1);
        date = calendar.getTime();
        logger.info("==============date:{}", sdf.format(date));
        int i = DateUtils.differentDaysByMillisecond(date, time);
        logger.info("==============distance:{}", i);
        TLeakagePointsPatrol tLeakagePointsPatrol = new TLeakagePointsPatrol();
        switch (i % 4) {
            case 0:
                tLeakagePointsPatrol.setTeamM("10");
                tLeakagePointsPatrol.setTeamN("12");
                break;
            case 1:
                tLeakagePointsPatrol.setTeamM("14");
                tLeakagePointsPatrol.setTeamN("10");
                break;
            case 2:
                tLeakagePointsPatrol.setTeamM("16");
                tLeakagePointsPatrol.setTeamN("14");
                break;
            case 3:
                tLeakagePointsPatrol.setTeamM("12");
                tLeakagePointsPatrol.setTeamN("16");
                break;
        }
        return AjaxResult.success(tLeakagePointsPatrol);
    }

    /**
     * 导出漏点巡检列表
     */
    @Log(title = "漏点巡检", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TLeakagePointsPatrol tLeakagePointsPatrol) {
        List<TLeakagePointsPatrol> list = tLeakagePointsPatrolService.selectTLeakagePointsPatrolList(tLeakagePointsPatrol);
        ExcelUtil<TLeakagePointsPatrol> util = new ExcelUtil<TLeakagePointsPatrol>(TLeakagePointsPatrol.class);
        util.exportExcel(response, list, "漏点巡检数据");
    }

    @Log(title = "漏点巡检", businessType = BusinessType.EXPORT)
    @PostMapping("/exportRecord")
    public void exportRecord(HttpServletResponse response, TLeakagePointsPatrol tLeakagePointsPatrol) throws IOException {

        if (tLeakagePointsPatrol.getCheckDateM() == null) {
            tLeakagePointsPatrol.setCheckDateM(new Date());
        }
        List<TLeakagePointsPatrol> list = tLeakagePointsPatrolService.selectTLeakagePointsPatrolList(tLeakagePointsPatrol);
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        // 正文格式
        CellStyle style2 = wb.createCellStyle();
        // 内容垂直居中，四周加边框线，自动换行
        style2.setAlignment(HorizontalAlignment.CENTER);
        style2.setVerticalAlignment(VerticalAlignment.CENTER);
        style2.setBorderBottom(BorderStyle.THIN);
        style2.setBorderLeft(BorderStyle.THIN);
        style2.setBorderRight(BorderStyle.THIN);
        style2.setBorderTop(BorderStyle.THIN);
        style2.setWrapText(true);
        // 设置正文字体，字体颜色
        Font headerFont2 = wb.createFont();
        headerFont2.setFontName("Arial");
        headerFont2.setFontHeightInPoints((short) 10);
        headerFont2.setColor(IndexedColors.BLACK.getIndex());
        style2.setFont(headerFont2);
        //创建sheet页
        Sheet sheet = wb.createSheet("sheet1");
        sheet.setDefaultRowHeightInPoints(30);
        //设置列的宽度，第一个参数为列的序号，从0开始，第二参数为列宽，单位1/256个字节
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 20 * 256);
        sheet.setColumnWidth(2, 15 * 256);
        sheet.setColumnWidth(3, 20 * 256);
        sheet.setColumnWidth(4, 30 * 256);
        sheet.setColumnWidth(5, 20 * 256);
        sheet.setColumnWidth(6, 30 * 256);
        // 创建表格行并设置相应标题
        Row row0 = sheet.createRow(0);
        row0.createCell(0).setCellValue("漏点巡检记录表");
        row0.createCell(1);
        row0.createCell(3);
        row0.createCell(4);
        row0.createCell(5);
        row0.createCell(2).setCellValue("日期");
        row0.createCell(6);
        Row row1 = sheet.createRow(1);
        row1.createCell(0);
        row1.createCell(1);
        row1.createCell(3);
        row1.createCell(4);
        row1.createCell(5);
        row1.createCell(2).setCellValue("班组");
        row1.createCell(6);
        Row row2 = sheet.createRow(2);
        row2.createCell(0);
        row2.createCell(1);
        row2.createCell(2).setCellValue("时间");
        row2.createCell(3).setCellValue("早班一次");
        row2.createCell(4);
        row2.createCell(5).setCellValue("夜班一次");
        row2.createCell(6);
        Row row3 = sheet.createRow(3);
        row3.createCell(0).setCellValue("漏点编号");
        row3.createCell(1).setCellValue("漏点位置");
        row3.createCell(2).setCellValue("介质");
        row3.createCell(3).setCellValue("挂牌 (是/否)");
        row3.createCell(4).setCellValue("泄露状态 (未检出/轻微/严重)");
        row3.createCell(5).setCellValue("挂牌 (是/否)");
        row3.createCell(6).setCellValue("泄露状态 (未检出/轻微/严重)");
        // 合并单元格  参数（1：起始行，2：结束行，3：起始列，4：结束列）
        sheet.addMergedRegion(new CellRangeAddress(0, 2, 0, 1));
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 3, 4));
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 5, 6));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 3, 4));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 5, 6));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 3, 4));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 5, 6));
        if (CollectionUtils.isNotEmpty(list)) {
            TLeakagePointsRecord record = new TLeakagePointsRecord();
            TLeakagePointsPatrol patrol = list.get(0);
            record.setPatrolId(patrol.getId());
            patrol.setRecords(tLeakagePointsRecordService.selectTLeakagePointsRecordList(record));
            row0.createCell(3).setCellValue(DateUtils.dateTime(patrol.getCheckDateM()));
            row0.createCell(5).setCellValue(DateUtils.dateTime(patrol.getCheckDateN()));
            row1.createCell(3).setCellValue(
                    sysDictDataService.selectDictLabel("team_divide", patrol.getTeamM()) + "班");
            row1.createCell(5).setCellValue(
                    sysDictDataService.selectDictLabel("team_divide", patrol.getTeamN()) + "班");
            int i = 3;
            for (TLeakagePointsRecord patrolRecord : patrol.getRecords()) {
                i++;
                Row row = sheet.createRow(i);
                row.createCell(0).setCellValue(patrolRecord.getPointNo());
                row.createCell(1).setCellValue(patrolRecord.getLeakagePosition());
                row.createCell(2).setCellValue(patrolRecord.getLeakageMedium());
                row.createCell(3).setCellValue(patrolRecord.getSuspendPlateM());
                row.createCell(4).setCellValue(patrolRecord.getLeakageStatusM());
                row.createCell(5).setCellValue(patrolRecord.getSuspendPlateN());
                row.createCell(6).setCellValue(patrolRecord.getLeakageStatusN());
                setStyle(row, style2);
            }
        }
        setStyle(row0, style2);
        setStyle(row1, style2);
        setStyle(row2, style2);
        setStyle(row3, style2);
        // 生成文件返回下载地址
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        wb.write(response.getOutputStream());
        wb.close();
    }

    /**
     * 设置单元格格式
     *
     * @param row   行
     * @param style 单元格样式
     */
    private void setStyle(Row row, CellStyle style) {
        for (int i = 0; i <= 6; i++) {
            row.getCell(i).setCellStyle(style);
        }
    }

    /**
     * 获取漏点巡检详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tLeakagePointsPatrolService.selectTLeakagePointsPatrolById(id));
    }

    /**
     * 新增漏点巡检
     */
    @Log(title = "漏点巡检", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TLeakagePointsPatrol tLeakagePointsPatrol) {
        tLeakagePointsPatrol.setCheckDateN(tLeakagePointsPatrol.getCheckDateM());
        TLeakagePointsPatrol patrol = new TLeakagePointsPatrol();
        patrol.setCheckDateM(tLeakagePointsPatrol.getCheckDateM());
        List<TLeakagePointsPatrol> list = tLeakagePointsPatrolService.selectTLeakagePointsPatrolList(patrol);
        if (CollectionUtils.isNotEmpty(list)) {
            return AjaxResult.warn("当前日期已存在巡检记录！");
        }
        tLeakagePointsPatrolService.insertTLeakagePointsPatrol(tLeakagePointsPatrol);
        TLeakagePoints tLeakagePoints = new TLeakagePoints();
        tLeakagePoints.setLeakageEliminationResult("1,2");
        for (TLeakagePoints leakagePoints : tLeakagePointsService.selectTLeakagePointsList(tLeakagePoints)) {
            TLeakagePointsRecord record = new TLeakagePointsRecord();
            record.setPatrolId(tLeakagePointsPatrol.getId());
            record.setPointNo(leakagePoints.getPointNo());
            record.setLeakagePosition(leakagePoints.getLeakagePosition());
            record.setLeakageMedium(leakagePoints.getLeakageMedium());
            record.setCreatedate(new Date());
            record.setCreaterCode(getUserId().toString());
            tLeakagePointsRecordService.insertTLeakagePointsRecord(record);
        }
        return toAjax(1);
    }

    /**
     * 修改漏点巡检
     */
    @Log(title = "漏点巡检", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TLeakagePointsPatrol tLeakagePointsPatrol) {
        if (CollectionUtils.isNotEmpty(tLeakagePointsPatrol.getRecords())) {
            tLeakagePointsPatrol.getRecords().forEach(item -> {
                item.setUpdatedate(new Date());
                item.setUpdaterCode(getUserId().toString());
                tLeakagePointsRecordService.updateTLeakagePointsRecord(item);
            });
        }
        return toAjax(tLeakagePointsPatrolService.updateTLeakagePointsPatrol(tLeakagePointsPatrol));
    }

    /**
     * 删除漏点巡检
     */
    @Log(title = "漏点巡检", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tLeakagePointsPatrolService.deleteTLeakagePointsPatrolByIds(ids));
    }


}
