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

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductUnitDO;
import cn.iocoder.yudao.module.erp.service.product.ErpProductUnitService;
import cn.iocoder.yudao.module.mes.controller.admin.zjitem.vo.ZjItemRespVO;
import cn.iocoder.yudao.module.mes.dal.dataobject.zjitem.ZjItemDO;
import cn.iocoder.yudao.module.mes.dal.dataobject.zjtype.ZjTypeDO;
import cn.iocoder.yudao.module.mes.service.zjitem.ZjItemService;
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.zjschema.vo.*;
import cn.iocoder.yudao.module.mes.dal.dataobject.zjschema.ZjSchemaDO;
import cn.iocoder.yudao.module.mes.service.zjschema.ZjSchemaService;

@Tag(name = "管理后台 - 检验方案")
@RestController
@RequestMapping("/mes/zj-schema")
@Validated
public class ZjSchemaController {

    @Resource
    private ZjSchemaService zjSchemaService;
    @Resource
    private ZjItemService zjitemService;
    @Resource
    private ZjTypeService zjTypeService;
    @Resource
    private ErpProductUnitService productUnitService;

    @PostMapping("/create")
    @Operation(summary = "创建检验方案")
    @PreAuthorize("@ss.hasPermission('mes:zj-schema:create')")
    public CommonResult<Long> createZjSchema(@Valid @RequestBody ZjSchemaSaveReqVO createReqVO) {
        return success(zjSchemaService.createZjSchema(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新检验方案")
    @PreAuthorize("@ss.hasPermission('mes:zj-schema:update')")
    public CommonResult<Boolean> updateZjSchema(@Valid @RequestBody ZjSchemaSaveReqVO updateReqVO) {
        zjSchemaService.updateZjSchema(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除检验方案")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('mes:zj-schema:delete')")
    public CommonResult<Boolean> deleteZjSchema(@RequestParam("id") Long id) {
        zjSchemaService.deleteZjSchema(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得检验方案")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:zj-schema:query')")
    public CommonResult<ZjSchemaRespVO> getZjSchema(@RequestParam("id") Long id) {
        ZjSchemaDO zjSchema = zjSchemaService.getZjSchema(id);
        return success(BeanUtils.toBean(zjSchema, ZjSchemaRespVO.class));
    }

    @GetMapping("/page")
    @Operation(summary = "获得检验方案分页")
    @PreAuthorize("@ss.hasPermission('mes:zj-schema:query')")
    public CommonResult<PageResult<ZjSchemaRespVO>> getZjSchemaPage(@Valid ZjSchemaPageReqVO pageReqVO) {
        PageResult<ZjSchemaDO> pageResult = zjSchemaService.getZjSchemaPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, ZjSchemaRespVO.class));
    }

    @GetMapping("/list")
    @Operation(summary = "获得检验方案列表")
    @PreAuthorize("@ss.hasPermission('mes:zj-schema:query')")
    public CommonResult<List<ZjSchemaDO>> getZjSchemaList() {
        List<ZjSchemaDO> zjSchemaDOList = zjSchemaService.getZjSchemaList();
        return success(zjSchemaDOList);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出检验方案 Excel")
    @PreAuthorize("@ss.hasPermission('mes:zj-schema:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportZjSchemaExcel(@Valid ZjSchemaPageReqVO pageReqVO,
              HttpServletResponse response) throws IOException {
        pageReqVO.setPageSize(PageParam.PAGE_SIZE_NONE);
        List<ZjSchemaDO> list = zjSchemaService.getZjSchemaPage(pageReqVO).getList();
        // 导出 Excel
        ExcelUtils.write(response, "检验方案.xls", "数据", ZjSchemaRespVO.class,
                        BeanUtils.toBean(list, ZjSchemaRespVO.class));
    }

    @GetMapping("/getItemList")
    @Operation(summary = "获得检验方案关联的项目列表")
    @Parameter(name = "id", description = "检验方案编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('mes:zj-schema:query')")
    public CommonResult<List<ZjItemRespVO>> getItemList(@RequestParam("id") Long id) {
        // 1. 查询检验方案主记录
        ZjSchemaDO zjSchema = zjSchemaService.getZjSchema(id);
        if (zjSchema == null) {
            return success(Collections.emptyList()); // 或抛出业务异常，根据项目规范调整
        }

        // 2. 解析item字段（处理空值和空字符串）
        String itemStr = zjSchema.getItem();
        if (itemStr == null || itemStr.trim().isEmpty()) {
            return success(Collections.emptyList());
        }

        // 3. 分割字符串并转换为Long类型的项目ID列表
        List<Long> itemIds = Arrays.stream(itemStr.split(","))
                .map(String::trim) // 去除空格
                .filter(str -> !str.isEmpty()) // 过滤空字符串
                .map(Long::valueOf) // 转换为Long
                .collect(Collectors.toList());

        // 4. 查询所有关联的项目信息（请根据实际项目调整Service方法）
        List<ZjItemDO> itemList = zjitemService.getItemsByIds(itemIds);

        List<ZjItemRespVO> voList = buildVOList(itemList);

        // 5. 转换为VO并返回
        return success(voList);
    }



    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);
            }
        });
    }
}