package cn.iocoder.yudao.module.mes.controller.admin.moldticketmanagement;

import cn.iocoder.yudao.module.mes.controller.admin.moldticketresults.vo.MoldTicketInspectionExportVO;
import cn.iocoder.yudao.module.mes.controller.admin.ticketmanagement.enums.InspectionResultEnum;
import cn.iocoder.yudao.module.mes.controller.admin.ticketresults.vo.TicketInspectionExportVO;
import cn.iocoder.yudao.module.common.dal.dataobject.moldticketresults.MoldTicketResultsDO;
import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import com.alibaba.excel.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import javax.servlet.http.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.io.IOException;
import java.util.stream.Collectors;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

import cn.iocoder.yudao.module.common.controller.admin.moldticketmanagement.vo.*;
import cn.iocoder.yudao.module.common.dal.dataobject.moldticketmanagement.MoldTicketManagementDO;
import cn.iocoder.yudao.module.mes.service.moldticketmanagement.MoldTicketManagementService;

@Tag(name = "管理后台 - 工单管理")
@RestController
@RequestMapping("/mes/mold-ticket-management")
@Validated
public class MoldTicketManagementController {

    @Resource
    private MoldTicketManagementService moldticketManagementService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private DictDataApi dictDataApi;

    @PostMapping("/create")
    @Operation(summary = "创建工单管理")
    @PreAuthorize("@ss.hasPermission('mes:mold-ticket-management:create')")
    public CommonResult<Long> createMoldTicketManagement(@Valid @RequestBody MoldTicketManagementSaveReqVO createReqVO) {
        return success(moldticketManagementService.createMoldTicketManagement(createReqVO));
    }

       @PutMapping("/update")
    @Operation(summary = "更新工单管理")
    @PreAuthorize("@ss.hasPermission('mes:mold-ticket-management:update')")
    public CommonResult<Boolean> updateMoldTicketManagement(@Valid @RequestBody MoldTicketManagementSaveReqVO updateReqVO) {
        moldticketManagementService.updateMoldTicketManagement(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除工单管理")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:mold-ticket-management:delete')")
    public CommonResult<Boolean> deleteMoldTicketManagement(@RequestParam("id") Long id) {
        moldticketManagementService.deleteMoldTicketManagement(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得工单管理")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:mold-ticket-management:query')")
    public CommonResult<MoldTicketManagementRespVO> getMoldTicketManagement(@RequestParam("id") Long id) {
        MoldTicketManagementDO moldticketManagement = moldticketManagementService.getMoldTicketManagement(id);
        return success(BeanUtils.toBean(moldticketManagement, MoldTicketManagementRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得工单管理分页")
    @PreAuthorize("@ss.hasPermission('mes:mold-ticket-management:query')")
    public CommonResult<PageResult<MoldTicketManagementRespVO>> getMoldTicketManagementPage(@Valid MoldTicketManagementPageReqVO pageReqVO) {
        PageResult<MoldTicketManagementDO> pageResult = moldticketManagementService.getMoldTicketManagementPage(pageReqVO);
        return success(buildPageCreatorName(BeanUtils.toBean(pageResult, MoldTicketManagementRespVO.class)));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出工单管理 Excel")
    @PreAuthorize("@ss.hasPermission('mes:mold-ticket-management:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMoldTicketManagementExcel(@Valid MoldTicketManagementPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MoldTicketManagementDO> list = moldticketManagementService.getMoldTicketManagementPage(pageReqVO).getList();
        List<MoldTicketManagementRespVO> moldticketManagementRespVOList = BeanUtils.toBean(list, MoldTicketManagementRespVO.class);
        for (MoldTicketManagementRespVO moldticketManagementRespVO : moldticketManagementRespVOList) {
            AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(moldticketManagementRespVO.getCreator()));
            moldticketManagementRespVO.setCreatorName( "(" + user.getUsername()+ ")" + user.getNickname());
        }

        // 导出 Excel
        ExcelUtils.write(response, "工单管理.xls", "数据", MoldTicketManagementRespVO.class,
                moldticketManagementRespVOList);
    }


    @PutMapping("/batchUpdateStatus")
    @Operation(summary = "批量取消工单")
    @PreAuthorize("@ss.hasPermission('mes:mold-ticket-management:update')")
    public CommonResult<Boolean> batchUpdateMoldTicketStatus(@Valid @RequestBody MoldTicketManagementBatchUpdateReqVO reqVO) {
        moldticketManagementService.batchUpdateJobStatus(reqVO);
        return success(true);
    }

    private PageResult<MoldTicketManagementRespVO> buildPageCreatorName(PageResult<MoldTicketManagementRespVO> moldticketManagementRespVOPageResult) {
        for (MoldTicketManagementRespVO moldticketManagementRespVO : moldticketManagementRespVOPageResult.getList()) {
            AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(moldticketManagementRespVO.getCreator()));
            moldticketManagementRespVO.setCreatorName( "(" + user.getUsername()+ ")" + user.getNickname());
            if (moldticketManagementRespVO.getOperator()!=null){
                AdminUserRespDTO operator = adminUserApi.getUser(Long.valueOf(moldticketManagementRespVO.getOperator()));
                moldticketManagementRespVO.setOperatorName("(" + operator.getUsername()+ ")" + operator.getNickname());
            }
        }
        return moldticketManagementRespVOPageResult;
    }


    @GetMapping("/getInspectionByMoldId")
    @Operation(summary = "根据模具Id获得点检历史记录")
    @Parameter(name = "moldId", description = "模具Id", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:mold-ticket-management:query')")
    public CommonResult< List<MoldTicketResultsDO>> getInspectionByMoldId(@RequestParam("moldId") Long moldId,
                                                                        @RequestParam(name = "startTime",required = false) String startTime,
                                                                        @RequestParam(name = "endTime",required = false) String endTime) {
        List<MoldTicketResultsDO> moldTicketResultsDOList = moldticketManagementService.getInspectionByMoldId(moldId,startTime,endTime,"");
        return success(moldTicketResultsDOList);
    }

    @GetMapping("/export-excel-inspection")
    @Operation(summary = "导出点检历史记录 Excel")
    @PreAuthorize("@ss.hasPermission('mes:mold-ticket-results:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMoldTicketResultsExcel(@RequestParam("moldId") Long moldId,
                                         @RequestParam(name = "ids",required = false) String ids,
                                         @RequestParam(name = "startTime",required = false) String startTime,
                                         @RequestParam(name = "endTime",required = false) String endTime,
                                         HttpServletResponse response) throws IOException {

        // 查询数据
        List<MoldTicketResultsDO> results = moldticketManagementService.getInspectionByMoldId(moldId, startTime, endTime, ids);

        // 转换为VO并处理数据
        List<MoldTicketInspectionExportVO> exportVos = results.stream()
                .map(this::convertToExportVO)
                .collect(Collectors.toList());
        // 设置响应头
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("点检记录.xls", "UTF-8"));
        response.setHeader("Content-Encoding", "identity");
        // 导出Excel
        String fileName = String.format("点检记录_%s.xls", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        ExcelUtils.write(response, fileName, "点检记录", MoldTicketInspectionExportVO.class, exportVos);
    }


    @GetMapping("/getMaintenanceByMoldId")
    @Operation(summary = "根据模具Id获得保养历史记录")
    @Parameter(name = "moldId", description = "模具Id", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:mold_ticket-management:query')")
    public CommonResult<List<MoldTicketResultsDO>> getMaintenanceByMoldId(@RequestParam("moldId") Long moldId,
                                                                        @RequestParam(name = "startTime",required = false) String startTime,
                                                                        @RequestParam(name = "endTime",required = false) String endTime) {
        List<MoldTicketResultsDO> moldticketResultsDOList = moldticketManagementService.getMaintenanceByMoldId(moldId,startTime,endTime,"");
        return success(moldticketResultsDOList);
    }


    @GetMapping("/export-excel-maintenance")
    @Operation(summary = "导出保养历史记录 Excel")
    @PreAuthorize("@ss.hasPermission('mes:mold_ticket-results:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportExcelMaintenance(@RequestParam("moldId") Long moldId,
                                       @RequestParam(name = "ids",required = false) String ids,
                                       @RequestParam(name = "startTime",required = false) String startTime,
                                       @RequestParam(name = "endTime",required = false) String endTime,
                                       HttpServletResponse response) throws IOException {

        // 查询数据
        List<MoldTicketResultsDO> results = moldticketManagementService.getMaintenanceByMoldId(moldId, startTime, endTime, ids);

        // 转换为VO并处理数据
        List<MoldTicketInspectionExportVO> exportVos = results.stream()
                .map(this::convertToExportVO)
                .collect(Collectors.toList());
        // 设置响应头
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("保养记录.xls", "UTF-8"));
        response.setHeader("Content-Encoding", "identity");
        // 导出Excel
        String fileName = String.format("保养记录_%s.xls", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        ExcelUtils.write(response, fileName, "保养记录", MoldTicketInspectionExportVO.class, exportVos);
    }



    /**
     * 获取字典数据
     */
    private Map<String, Map<String, String>> getDictData() {
        Map<String, Map<String, String>> dictData = new HashMap<>();

        try {
            // 获取检验方式字典
            Map<String, String> inspectionMethodDict = new HashMap<>();
            List<DictDataRespDTO> inspectionMethods = dictDataApi.getDictDataList("Inspection_method");
            for (DictDataRespDTO dict : inspectionMethods) {
                inspectionMethodDict.put(dict.getValue(), dict.getLabel());
            }
            dictData.put("Inspection_method", inspectionMethodDict);

        } catch (Exception e) {
            throw new RuntimeException("获取字典数据异常：" + e);
        }

        return dictData;
    }

    /**
     * 数据转换
     */
    private MoldTicketInspectionExportVO convertToExportVO(MoldTicketResultsDO record) {
        MoldTicketInspectionExportVO vo = BeanUtils.toBean(record, MoldTicketInspectionExportVO.class);

        // 转换检验结果
        if (record.getInspectionResult() != null) {
            vo.setResult(record.getInspectionResult().equals(InspectionResultEnum.OK.getCode()) ? InspectionResultEnum.OK.getLabel() :
                    record.getInspectionResult().equals(InspectionResultEnum.NG.getCode()) ? InspectionResultEnum.NG.getLabel() : String.valueOf(record.getInspectionResult()));
        }

        // 处理操作人信息
        if (StringUtils.isNotBlank(record.getOperator())) {
            try {
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(record.getOperator()));
                if (user != null) {
                    vo.setOperator("(" + user.getUsername() + ")" + user.getNickname());
                }
            } catch (Exception e) {
                // 转换失败保持原值
            }
        }

        // 处理检验方式字典
        if (StringUtils.isNotBlank(record.getInspectionMethod())) {
            Map<String, Map<String, String>> dictData = getDictData();
            String methodLabel = dictData.getOrDefault("Inspection_method", Collections.emptyMap())
                    .get(record.getInspectionMethod());
            if (StringUtils.isNotBlank(methodLabel)) {
                vo.setInspectionMethod(methodLabel);
            }
        }

        return vo;
    }
}