package com.njcn.gather.aireport.testreport.component;

import com.njcn.common.pojo.enums.response.CommonResponseEnum;
import com.njcn.common.pojo.exception.BusinessException;
import com.njcn.gather.aireport.testreport.pojo.constant.TestReportConst;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Component
public class TestReportLedgerTemplateService {

    public byte[] buildTemplate() {
        try (XSSFWorkbook workbook = new XSSFWorkbook();
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            writeGuideSheet(workbook.createSheet(TestReportConst.LEDGER_GUIDE_SHEET_NAME));
            writeHeaders(workbook, workbook.createSheet(TestReportConst.LEDGER_POINT_SHEET_NAME),
                    Arrays.asList("分组号", "变电站", "监测点名称", "检测设备编号", "委托单位名称", "Excel附件名称", "Word附件名称"));
            writeHeaders(workbook, workbook.createSheet(TestReportConst.LEDGER_DEVICE_SHEET_NAME),
                    Arrays.asList("设备型号", "设备编号", "标准有效期", "设备状态", "标准报告文件名"));
            writeHeaders(workbook, workbook.createSheet(TestReportConst.LEDGER_CLIENT_SHEET_NAME),
                    Arrays.asList("单位名称", "联系人", "联系方式", "地址"));
            workbook.write(outputStream);
            return outputStream.toByteArray();
        } catch (IOException exception) {
            throw new BusinessException(CommonResponseEnum.FAIL, "下载模板失败");
        }
    }

    private void writeGuideSheet(XSSFSheet sheet) {
        Row row0 = sheet.createRow(0);
        row0.createCell(0).setCellValue("1. 汇总文件名固定为台账信息汇总，扩展名支持 .xls、.xlsx");
        Row row1 = sheet.createRow(1);
        row1.createCell(0).setCellValue("2. 监测点信息sheet必填，检测设备/委托单位sheet按需填写");
        Row row2 = sheet.createRow(2);
        row2.createCell(0).setCellValue("3. 每个监测点必须填写Excel附件名称，Word附件名称可按需填写");
        Row row3 = sheet.createRow(3);
        row3.createCell(0).setCellValue("4. 检测设备编号、委托单位名称优先匹配数据库，未命中时再匹配本次sheet");
        sheet.setColumnWidth(0, 120 * 256);
    }

    private void writeHeaders(XSSFWorkbook workbook, XSSFSheet sheet, List<String> headers) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        Row headerRow = sheet.createRow(0);
        for (int i = 0; i < headers.size(); i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers.get(i));
            cell.setCellStyle(style);
            sheet.setColumnWidth(i, 24 * 256);
        }
    }
}
