package cn.api;

import cn.facade.abs.IService;
import cn.common.annotation.Log;
import cn.common.enums.BizOpType;
import cn.common.enums.ResultCode;
import cn.common.exception.BusinessException;
import cn.common.page.response.Result;
import cn.component.file.FileDownload;
import cn.component.util.HttpService;
import cn.constant.CharsetKit;
import cn.pojo.entity.TSysUser;
import cn.pojo.vo.LoginUser;
import cn.report.excel.util.ReadExcelUtil;
import cn.service.IEasyExcelService;
import cn.util.core.IsKit;
import cn.util.core.LogKit;
import cn.util.core.TypeKit;
import cn.util.file.FileKit;
import cn.util.core.ServletKit;
import cn.util.string.JsonKit;
import cn.util.string.StringKit;
import cn.util.uuid.UUIDKit;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
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.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * 通用文件请求处理
 */
@RestController
@RequestMapping("/api/file")
public class FileCtrl extends IService {
    @Value("${sam.file.reportTemplate}")
    private String reportDir = "";

    @Resource
    private HttpService httpService;

    @Resource
    private IEasyExcelService easyExcelService;

    private String filePath;

    ///////////////
    /**
     * 多sheet excel文件下传 支持VUE页面@RequestParam
     */
    @GetMapping("/exportSheets")
    @Log(title = "文件操作-多sheet导出-exportSheets", businessType = BizOpType.EXPORT)
    public void exportSheets(@RequestParam Map<String, Object> paramMap) {
        try {
            easyExcelService.exportSheets(paramMap);
        } catch (Exception e) {
            LogKit.info(e);
            //待验证
            ServletKit.renderString(ServletKit.getResponse(), JSON.toJSONString(Result.ok(ResultCode.FILE_EXPORT)));
        }
    }

    /**
     * 多sheet excel文件（第一行为中文表头，第二行开始为实际数据）上传, 导入excel文件内容到对应库表中
     * paramMap: 附加数据( boolean：页面需要1true;0false).
     * 示例格式：{
     * TableName=t_sys_user,
     * JsonData=[{"label":"用户ID","name":"user_id"}, {"label":"最后登陆时间","name":"login_date"}]
     * }
     * JsonData用于将中文表头翻译为对应表中字段；见前端uploadExcelModule.vue中JsonData内容（在接送文件中定义）
     */
    @PostMapping("/importSheets")
    @Log(title = "文件操作-多sheet导入-importSheets", businessType = BizOpType.IMPORT)
    public Result<?> importSheets(MultipartFile file/*不能变*/, @RequestParam Map<String, Object> extParamMap) {
        Integer result = easyExcelService.importSheets(file, extParamMap);
        if (result > 0)
            return Result.ok();
        else {
            return Result.warnMsg(ResultCode.FILE_IMPORT.getMsg());
        }
    }

    /**
     * 下载给定目录下的给定文件
     */
    @GetMapping("/downloadFile/{dirPath}/{fileName}")
    @Log(title = "文件操作作-下载文件-downloadFile", businessType = BizOpType.EXPORT)
    public void downloadFile(HttpServletResponse response,
                             @PathVariable String dirPath, @PathVariable String fileName) {
        downloadFileService.download(response, dirPath, fileName);
    }

    /**
     * 上传文件：上传数据构建是通过：formData实现
     * file 含页面所选文件信息
     * paramMap 页面所传的附加信息 Json字符串
     */
    //如果：直接用el-upload自动上传，jsonArray不需要json2Map_jackson
    //@RequestParam Map<String,Object> jsonArray
    //@RequestBody JSONObject
    @PostMapping("/uploadFile")
    @Log(title = "文件操作-上传文件-uploadFile", businessType = BizOpType.UPDATEFILE)
    public Result<?> uploadFile(MultipartFile file, @RequestParam Map<String, Object> jsonArray) {
        Map<String, Object> paramMap = JsonKit.json2Map_jackson(TypeKit.objToStr(jsonArray.get("data")));
        //上传文件,返回文件名
        String fileName = uploadFileService.uploadFile(file, paramMap);
        if (IsKit.isNull(fileName)) {
            return Result.warnMsg(ResultCode.FILE_WRITE.getMsg());
        } else {
            return Result.ok(fileName);
        }
    }

    /**
     * 上传文件：直接用el-upload自动上传
     */
    @PostMapping("/uploadFile_auto")
    @Log(title = "上传文件-组件自动上传文件-uploadFile_auto", businessType = BizOpType.UPDATEFILE)
    public Result<?> uploadFile_auto(MultipartFile file, @RequestParam Map<String, Object> paramMap) {
        //上传文件
        String fileName = uploadFileService.uploadFile(file, paramMap);
        if (IsKit.isNull(fileName)) {
            return Result.warnMsg(ResultCode.FILE_WRITE.getMsg());
        } else {
            return Result.ok(fileName);
        }
    }

    /**
     * 无用上传请求 不做任何事情，仅与页面的个别特殊情况进行配合运行
     */
    @PostMapping("/upFoo")
    public Result<?> upFool() {
        return Result.ok();
    }

    /**
     * 多表：批量删除多个表，主键一样
     * tableName:用逗号分割；keyParam:单一主键，格式: key|value
     * 同时删除指定路径下的文件。多个文件之间用，分割
     */
    @DeleteMapping("/delBatch_files/{tableName}/{fileDir}/{fileName}")
    @Log(title = "文件操作-批量删除多表记录及给定文件-delBatch_files", businessType = BizOpType.DELETE)
    public Result<?> delBatch_files(@PathVariable String tableName,
                                    @PathVariable String fileDir, @PathVariable String fileName,
                                    @RequestBody Map<String, Object> keyParam) {
        Boolean resultR;
        try {
            resultR = daoService.delBatch_where(tableName, keyParam);
        } catch (BusinessException e) {
            return Result.warnMsg(ResultCode.SQL_DELETE.getMsg());
        }
        if (!resultR) {
            return Result.warnMsg(ResultCode.SQL_DELETE.getMsg());
        }
        //如成功删除记录,删除硬盘上的图片
        if (IsKit.isNotNullOrEmpty(fileName)) {
            filePath = fileService.getFileFullPath(fileDir);
            String[] file = fileName.split(",");
            int num = 0;
            for (String s : file) {
                //暂时不考虑文件是否删除成功的情况
                Boolean resultF = FileKit.delFile(filePath, s);
                if (resultF) {
                    ++num;
                }
            }
            if (num == 0) {
                return Result.warnMsg(ResultCode.SQL_DELETE.getMsg());
            }
        }
        return Result.ok();
    }

    /**
     * 删除页面所选定所有记录及文件 单一主键
     */
    @DeleteMapping("/delBatch_file/{tableName}/{fileDir}")
    @Log(title = "库表操作-删除所选记录及文件-delBatch_file", businessType = BizOpType.DELETE)
    public Result<?> delBatch_file(@PathVariable String tableName,
                                   @PathVariable String fileDir, @RequestBody Map<String, Object> paramMap) {
        //要删除的记录的id 页面保证其不空
        String ids = TypeKit.objToStr(paramMap.get("id"));
        List<String> idList = Arrays.asList(ids.split(","));
        Boolean result;
        try {
            result = daoService.delBatch(tableName, idList);
        } catch (BusinessException e) {
            return Result.warnMsg(ResultCode.SQL_DELETE.getMsg());
        }
        if (!result) {
            return Result.warnMsg(ResultCode.SQL_DELETE.getMsg());
        }
        //要删除的文件的前缀fileIds
        String fileIds = TypeKit.objToStr(paramMap.get("file"));
        //删除硬盘上的文件 暂时不考虑文件是否删除成功的情况
        if (IsKit.isNotNullOrEmpty(fileIds)) {
            List<String> fileList = Arrays.asList(fileIds.split(","));
            filePath = fileService.getFileFullPath(fileDir);
            for (String s : fileList) {
                //删除给定前缀的文件
                FileKit.delMultiFile(filePath, s);
            }
        }
        return Result.ok();
    }

    /**
     * 先生成文件，然后返回文件地址，再由前端发送/api/download进行下载
     * 文件生成所含字段由json模板template决定;(位于：SamLims_web:/main/resources/static/report目录下)
     * 通用查询条件paramMap；rangeField为某个区间查询字段（目前支持一个）
     */
    @GetMapping("/genExcelFile/{tableName}/{template}/{rangeField}")
    @Log(title = "文件操作-生成文件并返回文件地址-genExcelFile", businessType = BizOpType.EXPORT)
    public Result<?> genExcelFile(@PathVariable String tableName, @PathVariable String template,
                                  @PathVariable String rangeField, @RequestParam Map<String, Object> paramMap)
    {
        Map<String, Object> titleFieldMap;
        if ("jar".equals(reportDir)) {
            titleFieldMap = FileKit.readJsonFile("report/" + template);
        } else {
            filePath = fileService.getFileFullPath("report");
            titleFieldMap = FileKit.readJsonFile(filePath + template);
        }
        if (IsKit.isNullOrEmpty(titleFieldMap)) {
            return Result.warnMsg(ResultCode.FILE_JSON.getMsg());
        }

        String title = "查询结果";
        if (IsKit.isNotNullOrEmpty(paramMap) && IsKit.isNotNullOrEmpty(paramMap.get("title"))) {
            title = TypeKit.objToStr(paramMap.get("title"));
            paramMap.remove("title");
        }

        Object[] keys = titleFieldMap.keySet().toArray();
        String items = TypeKit.arrayToStr(keys);
        List<Map<String, Object>> resultList;
        if (IsKit.isNullOrEmpty(rangeField)) {
            resultList = daoService.getList_order(tableName, items, paramMap);
        } else {
            resultList = daoService.getList_order(tableName, items, paramMap, rangeField);
        }
        Object[] objArray = titleFieldMap.values().toArray();
        String[] header = Arrays.stream(objArray).map(Object::toString).toArray(String[]::new);


        filePath = fileService.getAbsoluteFile(UUIDKit.encodingFilename_xlsx("Excel文档"));
        easyExcelService.genLocalExcel(resultList, filePath, title, header);
        if (IsKit.isFileExist(filePath)) {
            return Result.ok(filePath);
        } else {
            return Result.warnMsg(ResultCode.FILE_DOWNLOAD.getMsg());
        }
    }

    /**
     * 功能同genExcelFile
     * 不同之处：sql语句用户给定；paramMap只需给出一级标题等信息
     */
    @GetMapping("/genExcelFile_sql/{sqlId}/{template}")
    @Log(title = "文件操作-生成文件并返回文件地址-genExcelFile_sql", businessType = BizOpType.EXPORT)
    public Result<?> genExcelFile_sql(@PathVariable String sqlId,
                                      @PathVariable String template,
                                      @RequestParam Map<String, Object> paramMap) {
        String filePath = fileService.getFileFullPath("report");
        Map<String, Object> titleFieldMap;
        if ("jar".equals(reportDir)) {
            titleFieldMap = FileKit.readJsonFile("report/" + template);
        } else {
            titleFieldMap = FileKit.readJsonFile(filePath + template);
        }
        if (IsKit.isNullOrEmpty(titleFieldMap)) {
            return Result.warnMsg(ResultCode.FILE_JSON.getMsg());
        }
        Object[] objArray = titleFieldMap.values().toArray();
        String[] header = Arrays.stream(objArray).map(Object::toString).toArray(String[]::new);

        String title = "满足条件的记录";
        if (IsKit.isNotNullOrEmpty(paramMap) && IsKit.isNotNullOrEmpty(paramMap.get("title"))) {
            title = TypeKit.objToStr(paramMap.get("title"));
        }
        filePath = fileService.getAbsoluteFile(UUIDKit.encodingFilename_xlsx("Excel文档"));
        List<Map<String, Object>> resultList = daoService.getListBySql_order(sqlId, paramMap);
        easyExcelService.genLocalExcel(resultList, filePath, title, header);

        if (IsKit.isFileExist(filePath)) {
            return Result.ok(filePath);
        } else {
            return Result.warnMsg(ResultCode.FILE_DOWNLOAD.getMsg());
        }
    }

    /**
     * 下载给定文件(含完整路径)
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     * 主要用于： 先由后端生成文件genExportExcel，并保存在某个目录下，然后由此函数进行下载
     */
    @GetMapping("/getFile")
    @Log(title = "文件操作-下载给定文件-getFile", businessType = BizOpType.EXPORT)
    public void getFile(String fileName, Boolean delete, HttpServletResponse response) {
        try {
            if (!FileDownload.checkAllowDownload(fileName)) {
                throw new Exception(StringKit.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileDownload.setAttachmentResponseHeader(response, realFileName);
            FileKit.writeBytes(fileName, response.getOutputStream());
            if (delete) {
                FileKit.delFile(fileName);
            }
        } catch (Exception e) {
            LogKit.error("下载文件失败", e);
        }
    }


    /**
     * 删除以“,”分开的多个文件
     * 说明：文件名可能含有url信息，
     */
    //"http://www.localhost:8080/news/2022081012212963479721565.jpg";
    @PostMapping("/delFiles/{dirPath}")
    @Log(title = "文件操作-删除指定的多个文件-delFiles", businessType = BizOpType.DELETE)
    public Result<?> delFiles(@PathVariable String dirPath, @RequestBody List<String> paths) {
        int num = fileService.deleteFiles(dirPath, paths);
        if (num > 0) {
            return Result.ok();
        } else {
            return Result.warnMsg(ResultCode.FILE_DELETE.getMsg());
        }
    }

    /**
     * 属于专用：
     * 删除,分开的多个文件  @param paths数组[]
     * 说明：文件名可能含有url信息，比如：
     */
    //"http://www.localhost:8080/news/2022081012212963479721565.jpg";
    @PostMapping("/delFiles_P/{dirPath}/{filePrefix}")
    @Log(title = "文件操作-删除指定的多个文件-delFiles", businessType = BizOpType.DELETE)
    public Result<?> delFiles_P(
            @PathVariable String dirPath,
            @PathVariable String filePrefix,
            @RequestBody List<String> fileName)
    {
        int num = fileService.deleteFiles(dirPath, filePrefix, fileName);
        if (num > 0) {
            return Result.ok();
        } else {
            return Result.warnMsg(ResultCode.FILE_DELETE.getMsg());
        }
    }

    /**
     * wangEditor专用上传文件；返回格式的约定是由wangEditor规定的，不能改变。
     */
    @PostMapping("/uploadFileEditor")
    @Log(title = "富文本编辑器-上传文件-uploadFileEditor", businessType = BizOpType.UPDATE)
    public Map<String, Object> uploadFileEditor(@RequestParam("wangEditorFile") MultipartFile file,
                                                @RequestParam Map<String, Object> paramMap/*前端formData*/) {
        String dirName = "news";
        if (IsKit.isNotNull(paramMap)) {
            if (IsKit.isNotNull(paramMap.get("dirName"))) {
                dirName = TypeKit.objToStr(paramMap.get("dirName"));
            }
        }
        //纯数字文件名
        String fileName = UUIDKit.encodingUUID();
        //上传文件
        String avatar = uploadFileService.uploadFile(file, fileName, dirName);

        //构造返回的数据，wangEditor有自己的约定
        Map<String, Object> resultMap = new HashMap<>();
        if (IsKit.isNotNull(avatar)) {
            resultMap.put("errno", 0);
            Map<String, String> map = new HashMap<>();
            String imgPath =//httpService.getUrlPort()
                    httpService.getUrl()
                            + CharsetKit.SYMBOL_BACK_SLASH
                            + dirName
                            + CharsetKit.SYMBOL_BACK_SLASH
                            + avatar;
            map.put("url", imgPath);//必须图片src，用于页面上显示用
            map.put("href", "");//图片的链接，非必须
            map.put("alt", "");//图片描述文字，非必须
            resultMap.put("data", map);
        }
        //失败
        else {
            resultMap.put("errno", 1);// 只要不等于 0 就行
            resultMap.put("message", "写文件失败");
        }
        return resultMap;
    }

    /**
     * 以流文件形式返回给定文件到前端，供页面在线浏览，比如PDF文件
     */
    @GetMapping("/getStreamFile/{dirPath}/{fileName}")
    @Log(title = "文件操作-返回在线浏览所需流数据-getStreamFile", businessType = BizOpType.EXPORT)
    public void getStreamFile(HttpServletResponse response,
                              @PathVariable String dirPath, @PathVariable String fileName) {
        //获取目录
        String filePath = fileService.getFileFullPath(dirPath);
        downloadFileService.download_stream(filePath, fileName, response);
    }

    /**
     * 返回特定目录下所有文件或具有指定前缀的文件
     */
    @GetMapping(value = "/getFilesList")
    @Log(title = "文件操作-获取满足条件的所有文件名-getFilesList", businessType = BizOpType.SELECT)
    public Result<?> getFilesList(@RequestParam Map<String, Object> paramMap) {
        String dirName = TypeKit.objToStr(paramMap.get("DirName"));
        String filePrefix = TypeKit.objToStr(paramMap.get("FilePrefix"));
        //保存文件的完整路径 含有URL
        String filePath = fileService.getFileFullPath(dirName);
        List<String> fileName;
        //返回特定目录下所有文件
        if (IsKit.isNullOrEmpty(filePrefix)) {
            fileName = FileKit.getFilesName(filePath);
        }
        //返回特定目录下所有文件或具有指定前缀的文件
        else {
            fileName = FileKit.getFilesName(filePath, filePrefix);
        }
        return Result.ok(fileName);
    }

    /**
     * 处理图片
     * 返回web服务器特定目录下，比如tomcat/webapp/bjtu/avatar/目录下的
     * 图片文件的完整路径URL。页面只需要提供：avatar，20220423191245CDEWNk46186.jpg
     */
    //http://www.localhost:8081/bjtu/avatar/20220423191245CDEWNk46186.jpg"
    @Value("${sam.file.serverURL}")
    private String urlPath;

    @GetMapping("/getFileURI/{dirPath}/{fileName}")
    @Log(title = "文件操作-下载服务器特定目录下文件-getFileURI", businessType = BizOpType.EXPORT)
    public Result<?> getFileURI(@PathVariable String dirPath, @PathVariable String fileName) {
        //文件保存目录
        String dirName = "temp";
        if (IsKit.isNotNullOrEmpty(dirPath)) {
            dirName = dirPath;
        }
        String url = urlPath + CharsetKit.SYMBOL_BACK_SLASH
                + dirName + CharsetKit.SYMBOL_BACK_SLASH
                + fileName;
        return Result.ok(url);
    }

    /**
     * 上传Excel文件：写入数据库（tableName不空的化）： 一次上传一个excel文件
     */
    @PostMapping("/uploadExcelFile")
    @Log(title = "上传文件-上传Excel文件-uploadExcelFile(", businessType = BizOpType.UPDATE)
    public Result<?> uploadExcelFile(MultipartFile file, @RequestParam Map<String, Object> jsonArray) {
        Map<String, Object> paramMap = JsonKit.json2Map_jackson(TypeKit.objToStr(jsonArray.get("data")));

        String dirPath = TypeKit.objToStr(paramMap.get("DirName"));
        //删除标记
        String fileDel = TypeKit.objToStr(paramMap.get("FileDel"));
        String tableName = TypeKit.objToStr(paramMap.get("TableName"));
        //true数据覆盖；否则不覆盖
        String isCover = TypeKit.objToStr(paramMap.get("IsCover"));

        Long num = 0L;
        //tableName不空，写上传文件内容到数据库中
        if (IsKit.isNotNullOrEmpty(tableName)) {
            try {
                //表头占两行， 第一行表字段；第二行中文
                List<Map<String, Object>> listResult = ReadExcelUtil.getListNoModel(file, 0, 2, 0);
                if ("TSysUser".equals(tableName)) {
                    List<TSysUser> entityList = JSON.parseObject(JSON.toJSONString(listResult),
                            new TypeReference<List<TSysUser>>() {});
                    if ("true".equals(isCover)) {
                        num = daoService.saveOrUpdateAll(entityList);//,new String[]{}
                    } else {
                        num = daoService.saveAll(entityList);
                    }
                }
            } catch (Exception e) {
                return Result.warnMsg(ResultCode.SQL_RUN.getMsg());
            }
            return Result.ok("成功导入" + num + "条记录");
        }
        //写上传文件到给定目录
        else {
            String fileName = uploadFileService.uploadFile(file, paramMap);
            if (IsKit.isNull(fileName)) {
                return Result.warnMsg(ResultCode.FILE_WRITE.getMsg());
            }
            if ("true".equalsIgnoreCase(fileDel)) {
                String filePath = fileService.getFileFullPath(dirPath);
                FileKit.delFile(filePath, fileName);
            }
            return Result.ok("成功上传文件");
        }
    }


    /**
     * 返回特定目录下所有文件或具有指定前缀的文件
     */
    @GetMapping(value = "/getFilesDetail/{dirPath}")
    @Log(title = "文件操作-获取特定目录下所有文件的详细信息-getFilesDetail", businessType = BizOpType.SELECT)
    public Result<?> getFilesDetail(@PathVariable String dirPath) {
        if(IsKit.isNullOrEmpty(dirPath)){
            dirPath = "audio";
        }
        filePath = fileService.getFileFullPath(dirPath);
        List<Map<String,Object>> result = FileKit.getFilesInfo(filePath);
        if(IsKit.isNullOrEmpty(result)){
            return Result.ok("无文件");
        }
        return Result.ok_ePlus(Long.valueOf(result.size()), result);
    }


    /** 上传音频文件 formData格式数据*/
    @PostMapping("/uploadVoice")
    @Log(title = "个人信息维护-头像上传-uploadUserAvatar", businessType = BizOpType.UPDATE)
    public Result<?> uploadVoice(@RequestParam("file") MultipartFile file,
                                @RequestParam("extParam") String fileName)
    {
        System.out.println("uploadVoice-1:"+fileName);
        System.out.println("uploadVoice-2:"+file.getOriginalFilename());
        String avatar = uploadFileService.uploadFile(file,fileName,"avatar");
        System.out.println("uploadVoice-3:"+avatar);
        return Result.warnMsg(ResultCode.FILE_UPLOAD.getMsg());
    }

    
	/**
     * 读取 config.csv 文件并解析为 JSON 格式
     */
    @GetMapping("/getCsvData")
    @Log(title = "读取CSV文件数据-getCsvData", businessType = BizOpType.SELECT)
    public Result<?> readCsvToJson() {
        String filePath = "config.csv"; // 默认文件路径

        try {
            // 定义用于存储 CSV 数据的 List
            List<Map<String, String>> csvData = new ArrayList<>();

            // 读取 CSV 文件
            try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
                String line;
                String[] headers = null; // 存储表头
                int lineNumber = 0;

                while ((line = reader.readLine()) != null) {
                    // 按行解析 CSV 内容
                    String[] values = line.split(",");

                    // 首行为表头，存储字段名
                    if (lineNumber == 0) {
                        headers = values; // 存储表头字段名
                    } else {
                        if (headers != null) {
                            // 将每一行数据转为 Map（键值对：表头 -> 值）
                            Map<String, String> rowData = new LinkedHashMap<>();
                            for (int i = 0; i < headers.length; i++) {
                                rowData.put(headers[i], i < values.length ? values[i] : null);
                            }
                            csvData.add(rowData);
                        }
                    }
                    lineNumber++;
                }
            }

            // 返回 JSON 数据，使用 Result.ok
            return Result.ok(csvData);

        } catch (FileNotFoundException e) {
            return Result.warnMsg("文件未找到: " + filePath);
        } catch (IOException e) {
            return Result.warnMsg("读取文件时发生错误: " + e.getMessage());
        } catch (Exception e) {
            return Result.errorMsg("系统异常: " + e.getMessage());
        }
    }

    /**
     * 接收 JSON 数据并保存为 config.csv 文件
     */
    @PostMapping("/setCsvData")
    @Log(title = "更新CSV文件数据-setCsvData", businessType = BizOpType.UPDATE)
    public Result<?> writeJsonToCsv(@RequestBody List<Map<String, String>> csvData) {
        String filePath = "config.csv"; // 默认文件路径

        try {
            // 校验数据是否为空
            if (csvData == null || csvData.isEmpty()) {
                return Result.warnMsg("CSV 数据不能为空");
            }

            // 获取表头
            Set<String> headers = csvData.get(0).keySet();

            // 写入 CSV 文件
            try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
                // 写入表头
                writer.write(String.join(",", headers));
                writer.newLine();

                // 写入每一行数据
                for (Map<String, String> row : csvData) {
                    List<String> values = new ArrayList<>();
                    for (String header : headers) {
                        values.add(row.getOrDefault(header, ""));
                    }
                    writer.write(String.join(",", values));
                    writer.newLine();
                }
            }

            return Result.okMsg("CSV 数据保存成功");

        } catch (IOException e) {
            return Result.warnMsg("写入文件时发生错误: " + e.getMessage());
        } catch (Exception e) {
            return Result.errorMsg("系统异常: " + e.getMessage());
        }
    }

    
    /**
     * 根据光栅编号读取对应信息
     */
    @GetMapping("/getGratingData/{gratingId}")
    @Log(title = "读取光栅编号数据-getGratingData", businessType = BizOpType.SELECT)
    public Result<?> getGratingData(@PathVariable("gratingId") int gratingId) {
        String filePath = "config.csv"; // 默认配置文件路径

        try {
            // 用于存储读取到的目标行数据
            Map<String, String> resultData = null;

            // 读取 CSV 文件
            try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
                String line;
                String[] headers = null; // 存储表头
                int lineNumber = 0;

                while ((line = reader.readLine()) != null) {
                    // 按行解析 CSV 内容
                    String[] values = line.split(",");

                    // 处理表头
                    if (lineNumber == 0) {
                        headers = values; // 存储表头字段名
                    } else {
                        if (headers != null && values.length > 0) {
                            // 如果是目标光栅编号，则返回对应行的数据
                            if (Integer.parseInt(values[0].trim()) == gratingId) {
                                resultData = new LinkedHashMap<>();
                                for (int i = 0; i < headers.length; i++) {
                                    resultData.put(headers[i], i < values.length ? values[i].trim() : null);
                                }
                                break; // 找到对应光栅编号后退出循环
                            }
                        }
                    }
                    lineNumber++;
                }
            }

            // 如果未找到对应的光栅编号数据
            if (resultData == null) {
                return Result.warnMsg("未找到光栅编号为 " + gratingId + " 的数据");
            }

            // 返回找到的数据
            return Result.ok(resultData);

        } catch (FileNotFoundException e) {
            return Result.warnMsg("文件未找到: " + filePath);
        } catch (IOException e) {
            return Result.warnMsg("读取文件时发生错误: " + e.getMessage());
        } catch (NumberFormatException e) {
            return Result.warnMsg("光栅编号格式错误: " + e.getMessage());
        } catch (Exception e) {
            return Result.errorMsg("系统异常: " + e.getMessage());
        }
    }


}
