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.BaseDataVO;
import com.ruoyi.tjfx.entity.Category;
import com.ruoyi.tjfx.service.BaseDataService;
import com.ruoyi.tjfx.entity.BaseData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@SaIgnore
@Slf4j
@RestController
@RequestMapping("/basedata")
public class BaseDataController {

    @Autowired
    private BaseDataService baseDataService;

    /**
     * 分页查询基础数据
     */
    @GetMapping()
    public ApiResponse<PageResponse<BaseDataVO>> getBaseDataPage(
        @RequestParam(defaultValue = "1") Integer page,
        @RequestParam(defaultValue = "10") Integer pageSize,
        @RequestParam(required = false) String productCode,
        @RequestParam(required = false) String productName,
        @RequestParam(required = false) Long categoryId) {
        try {
            return ApiResponse.success(baseDataService.getPage(page, pageSize, productCode, productName, categoryId));
        } catch (Exception e) {
            log.error("分页查询基础数据失败", e);
            return ApiResponse.error("获取基础数据失败");
        }


    }

    @GetMapping("/{id}")
    public ApiResponse<BaseData> getById(@PathVariable Long id) {
        BaseData data = baseDataService.getById(id);
        if (data == null) return ApiResponse.error(404, "数据不存在");
        return ApiResponse.success(data, "获取成功");
    }

    @PostMapping
    public ApiResponse<Void> add(@RequestBody BaseData baseData) {
        baseDataService.add(baseData);
        return ApiResponse.success(null, "新增成功");
    }

    @PutMapping("/{id}")
    public ApiResponse<Void> update(@PathVariable Long id, @RequestBody BaseData baseData) {
        baseDataService.update(id, baseData);
        return ApiResponse.success(null, "更新成功");
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id) {
        baseDataService.delete(id);
        return ApiResponse.success(null, "删除成功");
    }

    @DeleteMapping("/batch/{ids}")
    public ApiResponse<Void> deleteBatch(@PathVariable String ids) {
        List<Long> idList = Arrays.stream(ids.split(","))
            .map(String::trim)
            .filter(s -> !s.isEmpty())
            .map(Long::valueOf)
            .collect(Collectors.toList());

        baseDataService.deleteBatch(idList);
        return ApiResponse.success(null, "批量删除成功");
    }
    @PostMapping("/import")
    public ApiResponse<?> importExcel(@RequestParam("file") MultipartFile file,
                                      @RequestParam("categoryId") Long categoryId) {
        try {
            if (file.isEmpty()) {
                return ApiResponse.validationError("请选择Excel文件");
            }

            baseDataService.importExcel(file, categoryId);
            return ApiResponse.success(null, "Excel导入成功");
        } catch (RuntimeException e) {
            return ApiResponse.validationError(e.getMessage());
        } catch (Exception e) {
            log.error("Excel导入失败", e);
            return ApiResponse.error("Excel导入失败");
        }
    }

    @GetMapping("/export/{categoryId}")
    public void exportExcel(@PathVariable Long categoryId, HttpServletResponse response) {
        try {
            baseDataService.exportExcel(categoryId, response);
        } catch (RuntimeException e) {
            try {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"success\":false,\"message\":\"" + e.getMessage() + "\"}");
            } catch (Exception ex) {
                log.error("写入错误响应失败", ex);
            }
        } catch (Exception e) {
            log.error("Excel导出失败", e);
            try {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write("{\"success\":false,\"message\":\"Excel导出失败\"}");
            } catch (Exception ex) {
                log.error("写入错误响应失败", ex);
            }
        }
    }
}
