package com.ruoyi.tjfx.controller;


import cn.dev33.satoken.annotation.SaIgnore;
import com.ruoyi.tjfx.common.ApiResponse;
import com.ruoyi.tjfx.common.PageResponse;
import com.ruoyi.tjfx.entity.AnalysisData;
import com.ruoyi.tjfx.service.AnalysisDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 分析数据Controller
 */
@SaIgnore
@Slf4j
@RestController
@RequestMapping("/analysis-data")
public class AnalysisDataController {

    @Autowired
    private AnalysisDataService analysisDataService;

    /**
     * 分页查询分析数据
     */
    @GetMapping
    public ApiResponse<PageResponse<AnalysisData>> getPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) String productCode,
            @RequestParam(required = false) String productName,
            @RequestParam(required = false) String customerName,
            @RequestParam(required = false) String shopName,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate) {

        try {
            PageResponse<AnalysisData> result = analysisDataService.getPage(
                    page, pageSize, productCode, productName, customerName, shopName, status, startDate, endDate);
            return ApiResponse.success(result, "获取成功");
        } catch (Exception e) {
            log.error("获取分析数据列表失败", e);
            return ApiResponse.error("获取分析数据列表失败");
        }
    }

    /**
     * 根据ID获取分析数据详情
     */
    @GetMapping("/{id}")
    public ApiResponse<AnalysisData> getById(@PathVariable Long id) {
        try {
            AnalysisData analysisData = analysisDataService.getById(id);
            if (analysisData == null) {
                return ApiResponse.error(404, "分析数据不存在");
            }
            return ApiResponse.success(analysisData, "获取成功");
        } catch (Exception e) {
            log.error("获取分析数据详情失败", e);
            return ApiResponse.error("获取分析数据详情失败");
        }
    }

    /**
     * 更新分析数据
     */
    @PutMapping("/{id}")
    public ApiResponse<Void> updateById(@PathVariable Long id, @RequestBody AnalysisData analysisData) {
        try {
            analysisDataService.updateById(id, analysisData);
            return ApiResponse.success(null, "更新成功");
        } catch (Exception e) {
            log.error("更新分析数据失败", e);
            return ApiResponse.error("更新分析数据失败");
        }
    }

    /**
     * 删除分析数据
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteById(@PathVariable Long id) {
        try {
            analysisDataService.deleteById(id);
            return ApiResponse.success(null, "删除成功");
        } catch (Exception e) {
            log.error("删除分析数据失败", e);
            return ApiResponse.error("删除分析数据失败");
        }
    }

    /**
     * 批量删除分析数据
     */
    @DeleteMapping("/batch/{ids}")
    public ApiResponse<Map<String, Object>> deleteBatchByIds(@PathVariable String ids) {
        try {
            String[] idArray = ids.split(",");
            List<Long> idList = new ArrayList<>();
            for (String id : idArray) {
                try {
                    idList.add(Long.parseLong(id.trim()));
                } catch (NumberFormatException ignored) {
                    // 忽略无效的ID
                }
            }

            if (idList.isEmpty()) {
                return ApiResponse.validationError("请选择要删除的数据");
            }

            analysisDataService.deleteBatchByIds(idList);

            Map<String, Object> result = new HashMap<>();
            result.put("deletedCount", idList.size());
            return ApiResponse.success(result, "批量删除成功");
        } catch (Exception e) {
            log.error("批量删除分析数据失败", e);
            return ApiResponse.error("批量删除分析数据失败");
        }
    }

    /**
     * 导出Excel（支持分页）
     */
    @GetMapping("/export")
    public void exportExcel(HttpServletResponse response,
                           @RequestParam(required = false) String productCode,
                           @RequestParam(required = false) String productName,
                           @RequestParam(required = false) String customerName,
                           @RequestParam(required = false) String shopName,
                           @RequestParam(required = false) Integer status,
                           @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate startDate,
                           @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate endDate,
                           @RequestParam(required = false) Integer page,
                           @RequestParam(required = false) Integer pageSize) {
        try {
            analysisDataService.exportExcel(response, productCode, productName, customerName, shopName, status, startDate, endDate, page, pageSize);
        } catch (Exception e) {
            log.error("Excel导出失败", e);
            try {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"code\":500,\"message\":\"Excel导出失败\"}");
            } catch (Exception ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }

    /**
     * 导入Excel数据（单文件）
     */
    @PostMapping("/import")
    public ApiResponse<Map<String, Object>> importExcel(
            @RequestParam("file") MultipartFile file,
            @RequestParam("categoryId") Long categoryId) {
        try {
            if (file.isEmpty()) {
                return ApiResponse.validationError("请选择Excel文件");
            }

            // 保存上传的文件
            String filePath = saveUploadedFile(file);

            Map<String, Object> result = analysisDataService.importExcel(filePath, categoryId);
            return ApiResponse.success(result, "数据处理完成，请确认后保存");
        } catch (Exception e) {
            log.error("Excel导入失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 批量导入Excel数据
     */
/*    @PostMapping("/import-batch")
    public ApiResponse<Map<String, Object>> importBatchExcel(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam("categoryId") Long categoryId) {
        try {
            if (files == null || files.length == 0) {
                return ApiResponse.validationError("请选择Excel文件");
            }

            List<String> filePaths = new ArrayList<>();
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    filePaths.add(saveUploadedFile(file));
                }
            }

            if (filePaths.isEmpty()) {
                return ApiResponse.validationError("没有有效的Excel文件");
            }

            Map<String, Object> result = analysisDataService.importBatchExcel(filePaths, categoryId);
            return ApiResponse.success(result, "批量数据处理完成，请确认后保存");
        } catch (Exception e) {
            log.error("批量Excel导入失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }*/
    /**
     * 批量导入Excel数据
     */
    @PostMapping("/import-batch")
    public ApiResponse<Map<String, Object>> importBatchExcel(
        @RequestParam("files") MultipartFile[] files,
        @RequestParam("categoryId") Long categoryId) {
        try {
            if (files == null || files.length == 0) {
                return ApiResponse.validationError("请选择Excel文件");
            }

            List<String> filePaths = new ArrayList<>();
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    filePaths.add(saveUploadedFile(file));
                }
            }

            if (filePaths.isEmpty()) {
                return ApiResponse.validationError("没有有效的Excel文件");
            }

            Map<String, Object> result = analysisDataService.importBatchExcel(filePaths, categoryId);
            return ApiResponse.success(result, "批量数据处理完成，请确认后保存");
        } catch (Exception e) {
            log.error("批量Excel导入失败", e);
            return ApiResponse.error("导入失败：" + e.getMessage());
        }
    }

    /**
     * 导入FBA数据（单文件）
     */
    @PostMapping("/import/fba")
    public ApiResponse<Map<String, Object>> importFbaExcel(
            @RequestParam("file") MultipartFile file,
            @RequestParam("shopName") String shopName) {
        try {
            if (file.isEmpty()) {
                return ApiResponse.validationError("请选择Excel文件");
            }

            String filePath = saveUploadedFile(file);
            Map<String, Object> result = analysisDataService.importFbaExcel(filePath, shopName);
            return ApiResponse.success(result, "FBA数据处理完成，请确认后保存");
        } catch (Exception e) {
            log.error("FBA数据导入失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 批量导入FBA数据
     */
    @PostMapping("/import/fba/batch")
    public ApiResponse<Map<String, Object>> importBatchFbaExcel(
            @RequestParam("files") MultipartFile[] files,
            @RequestParam("shopName") String shopName) {
        try {
            if (files == null || files.length == 0) {
                return ApiResponse.validationError("请选择Excel文件");
            }

            List<String> filePaths = new ArrayList<>();
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    filePaths.add(saveUploadedFile(file));
                }
            }

            if (filePaths.isEmpty()) {
                return ApiResponse.validationError("没有有效的Excel文件");
            }

            Map<String, Object> result = analysisDataService.importBatchFbaExcel(filePaths, shopName);
            return ApiResponse.success(result, "FBA批量数据处理完成，请确认后保存");
        } catch (Exception e) {
            log.error("FBA批量数据导入失败", e);
            return ApiResponse.error(e.getMessage());
        }
    }

    /**
     * 保存导入的数据
     */
    @PostMapping("/save-imported")
    public ApiResponse<Map<String, Object>> saveImportedData(@RequestBody List<AnalysisData> dataList) {
        try {
            if (dataList == null || dataList.isEmpty()) {
                return ApiResponse.validationError("没有可保存的数据");
            }

            Map<String, Object> result = analysisDataService.saveImportedData(dataList);
            return ApiResponse.success(result, "数据保存完成");
        } catch (Exception e) {
            log.error("保存数据失败", e);
            return ApiResponse.error("保存数据失败");
        }
    }

    /**
     * 保存上传的文件到系统临时目录
     */
    private String saveUploadedFile(MultipartFile file) throws Exception {
        // 获取系统临时目录
        String tempDir = System.getProperty("java.io.tmpdir");

        // 防止文件名冲突，加时间戳
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();

        // 构建目标文件路径
        String filePath = tempDir + java.io.File.separator + fileName;

        // 创建文件对象并保存
        java.io.File destFile = new java.io.File(filePath);
        file.transferTo(destFile);

        return filePath;
    }

    /**
     * 保存上传的文件
     */
/*    private String saveUploadedFile(MultipartFile file) throws Exception {
        // 这里应该实现文件保存逻辑
        // 为了简化，这里只是返回一个临时路径
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
        String uploadPath = "./uploads/";

        // 确保目录存在
        java.io.File uploadDir = new java.io.File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        String filePath = uploadPath + fileName;
        file.transferTo(new java.io.File(filePath));

        return filePath;
    }*/
}
