package com.ruoyi.web.calculate.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
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.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.web.calculate.domain.CmcEleDifSideLandDir;
import com.ruoyi.web.calculate.service.ICmcEleDifSideLandDirService;
import com.ruoyi.web.calculate.vo.CmcEleDifSideLandDirTemplate;

/**
 * 计算请求VO
 */
class CalculateRequest {
    private Map<String, Map<String, Integer>> columnMappings;
    private List<CmcEleDifSideLandDir> data;
    
    public Map<String, Map<String, Integer>> getColumnMappings() {
        return columnMappings;
    }
    
    public void setColumnMappings(Map<String, Map<String, Integer>> columnMappings) {
        this.columnMappings = columnMappings;
    }
    
    public List<CmcEleDifSideLandDir> getData() {
        return data;
    }
    
    public void setData(List<CmcEleDifSideLandDir> data) {
        this.data = data;
    }
}

/**
 * 高差边长方向值Controller
 * 
 * @author R
 * @date 2026-06-15
 */
@RestController
@RequestMapping("/calculate/eleDifSideLandDir")
public class CmcEleDifSideLandDirController {

    @Autowired
    private ICmcEleDifSideLandDirService cmcEleDifSideLandDirService;

    /**
     * 导入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 cmcEleDifSideLandDirService.importExcelData(file, sheetNames, columnMappings);

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

    /**
     * 导出高差边长方向值计算结果列表
     */
    @Log(title = "高差边长方向值", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody List<CmcEleDifSideLandDir> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            throw new RuntimeException("没有需要导出的数据");
        }

        List<CmcEleDifSideLandDir> exportList = new ArrayList<>();
        for (CmcEleDifSideLandDir item : dataList) {
            CmcEleDifSideLandDir exportItem = new CmcEleDifSideLandDir();
            // 测站序号
            exportItem.setStationPN(item.getStationPN());
            // 方向序号
            exportItem.setDirectionPN(item.getDirectionPN());
            // 测站坐标
            exportItem.setSPX(item.getSPX());
            exportItem.setSPY(item.getSPY());
            exportItem.setSPZ(item.getSPZ());
            // 方向坐标
            exportItem.setDPX(item.getDPX());
            exportItem.setDPY(item.getDPY());
            exportItem.setDPZ(item.getDPZ());
            // 方位角
            exportItem.setAzimuthAngle(item.getAzimuthAngle());
            exportList.add(exportItem);
        }

        ExcelUtil<CmcEleDifSideLandDir> util = new ExcelUtil<CmcEleDifSideLandDir>(CmcEleDifSideLandDir.class);
        util.exportExcel(response, exportList, "高差边长方向值计算结果");
    }

    /**
     * 执行高差边长方向值计算（仅计算，不保存）
     */
    @PostMapping("/calculate")
    public AjaxResult calculate(@RequestBody CalculateRequest request) {
        List<CmcEleDifSideLandDir> dataList = request.getData();
        Map<String, Map<String, Integer>> columnMappings = request.getColumnMappings();
        
        // 第一步：匹配测站和方向坐标
        List<CmcEleDifSideLandDir> matchedList = cmcEleDifSideLandDirService.calculateEleDifSideLandDir(dataList, columnMappings);
        // 第二步：计算方位角和角度差
        List<CmcEleDifSideLandDir> result = cmcEleDifSideLandDirService.calculateAzimuthAngle(matchedList);
        return AjaxResult.success(result);
    }
}