package com.goldenwater.slaj.hidd.controller;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.goldenwater.common.core.controller.BaseController;
import com.goldenwater.common.core.domain.AjaxResult;
import com.goldenwater.slaj.hidd.service.IBisHiddRecRepService;
import com.goldenwater.slaj.hidd.service.IBisOrgMonRepPeriService;

import jakarta.servlet.http.HttpServletResponse;

/**
 * 隐患统计导出
 */
@RestController
@RequestMapping("/hidd/hiddStat")
public class BisHiddStatController extends BaseController {
    @Autowired
    private IBisHiddRecRepService bisHiddRecRepService;
    
    @Autowired
    private IBisOrgMonRepPeriService bisOrgMonRepPeriService;

    /**
     * 导出隐患月报数据
     * @param repYear 年份
     * @param repMonth 月份（如"2025年06月"）
     * @param id 月报期间GUID
     * @param requestType 请求类型：0-新增上报类型，1-查看本单位或下级
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam(required = false) String repYear,
                       @RequestParam(required = false) String repMonth,
                       @RequestParam(required = false) String id,
                       @RequestParam(required = false) String requestType) {
        try {
            // 导出Excel文件名
            String month = repMonth != null ? repMonth : "";
            String excelName = month + "隐患月报";
            String sheetName = month + "隐患月报";
            
            // 导出的列名集合
            String[] colNameList = {"序号", "所属单位", "隐患名称", "隐患类别", "所属工程", "排查日期", "要求整改完成日期", "实际整改完成日期", "整改状态"};
            
            // 获取导出数据
            List<Map<String, Object>> data = new ArrayList<>();
            if ("1".equals(requestType) && id != null) {
                // 查看本单位或下级的月报详情
                data = bisHiddRecRepService.selectBisHiddRecRepWithHiddByRepGuid(id);
            }
            
            // 构建导出内容
            String[][] content = new String[data.size()][];
            for (int i = 0; i < data.size(); i++) {
                content[i] = new String[colNameList.length];
                Map<String, Object> obj = data.get(i);
                content[i][0] = String.valueOf(i + 1);
                content[i][1] = obj.get("orgName") != null ? obj.get("orgName").toString() : "";
                content[i][2] = obj.get("hiddName") != null ? obj.get("hiddName").toString() : "";
                content[i][3] = "2".equals(obj.get("hiddGrad")) ? "重大隐患" : "一般隐患";
                content[i][4] = obj.get("engName") != null ? obj.get("engName").toString() : "";
                content[i][5] = obj.get("inspDate") != null ? obj.get("inspDate").toString().substring(0, 10) : "--";
                content[i][6] = obj.get("requCompDate") != null ? obj.get("requCompDate").toString().substring(0, 10) : "--";
                content[i][7] = obj.get("factCompDate") != null ? obj.get("factCompDate").toString().substring(0, 10) : "--";
                String hiddStat = obj.get("hiddStat") != null ? obj.get("hiddStat").toString() : "";
                content[i][8] = "0".equals(hiddStat) ? "未落实整改" : "1".equals(hiddStat) ? "正在整改" : "2".equals(hiddStat) ? "完成整改" : "";
            }
            
            // 导出Excel
            org.apache.poi.hssf.usermodel.HSSFWorkbook wb = getHSSFWorkbook(sheetName, colNameList, content, null);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename=" + new String(excelName.getBytes("utf-8"), "ISO-8859-1") + ".xls");
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 创建HSSFWorkbook
     */
    private org.apache.poi.hssf.usermodel.HSSFWorkbook getHSSFWorkbook(String sheetName, String[] header, String[][] data, org.apache.poi.hssf.usermodel.HSSFCellStyle style) {
        org.apache.poi.hssf.usermodel.HSSFWorkbook wb = new org.apache.poi.hssf.usermodel.HSSFWorkbook();
        org.apache.poi.hssf.usermodel.HSSFSheet sheet = wb.createSheet(sheetName);
        
        // 表头样式
        org.apache.poi.hssf.usermodel.HSSFCellStyle headerStyle = wb.createCellStyle();
        org.apache.poi.hssf.usermodel.HSSFFont headerFont = wb.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);
        headerStyle.setAlignment(org.apache.poi.ss.usermodel.HorizontalAlignment.CENTER);
        
        // 写表头
        org.apache.poi.hssf.usermodel.HSSFRow headerRow = sheet.createRow(0);
        for (int i = 0; i < header.length; i++) {
            org.apache.poi.hssf.usermodel.HSSFCell cell = headerRow.createCell(i);
            cell.setCellValue(header[i]);
            cell.setCellStyle(headerStyle);
            sheet.setColumnWidth(i, 5000);
        }
        
        // 写数据
        for (int i = 0; i < data.length; i++) {
            org.apache.poi.hssf.usermodel.HSSFRow row = sheet.createRow(i + 1);
            for (int j = 0; j < data[i].length; j++) {
                org.apache.poi.hssf.usermodel.HSSFCell cell = row.createCell(j);
                cell.setCellValue(data[i][j]);
            }
        }
        
        return wb;
    }
}
