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

import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.module.mes.controller.admin.dvrepair.enums.RepairEnum;
import cn.iocoder.yudao.module.mes.controller.admin.dvrepair.enums.RepairStatusEnum;
import cn.iocoder.yudao.module.mes.controller.admin.dvrepair.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.dvrepair.DvRepairDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.dvrepair.DvRepairLineDO;
import cn.iocoder.yudao.module.mes.service.dvrepair.DvRepairService;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

@Tag(name = "管理后台 - 设备维修记录")
@RestController
@RequestMapping("/mes/dv-repair")
@Validated
public class DvRepairController {

    @Resource
    private DvRepairService dvRepairService;

    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建设备维修记录")
    @PreAuthorize("@ss.hasPermission('mes:dv-repair:create')")
    public CommonResult<Long> createDvRepair(@Valid @RequestBody DvRepairSaveReqVO createReqVO) {
        return success(dvRepairService.createDvRepair(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新设备维修记录")
    @PreAuthorize("@ss.hasPermission('mes:dv-repair:update')")
    public CommonResult<Boolean> updateDvRepair(@Valid @RequestBody DvRepairSaveReqVO updateReqVO) {
        dvRepairService.updateDvRepair(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除设备维修记录")
    @Parameter(name = "ids", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:dv-repair:delete')")
    public CommonResult<Boolean> deleteDvRepair(@RequestParam("ids") String ids) {

        // 将逗号分隔的字符串转换为Long类型的List
        List<Long> idList = Arrays.stream(ids.split(","))
                .map(String::trim) // 去除可能存在的空格
                .map(Long::valueOf)
                .collect(Collectors.toList());
        dvRepairService.deleteDvRepair(idList);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得设备维修记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:dv-repair:query')")
    public CommonResult<DvRepairRespVO> getDvRepair(@RequestParam("id") Long id) {
        DvRepairDO dvRepair = dvRepairService.getDvRepair(id);
        return success(BeanUtils.toBean(dvRepair, DvRepairRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得设备维修记录分页")
    @PreAuthorize("@ss.hasPermission('mes:dv-repair:query')")
    public CommonResult<PageResult<DvRepairRespVO>> getDvRepairPage(@Valid DvRepairPageReqVO pageReqVO) {
        PageResult<DvRepairDO> pageResult = dvRepairService.getDvRepairPage(pageReqVO);
        PageResult<DvRepairRespVO> dvRepairRespVOPageResult = BeanUtils.toBean(pageResult, DvRepairRespVO.class);
        return success(buildCreatorName(dvRepairRespVOPageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出设备维修记录 Excel")
    @PreAuthorize("@ss.hasPermission('mes:dv-repair:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportDvRepairExcel(@Valid DvRepairPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<DvRepairDO> list = dvRepairService.getDvRepairPage(pageReqVO).getList();
        List<DvRepairRespVO> dvRepairRespVOList = BeanUtils.toBean(list, DvRepairRespVO.class);
        for (DvRepairRespVO dvSubjectRespVO : dvRepairRespVOList) {
            if (dvSubjectRespVO.getAcceptedBy() !=null) {
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(dvSubjectRespVO.getAcceptedBy()));
                dvSubjectRespVO.setAcceptedBy("(" + user.getUsername() + ")" + user.getNickname());
            }
            if (dvSubjectRespVO.getConfirmBy() !=null) {
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(dvSubjectRespVO.getConfirmBy()));
                dvSubjectRespVO.setConfirmBy("(" + user.getUsername() + ")" + user.getNickname());
            }
            if (dvSubjectRespVO.getStatus() !=null) {
                String statusName = RepairStatusEnum.getDescriptionByCode(dvSubjectRespVO.getStatus());
                dvSubjectRespVO.setStatusName(statusName);
            }
            if (dvSubjectRespVO.getRepairStatus() !=null) {
                String repairStatusName = RepairEnum.getDescriptionByCode(dvSubjectRespVO.getRepairStatus());
                dvSubjectRespVO.setRepairStatusName(repairStatusName);
            }

        }

        // 设置响应头
        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");
        String fileName = String.format("设备维修记录_%s.xls", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")));
        // 导出 Excel
        ExcelUtils.write(response, "设备维修记录.xls", "数据", DvRepairRespVO.class,dvRepairRespVOList);
    }

    // ==================== 子表（设备维修记录行） ====================

    @GetMapping("/dv-repair-line/list-by-repair-id")
    @Operation(summary = "获得设备维修记录行列表")
    @Parameter(name = "repairId", description = "维修单ID")
    @PreAuthorize("@ss.hasPermission('mes:dv-repair:query')")
    public CommonResult<List<DvRepairLineDO>> getDvRepairLineListByRepairId(@RequestParam("repairId") Long repairId) {
        return success(dvRepairService.getDvRepairLineListByRepairId(repairId));
    }


    @PostMapping("/updateRepairLine")
    @Operation(summary = "更新设备维修子表")
    @PreAuthorize("@ss.hasPermission('mes:dv-repair:update')")
    public CommonResult<Boolean> updateRepairLine(@Valid @RequestBody DvRepairLineSaveReqVO updateReqVO) {
        dvRepairService.updateRepairLine(updateReqVO);
        return success(true);
    }

    @PutMapping("/updateDvRepairStatus")
    @Operation(summary = "更新设备维修子记录状态")
    @PreAuthorize("@ss.hasPermission('mes:dv-repair:update')")
    public CommonResult<Boolean> updateDvRepairStatus(@Valid @RequestBody DvRepirUpdateReqVO updateReqVO) {
        dvRepairService.updateDvRepairStatus(updateReqVO);
        return success(true);
    }


    @PutMapping("/batchUpdate")
    @Operation(summary = "批量更新维修检验结果")
    @PreAuthorize("@ss.hasPermission('mes:ticket-results:update')")
    public CommonResult<Boolean> batchUpdateTicketResults(
            @Valid @RequestBody List<DvRepairLineSaveReqVO> updateReqVOList) {
        dvRepairService.batchUpdateTicketResults(updateReqVOList);
        return success(true);
    }


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



    @GetMapping("/export-repair-excel")
    @Operation(summary = "导出维修历史记录 Excel")
    @PreAuthorize("@ss.hasPermission('mes:ticket-results:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportRepairExcel(@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<DvRepairLineRespVO> dvRepairDOList = dvRepairService.getRepairListByDeviceId(deviceId,startTime,endTime,ids);

        // 设置响应头
        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, "维修记录", DvRepairLineRespVO.class, dvRepairDOList);
    }

    private PageResult<DvRepairRespVO> buildCreatorName(PageResult<DvRepairRespVO> dvSubjectRespVOPageResult) {
        for (DvRepairRespVO dvSubjectRespVO : dvSubjectRespVOPageResult.getList()) {
            if (dvSubjectRespVO.getAcceptedBy() !=null) {
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(dvSubjectRespVO.getAcceptedBy()));
                if (user !=null ){
                    dvSubjectRespVO.setAcceptedBy("(" + user.getUsername() + ")" + user.getNickname());
                }
            }
            if (dvSubjectRespVO.getConfirmBy() !=null) {
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(dvSubjectRespVO.getConfirmBy()));
                if (user !=null){
                    dvSubjectRespVO.setConfirmBy("(" + user.getUsername() + ")" + user.getNickname());
                }
            }
        }

        return dvSubjectRespVOPageResult;
    }

}