package com.xdap.self_development.controller;


import com.definesys.mpaas.common.http.Response;
import com.xdap.api.moudle.user.pojo.XdapUsers;
import com.xdap.self_development.controller.request.EngineParamDetailRequest;
import com.xdap.self_development.domain.dto.EngineDeptUpdateDTO;
import com.xdap.self_development.domain.dto.EngineParamDetailDTO;
import com.xdap.self_development.domain.pojo.EngineParamDetailPojo;
import com.xdap.self_development.exception.CommonException;
import com.xdap.self_development.service.EngineParamDetailService;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 发动机参数详情控制器
 * 提供发动机参数详情相关的功能，包括参数列表查询、参数值查询、Excel导入导出、参数值修改等
 *
 * @version 1.0
 * @since 2025
 */
@RestController
@RequestMapping("/custom/engineParamDetailPojo")
public class EngineParamDetailController {
    @Resource
    private EngineParamDetailService engineParamDetailService;

    /**
     * 更新部门
     *
     * @return 操作结果响应
     */
    @PostMapping("/updateDept")
    public Response updateDept(
            @Valid @RequestBody EngineDeptUpdateDTO engineDeptUpdateDTO,
            BindingResult bindingResult
    ) {
        if (bindingResult.hasErrors()) {
            bindingResult.getFieldErrors().forEach(error -> {
                throw new CommonException(error.getDefaultMessage());
            });
        }
        engineParamDetailService.updateDept(engineDeptUpdateDTO);
        return Response.ok().data("更新部门成功");
    }

    /**
     * 参数列表查询
     *
     * @param modelID 机型ID
     * @param tcData  TC数据
     * @return 参数列表
     */
    @GetMapping("/selectParamList")
    public Response selectParamList(
            @RequestParam(value = "modelID", required = false) String modelID,
            @RequestParam(value = "tcData", required = false) String tcData,
            @RequestParam(required = false) String userId
    ) {
        Map<String, Set<String>> list = engineParamDetailService.selectParamList(modelID, tcData, userId);
        return Response.ok().data(list);
    }
    /**
     * 参数列表和模型查询
     *
     * @param modelID 机型ID
     * @return 参数列表和模型映射
     */
    @GetMapping("/selectParamListAndModel")
    public Response selectParamListAndModel(
            @RequestParam(value = "modelID") String modelID,
            @RequestParam(required = false) Integer parameterVersion,
            @RequestParam(required = false) String userID
    ) {
        Map<String, Map<String, Set<String>>> list = engineParamDetailService.selectParamListAndModel(modelID, parameterVersion, userID);
        return Response.ok().data(list);
    }

    @GetMapping("/selectParamListAndModelForFilledBy")
    public Response selectParamListAndModelForFilledBy(
            @RequestParam(value = "modelID") String modelID,
            @RequestParam(required = false) Integer parameterVersion,
            @RequestParam(value = "userID") String userID
    ) {
        Map<String, Map<String, Set<String>>> list = engineParamDetailService.selectParamListAndModelForFilledBy(modelID, parameterVersion, userID);
        return Response.ok().data(list);
    }

    @GetMapping("/selectParamListAndModelForFilledByHistory")
    public Response selectParamListAndModelForFilledByHistory(
            @RequestParam(value = "modelID") String modelID,
            @RequestParam(required = false) Integer parameterVersion,
            @RequestParam(value = "userID") String userID
    ) {
        Map<String, Map<String, Set<String>>> list = engineParamDetailService.selectParamListAndModelForFilledByHistory(modelID, parameterVersion, userID);
        return Response.ok().data(list);
    }

    /**
     * 参数值查询（一般不用）
     *
     * @param engineParamDetailRequest 发动机参数详情请求
     * @return 参数详情列表
     */
    @PostMapping("/selectValueByParam")
    public Response selectValueByParam(@RequestBody EngineParamDetailRequest engineParamDetailRequest) {
        List<EngineParamDetailDTO> dtoList = engineParamDetailService.selectValueByParam(engineParamDetailRequest);
        return Response.ok().data(dtoList);
    }

    /**
     * 参数值多项查询（待办点进来和机型查看点进来都要传入机型ID）
     *
     * @param engineParamDetailRequest 发动机参数详情请求
     * @return 参数详情映射
     */
    @PostMapping("/selectValueByMoreParam")
    public Response selectValueByMoreParam(@RequestBody EngineParamDetailRequest engineParamDetailRequest) {
        Map<String, List<EngineParamDetailDTO>> stringListMap = engineParamDetailService.selectValueByMoreParam(engineParamDetailRequest);
        return Response.ok().data(stringListMap);
    }


    /**
     * Excel导入
     *
     * @param file   文件
     * @param userId 用户ID
     * @param modelId 机型ID
     * @return 操作结果响应
     */
    @PostMapping("/excelImport")
    public Response excelImport(@RequestParam(value = "file") MultipartFile file,
                                @RequestParam(value = "userId") String userId,
                                @RequestParam(value = "modelId") String modelId) {
        if (file == null || file.isEmpty()) {
            return Response.error("请选择要导入的文件");
        }
        // 文件类型校验
        String filename = file.getOriginalFilename();
        if (filename == null || (!filename.endsWith(".xlsx") && !filename.endsWith(".xls"))) {
            return Response.error("只支持.xlsx或.xls格式的Excel文件");
        }
        try {
            engineParamDetailService.excelImport(file, modelId, userId);
        } catch (Exception e) {
            return Response.error("导入失败" + e.getMessage());
        }
        return Response.ok().data("导入成功");
    }

    /**
     * 导出Excel模板
     *
     * @param response    HTTP响应
     * @param engineModelID 发动机型号ID
     * @param userId      用户ID
     * @return 操作结果响应
     */
    @GetMapping("/excelExport")
    public Response excelExport(
            HttpServletResponse response,
            @RequestParam String engineModelID,
            @RequestParam String userId,
            @RequestParam(required = false) java.util.List<String> subsystemParts
    ) {
        try {
            engineParamDetailService.excelExport(response, engineModelID, userId, subsystemParts);
        } catch (Exception e) {
            return Response.error("导出失败" + e.getMessage());
        }
        return Response.ok().data("导出成功");
    }

    /**
     * 修改参数值
     *
     * @param engineParamDetailPojos 发动机参数详情列表
     * @param currentUserId          当前用户ID
     * @return 操作结果响应
     */
    @PostMapping(value = "/updateParamValue")
    public Response updateParamValue(
            @NotEmpty(message = "参数详情列表不能为空") @RequestBody List<EngineParamDetailPojo> engineParamDetailPojos,
            @NotBlank(message = "用户ID不能为空") @RequestParam("userID") String currentUserId
    ) {
        engineParamDetailService.updateParamValue(engineParamDetailPojos, currentUserId);
        return Response.ok().data("修改成功,保存草稿,准备进入审批");
    }

    /**
     * 分解任务
     *
     * @param engineParamDetailPojos 发动机参数详情列表
     * @param userID               用户ID
     * @return 操作结果响应
     */
    @PostMapping(value = "/updateToInsertFiledBy")
    public Response updateToInsertFiledBy(
            @NotEmpty(message = "参数详情列表不能为空") @RequestBody List<EngineParamDetailPojo> engineParamDetailPojos,
            @NotBlank(message = "用户ID不能为空") @RequestParam(value = "userID") String userID
    ) {
        engineParamDetailService.updateToInsertFiledBy(engineParamDetailPojos, userID);
        return Response.ok().data("修改成功");
    }

    /**
     * 查询版本列表
     *
     * @param modelId 机型ID
     * @return 版本号列表
     */
    @GetMapping(value = "/selectVersionList")
    public  Response selectVersionList(@RequestParam(value = "modelId") String modelId) {
        List<Integer> versionNumList  =  engineParamDetailService.selectVersionList(modelId);
        return Response.ok().data(versionNumList);
    }

    /**
     * 查找责任人或填写人列表
     *
     * @param subSystem 子系统
     * @param dept      部门
     * @param type      类型
     * @return 用户列表
     */
    @GetMapping(value = "/selectPersonoByType")
    public  Response selectPersonoByType(@RequestParam(value = "subSystem") String subSystem,@RequestParam(value = "dept") String dept
    ,@RequestParam(value = "type") Integer type) {
        List<XdapUsers> xdapUsersPojos  =  engineParamDetailService.selectPersonoByType(subSystem,dept,type);
        return Response.ok().data(xdapUsersPojos);
    }


}

