package com.ruoyi.web.calculate.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.util.CellRangeAddress;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.web.calculate.domain.CmcNonparallelismCorrection;
import com.ruoyi.web.calculate.service.ICmcNonparallelismCorrectionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 非平行差改正Controller
 * 
 * @author qyx
 * @date 2026-06-22
 */
@RestController
@RequestMapping("/calculate/nonparallelismCorrection")
public class CmcNonparallelismCorrectionController extends BaseController
{
    @Autowired
    private ICmcNonparallelismCorrectionService cmcNonparallelismCorrectionService;

     /**
     * 导入Excel数据（支持多个工作表）
     * 
     * @param file           Excel文件
     * @param sheetNames     工作表名称列表（可选，为空时读取所有工作表）
     * @param columnMappings 列映射配置（可选）
     */
    @PostMapping("/import")
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file,
            @RequestParam(value = "sheetNames", required = false) List<String> sheetNames,
            @RequestParam(value = "columnMappings", required = false) String columnMappings) {
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                return AjaxResult.error("请选择要导入的文件！");
            }

            // 检查文件格式
            String fileName = file.getOriginalFilename();
            if (fileName == null || (!fileName.endsWith(".xls") && !fileName.endsWith(".xlsx"))) {
                return AjaxResult.error("请上传Excel文件（.xls或.xlsx格式）！");
            }

            // 调用Service层解析Excel并返回数据
            return cmcNonparallelismCorrectionService.importExcelData(file, sheetNames, columnMappings);

        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }

    /**
     * 导出非平行差改正列表（两个表在同一个Excel文件的两个sheet中）
     */
    @Log(title = "非平行差改正", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody Map<String, Object> exportData)
    {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            
            // 解析测段高差表数据
            List<CmcNonparallelismCorrection> heightDifferenceData = objectMapper.convertValue(
                exportData.get("heightDifferenceData"),
                new TypeReference<List<CmcNonparallelismCorrection>>() {}
            );
            
            // 解析不平行改正表数据
            List<CmcNonparallelismCorrection> correctionData = objectMapper.convertValue(
                exportData.get("correctionData"),
                new TypeReference<List<CmcNonparallelismCorrection>>() {}
            );
            
            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            
            // 创建测段高差表sheet
            createHeightDifferenceSheet(workbook, heightDifferenceData);
            
            // 创建不平行改正表sheet
            createCorrectionSheet(workbook, correctionData);
            
            // 设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=非平行差改正结果.xlsx");
            
            // 写入响应流
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            outputStream.close();
            workbook.close();
            
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("导出失败：" + e.getMessage());
        }
    }
    
    /**
     * 创建测段高差表sheet
     */
    private void createHeightDifferenceSheet(Workbook workbook, List<CmcNonparallelismCorrection> dataList) {
        Sheet sheet = workbook.createSheet("测段高差表");
        
        // 创建表头样式
        CellStyle headerStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headerStyle.setBorderBottom(BorderStyle.THIN);
        headerStyle.setBorderTop(BorderStyle.THIN);
        headerStyle.setBorderLeft(BorderStyle.THIN);
        headerStyle.setBorderRight(BorderStyle.THIN);
        
        // 创建数据样式
        CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setAlignment(HorizontalAlignment.CENTER);
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        dataStyle.setBorderBottom(BorderStyle.THIN);
        dataStyle.setBorderTop(BorderStyle.THIN);
        dataStyle.setBorderLeft(BorderStyle.THIN);
        dataStyle.setBorderRight(BorderStyle.THIN);
        
        // 创建表头行
        Row headerRow = sheet.createRow(0);
        String[] headers = {"序号", "起点号", "终点号", "站数", "距离(m)", "高差值(m)", 
                           "标尺真长(m)", "平均距离(km)", "平均尺改高差(m)", "往返较差(mm)", "限差(mm)", "精度统计", "质量评分"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
            sheet.setColumnWidth(i, 4000);
        }
        
        // 填充数据
        if (dataList != null && !dataList.isEmpty()) {
            for (int i = 0; i < dataList.size(); i++) {
                Row row = sheet.createRow(i + 1);
                CmcNonparallelismCorrection item = dataList.get(i);
                
                // 序号（每两行显示一个序号）
                createCell(row, 0, Math.floor(i / 2) + 1, dataStyle);
                createCell(row, 1, item.getStartPointNo(), dataStyle);
                createCell(row, 2, item.getEndPointNo(), dataStyle);
                createCell(row, 3, item.getStationCount(), dataStyle);
                createCell(row, 4, item.getDistance(), dataStyle);
                createCell(row, 5, item.getHeightDifference(), dataStyle);
                createCell(row, 6, item.getScaleTrueLength(), dataStyle);
                createCell(row, 7, item.getAverageDistance(), dataStyle);
                createCell(row, 8, item.getAverageScaleCorrectedHeightDiff(), dataStyle);
                createCell(row, 9, item.getRoundTripDifference(), dataStyle);
                createCell(row, 10, item.getTolerance(), dataStyle);
                createCell(row, 11, item.getPrecisionStatistics(), dataStyle);
                createCell(row, 12, item.getQualityScore(), dataStyle);
            }
            
            // 合并单元格：每两行合并一次
            // 需要合并的列索引：0: 序号, 7: 平均距离(km), 8: 平均尺改高差(m), 9: 往返较差(mm), 10: 限差(mm), 11: 精度统计, 12: 质量评分
            int[] mergeColumns = {0, 7, 8, 9, 10, 11, 12};
            for (int i = 0; i < dataList.size(); i += 2) {
                for (int colIndex : mergeColumns) {
                    if (i + 1 < dataList.size()) {
                        // 合并当前行和下一行
                        sheet.addMergedRegion(new CellRangeAddress(i + 1, i + 2, colIndex, colIndex));
                    }
                }
            }
        }
    }
    
    /**
     * 创建不平行改正表sheet
     */
    private void createCorrectionSheet(Workbook workbook, List<CmcNonparallelismCorrection> dataList) {
        Sheet sheet = workbook.createSheet("不平行改正表");
        
        // 创建表头样式
        CellStyle headerStyle = workbook.createCellStyle();
        Font headerFont = workbook.createFont();
        headerFont.setBold(true);
        headerStyle.setFont(headerFont);
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        headerStyle.setBorderBottom(BorderStyle.THIN);
        headerStyle.setBorderTop(BorderStyle.THIN);
        headerStyle.setBorderLeft(BorderStyle.THIN);
        headerStyle.setBorderRight(BorderStyle.THIN);
        
        // 创建数据样式
        CellStyle dataStyle = workbook.createCellStyle();
        dataStyle.setAlignment(HorizontalAlignment.CENTER);
        dataStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        dataStyle.setBorderBottom(BorderStyle.THIN);
        dataStyle.setBorderTop(BorderStyle.THIN);
        dataStyle.setBorderLeft(BorderStyle.THIN);
        dataStyle.setBorderRight(BorderStyle.THIN);
        
        // 创建表头行
        Row headerRow = sheet.createRow(0);
        String[] headers = {"待求点", "纵坐标X(m)", "横坐标Y(m)", "高程H(m)", "带号", "带宽(°)",
                           "大地经度(°′″)", "大地纬度(°′″)", "点间改正ε(m)", "改正后高差(m)", "高程(m)",
                           "距起点距离(m)", "高程中误差(m)"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
            sheet.setColumnWidth(i, 5000);
        }
        
        // 填充数据
        if (dataList != null && !dataList.isEmpty()) {
            for (int i = 0; i < dataList.size(); i++) {
                Row row = sheet.createRow(i + 1);
                CmcNonparallelismCorrection item = dataList.get(i);
                
                createCell(row, 0, item.getPendingPoint(), dataStyle);
                createCell(row, 1, item.getCoordinateX(), dataStyle);
                createCell(row, 2, item.getCoordinateY(), dataStyle);
                createCell(row, 3, item.getHeightH(), dataStyle);
                createCell(row, 4, item.getZoneNo(), dataStyle);
                createCell(row, 5, item.getBandWidth(), dataStyle);
                createCell(row, 6, item.getGeodeticLongitude(), dataStyle);
                createCell(row, 7, item.getGeodeticLatitude(), dataStyle);
                createCell(row, 8, item.getPointCorrection(), dataStyle);
                createCell(row, 9, item.getCorrectedHeightDifference(), dataStyle);
                createCell(row, 10, item.getElevation(), dataStyle);
                createCell(row, 11, item.getDistanceFromStart(), dataStyle);
                createCell(row, 12, item.getHeightMiddleError(), dataStyle);
            }
            
            // 合并单元格：每两行合并一次
            // 需要合并的列索引：8: 点间改正ε(m), 9: 改正后高差(m)
            int[] mergeColumns = {8, 9};
            for (int i = 0; i < dataList.size(); i += 2) {
                for (int colIndex : mergeColumns) {
                    if (i + 1 < dataList.size()) {
                        // 合并当前行和下一行
                        sheet.addMergedRegion(new CellRangeAddress(i + 1, i + 2, colIndex, colIndex));
                    }
                }
            }
        }
    }
    
    /**
     * 创建单元格并设置值
     */
    private void createCell(Row row, int column, Object value, CellStyle style) {
        Cell cell = row.createCell(column);
        if (value == null) {
            cell.setCellValue("");
        } else if (value instanceof Number) {
            cell.setCellValue(((Number) value).doubleValue());
        } else {
            cell.setCellValue(value.toString());
        }
        cell.setCellStyle(style);
    }

    /**
     * 执行非平行差改正计算（仅计算，不保存）
     */
    @PostMapping("/calculate")
    public AjaxResult calculate(@RequestBody List<CmcNonparallelismCorrection> dataList)
    {
        List<CmcNonparallelismCorrection> result = cmcNonparallelismCorrectionService.calculateNonparallelismCorrection(dataList);
        return success(result);
    }
}
