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

import cn.iocoder.yudao.module.mes.controller.admin.deviceledger.vo.DeviceLedgerRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.moldsubject.vo.MoldSubjectRespVO;
import cn.iocoder.yudao.module.mes.controller.admin.ticketmanagement.enums.InspectionResultEnum;
import cn.iocoder.yudao.module.mes.controller.admin.ticketmanagement.enums.JobResultEnum;
import cn.iocoder.yudao.module.mes.controller.admin.ticketmanagement.enums.PlanTypeEnum;
import cn.iocoder.yudao.module.mes.controller.admin.ticketresults.vo.TicketInspectionExportVO;
import cn.iocoder.yudao.module.mes.controller.admin.ticketresults.vo.TicketResultsPageReqVO;
import cn.iocoder.yudao.module.mes.controller.admin.ticketresults.vo.TicketResultsRespVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.ticketresults.TicketResultsDO;
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.apache.ibatis.annotations.Param;
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.constraints.*;
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.mes.controller.admin.ticketmanagement.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.ticketmanagement.TicketManagementDO;
import cn.iocoder.yudao.module.mes.service.ticketmanagement.TicketManagementService;

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

    @Resource
    private TicketManagementService ticketManagementService;

    @Resource
    private AdminUserApi adminUserApi;
    @Resource
    private DictDataApi dictDataApi;


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

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

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

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

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

    @GetMapping("/export-excel")
    @Operation(summary = "导出工单管理 Excel")
    @PreAuthorize("@ss.hasPermission('mes:ticket-management:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportTicketManagementExcel(@Valid TicketManagementPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<TicketManagementDO> list = ticketManagementService.getTicketManagementPage(pageReqVO).getList();
        List<TicketManagementRespVO> ticketManagementRespVOList = BeanUtils.toBean(list, TicketManagementRespVO.class);
        for (TicketManagementRespVO ticketManagementRespVO : ticketManagementRespVOList) {
            if(ticketManagementRespVO.getOperator() != null){
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(ticketManagementRespVO.getOperator()));
                ticketManagementRespVO.setOperatorName( "(" + user.getUsername()+ ")" + user.getNickname());
            }

            if (ticketManagementRespVO.getPlanType()!=null){
                String planName = PlanTypeEnum.getDescriptionByCode(ticketManagementRespVO.getPlanType());
                ticketManagementRespVO.setPlanTypeName(planName);
            }
            if (ticketManagementRespVO.getJobResult()!=null){
                String jobResultName = JobResultEnum.getDescriptionByCode(ticketManagementRespVO.getJobResult());
                ticketManagementRespVO.setJobResultName(jobResultName);            }

        }

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


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

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


    @GetMapping("/getInspectionByDeviceId")
    @Operation(summary = "根据设备Id获得点检历史记录")
    @Parameter(name = "deviceId", description = "设备Id", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:ticket-management:query')")
    public CommonResult< List<TicketResultsDO>> getInspectionByDeviceId(@RequestParam("deviceId") Long deviceId,
                                                                        @RequestParam(name = "startTime",required = false) String startTime,
                                                                        @RequestParam(name = "endTime",required = false) String endTime) {
        List<TicketResultsDO> ticketResultsDOList = ticketManagementService.getInspectionByDeviceId(deviceId,startTime,endTime,"");
        return success(ticketResultsDOList);
    }

    @GetMapping("/export-excel-inspection")
    @Operation(summary = "导出点检历史记录 Excel")
    @PreAuthorize("@ss.hasPermission('mes:ticket-results:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportTicketResultsExcel(@RequestParam("deviceId") Long deviceId,
                                         @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<TicketResultsDO> results = ticketManagementService.getInspectionByDeviceId(deviceId, startTime, endTime, ids);

        // 转换为VO并处理数据
        List<TicketInspectionExportVO> 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, "点检记录", TicketInspectionExportVO.class, exportVos);
    }





    @GetMapping("/getMaintenanceByDeviceId")
    @Operation(summary = "根据设备Id获得保养历史记录")
    @Parameter(name = "deviceId", description = "设备Id", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:ticket-management:query')")
    public CommonResult<List<TicketResultsDO>> getMaintenanceByDeviceId(@RequestParam("deviceId") Long deviceId,
                                                                        @RequestParam(name = "startTime",required = false) String startTime,
                                                                        @RequestParam(name = "endTime",required = false) String endTime) {
        List<TicketResultsDO> ticketResultsDOList = ticketManagementService.getMaintenanceByDeviceId(deviceId,startTime,endTime,"");
        return success(ticketResultsDOList);
    }


    @GetMapping("/export-excel-maintenance")
    @Operation(summary = "导出保养历史记录 Excel")
    @PreAuthorize("@ss.hasPermission('mes:ticket-results:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportExcelMaintenance(@RequestParam("deviceId") Long deviceId,
                                         @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<TicketResultsDO> results = ticketManagementService.getMaintenanceByDeviceId(deviceId, startTime, endTime, ids);

        // 转换为VO并处理数据
        List<TicketInspectionExportVO> 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, "保养记录", TicketInspectionExportVO.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 TicketInspectionExportVO convertToExportVO(TicketResultsDO record) {
        TicketInspectionExportVO vo = BeanUtils.toBean(record, TicketInspectionExportVO.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;
    }

}