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

import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductUnitDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.deviceledger.DeviceLedgerDO;
import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.module.mes.controller.admin.plan.vo.PlanRespVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.organization.OrganizationDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.zjtype.ZjTypeDO;
import cn.iocoder.yudao.module.mes.service.zjtype.ZjTypeService;
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.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 static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;

import cn.iocoder.yudao.module.mes.controller.admin.zjitem.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.zjitem.ZjItemDO;
import cn.iocoder.yudao.module.mes.service.zjitem.ZjItemService;

import cn.iocoder.yudao.module.erp.controller.admin.product.vo.product.ErpProductRespVO;
import cn.iocoder.yudao.module.erp.service.product.ErpProductUnitService;

@Tag(name = "管理后台 - 质量管理-检验项目")
@RestController
@RequestMapping("/mes/zj-item")
@Validated
public class ZjItemController {

    @Resource
    private ZjItemService zjItemService;
    @Resource
    private ZjTypeService zjTypeService;
    @Resource
    private ErpProductUnitService productUnitService;

    @PostMapping("/create")
    @Operation(summary = "创建质量管理-检验项目")
    @PreAuthorize("@ss.hasPermission('mes:zj-item:create')")
    public CommonResult<Long> createZjItem(@Valid @RequestBody ZjItemSaveReqVO createReqVO) {
        return success(zjItemService.createZjItem(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新质量管理-检验项目")
    @PreAuthorize("@ss.hasPermission('mes:zj-item:update')")
    public CommonResult<Boolean> updateZjItem(@Valid @RequestBody ZjItemSaveReqVO updateReqVO) {
        zjItemService.updateZjItem(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除质量管理-检验项目")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:zj-item:delete')")
    public CommonResult<Boolean> deleteZjItem(@RequestParam("id") Long id) {
        zjItemService.deleteZjItem(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得质量管理-检验项目")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:zj-item:query')")
    public CommonResult<ZjItemRespVO> getZjItem(@RequestParam("id") Long id) {
        ZjItemDO zjItem = zjItemService.getZjItem(id);
        return success(BeanUtils.toBean(zjItem, ZjItemRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得质量管理-检验项目分页")
    @PreAuthorize("@ss.hasPermission('mes:zj-item:query')")
    public CommonResult<PageResult<ZjItemRespVO>> getZjItemPage(@Valid ZjItemPageReqVO pageReqVO) {
        PageResult<ZjItemDO> pageResult = zjItemService.getZjItemPage(pageReqVO);
        return success(new PageResult<>(buildVOList(pageResult.getList()), pageResult.getTotal()));
    }

    private List<ZjItemRespVO> buildVOList(List<ZjItemDO> list) {
        if (CollUtil.isEmpty(list)) {
            return Collections.emptyList();
        }

        Map<Long, ZjTypeDO> zjTypeMap = zjTypeService.getZjTypeVOMap(
                convertSet(list, ZjItemDO::getZjType));

        List<ErpProductUnitDO> unitDOList = productUnitService.getProductUnitListByStatus(CommonStatusEnum.ENABLE.getStatus());
        // 转换为 ID -> 名称 的映射（key是单位ID，value是单位名称）
        Map<String, String> unitNameMap = unitDOList.stream()
                .collect(Collectors.toMap(
                        unit -> String.valueOf(unit.getId()),
                        ErpProductUnitDO::getName,
                        (k1, k2) -> k1
                ));

        // 3. 转换DO到VO，同时赋值两个名称字段
        return BeanUtils.toBean(list, ZjItemRespVO.class, item -> {
            // 原有：设置质检类型名称
            MapUtils.findAndThen(zjTypeMap, item.getZjType(), zjType -> item.setZjTypeName(zjType.getName()));

            // 新增：设置单位名称（容错处理：空值/无映射时显示空字符串）
            if (item.getUnit() != null) {
                String unitName = unitNameMap.getOrDefault(item.getUnit(), "");
                item.setUnitName(unitName);
            }
        });
    }

    @GetMapping("/list")
    @Operation(summary = "获得检验项目列表")
    @PreAuthorize("@ss.hasPermission('mes:zj-item:query')")
    public CommonResult<List<ZjItemDO>> getZjItemList() {
        List<ZjItemDO> zjItemDOList = zjItemService.getZjItemList();
        return success(zjItemDOList);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出质量管理-检验项目 Excel")
    @PreAuthorize("@ss.hasPermission('mes:zj-item:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportZjItemExcel(@Valid ZjItemPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ZjItemDO> list = zjItemService.getZjItemPage(pageReqVO).getList();
        List<ZjItemRespVO> voList = buildVOList(list);
        // 导出 Excel
        ExcelUtils.write(response, "质量管理-检验项目.xls", "数据", ZjItemRespVO.class, voList);
    }

}