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

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.common.controller.admin.moldrepair.vo.MoldRepairLineRespVO;
import cn.iocoder.yudao.module.common.controller.admin.moldrepair.vo.MoldRepairLineSaveReqVO;
import cn.iocoder.yudao.module.common.controller.admin.moldrepair.vo.MoldRepairUpdateReqVO;
import cn.iocoder.yudao.module.common.controller.admin.moldrepair.vo.*;
import cn.iocoder.yudao.module.common.dal.dataobject.moldrepair.MoldRepairDO;
import cn.iocoder.yudao.module.common.dal.dataobject.moldrepair.MoldRepairLineDO;
import cn.iocoder.yudao.module.mes.service.moldrepair.MoldRepairService;
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/mold-repair")
@Validated
public class MoldRepairController {

    @Resource
    private MoldRepairService moldRepairService;

    @Resource
    private AdminUserApi adminUserApi;

    @PostMapping("/create")
    @Operation(summary = "创建模具维修记录")
    @PreAuthorize("@ss.hasPermission('mes:mold-repair:create')")
    public CommonResult<Long> createMoldRepair(@Valid @RequestBody MoldRepairSaveReqVO createReqVO) {
        return success(moldRepairService.createMoldRepair(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新模具维修记录")
    @PreAuthorize("@ss.hasPermission('mes:mold-repair:update')")
    public CommonResult<Boolean> updateMoldRepair(@Valid @RequestBody MoldRepairSaveReqVO updateReqVO) {
        moldRepairService.updateMoldRepair(updateReqVO);
        return success(true);
    }

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

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

    @GetMapping("/get")
    @Operation(summary = "获得模具维修记录")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:mold-repair:query')")
    public CommonResult<MoldRepairRespVO> getMoldRepair(@RequestParam("id") Long id) {
        MoldRepairDO moldRepair = moldRepairService.getMoldRepair(id);
        return success(BeanUtils.toBean(moldRepair, MoldRepairRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得模具维修记录分页")
    @PreAuthorize("@ss.hasPermission('mes:mold-repair:query')")
    public CommonResult<PageResult<MoldRepairRespVO>> getMoldRepairPage(@Valid MoldRepairPageReqVO pageReqVO) {
        PageResult<MoldRepairDO> pageResult = moldRepairService.getMoldRepairPage(pageReqVO);
        PageResult<MoldRepairRespVO> moldRepairRespVOPageResult = BeanUtils.toBean(pageResult, MoldRepairRespVO.class);
        return success(buildCreatorName(moldRepairRespVOPageResult));
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出模具维修记录 Excel")
    @PreAuthorize("@ss.hasPermission('mes:mold-repair:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportMoldRepairExcel(@Valid MoldRepairPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<MoldRepairDO> list = moldRepairService.getMoldRepairPage(pageReqVO).getList();
        List<MoldRepairRespVO> moldRepairRespVOList = BeanUtils.toBean(list, MoldRepairRespVO.class);
        for (MoldRepairRespVO moldSubjectRespVO : moldRepairRespVOList) {
            if (moldSubjectRespVO.getAcceptedBy() !=null) {
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(moldSubjectRespVO.getAcceptedBy()));
                moldSubjectRespVO.setAcceptedBy("(" + user.getUsername() + ")" + user.getNickname());
            }
            if (moldSubjectRespVO.getConfirmBy() !=null) {
                AdminUserRespDTO user = adminUserApi.getUser(Long.valueOf(moldSubjectRespVO.getConfirmBy()));
                moldSubjectRespVO.setConfirmBy("(" + user.getUsername() + ")" + user.getNickname());
            }
            if (moldSubjectRespVO.getStatus() !=null) {
                moldSubjectRespVO.setStatusName(moldSubjectRespVO.getStatus() != null ?
                        (moldSubjectRespVO.getStatus() == 0 ? "待完成" : "已完成") : null);
            }
            if (moldSubjectRespVO.getRepairStatus() !=null) {
                moldSubjectRespVO.setRepairStatusName(moldSubjectRespVO.getRepairStatus() != null ?
                        (moldSubjectRespVO.getRepairStatus() == 1 ? "通过" : "不通过") : null);
            }

        }
        // 导出 Excel
        ExcelUtils.write(response, "模具维修记录.xls", "数据", MoldRepairRespVO.class,moldRepairRespVOList);
    }

    // ==================== 子表（模具维修记录行） ====================

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

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

    @PutMapping("/updateMoldRepairStatus")
    @Operation(summary = "更新模具维修子记录状态")
    @PreAuthorize("@ss.hasPermission('mes:mold-repair:update')")
    public CommonResult<Boolean> updateMoldRepairStatus(@Valid @RequestBody MoldRepairUpdateReqVO updateReqVO) {
        moldRepairService.updateMoldRepairStatus(updateReqVO);
        return success(true);
    }


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


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



    @GetMapping("/export-repair-excel")
    @Operation(summary = "导出维修历史记录 Excel")
    @PreAuthorize("@ss.hasPermission('mes:mold_ticket-results:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportRepairExcel(@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<MoldRepairLineRespVO> moldRepairDOList = moldRepairService.getRepairListByMoldId(moldId,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, "维修记录", MoldRepairLineRespVO.class, moldRepairDOList);
    }


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

        return moldSubjectRespVOPageResult;
    }

}