package cn.iocoder.yudao.module.iot.service.recipepoint;

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 org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import java.util.stream.Collectors;

import cn.iocoder.yudao.module.iot.controller.admin.recipepoint.vo.*;
import cn.iocoder.yudao.module.iot.dal.dataobject.recipepoint.RecipePointDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.iot.dal.mysql.recipepoint.RecipePointMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.iot.enums.ErrorCodeConstants.*;

/**
 * 手动配置参数表（绑定配方） Service 实现类
 *
 * @author 内蒙必硕
 */
@Service
@Validated
public class RecipePointServiceImpl implements RecipePointService {

    @Resource
    private RecipePointMapper recipePointMapper;
    @Resource
    private ErpProductUnitService productUnitService;

    @Override
    public Long createRecipePoint(RecipePointSaveReqVO createReqVO) {
        // 插入
        RecipePointDO recipePoint = BeanUtils.toBean(createReqVO, RecipePointDO.class);
        recipePointMapper.insert(recipePoint);
        // 返回
        return recipePoint.getId();
    }

    @Override
    public void updateRecipePoint(RecipePointSaveReqVO updateReqVO) {
        // 校验存在
        validateRecipePointExists(updateReqVO.getId());
        // 更新
        RecipePointDO updateObj = BeanUtils.toBean(updateReqVO, RecipePointDO.class);
        recipePointMapper.updateById(updateObj);
    }

    @Override
    public void deleteRecipePoint(Long id) {
        // 校验存在
        validateRecipePointExists(id);
        // 删除
        recipePointMapper.deleteById(id);
    }

    private void validateRecipePointExists(Long id) {
        if (recipePointMapper.selectById(id) == null) {
            throw exception(RECIPE_POINT_NOT_EXISTS);
        }
    }

    @Override
    public PageResult<RecipePointDO> getRecipePointPage(RecipePointPageReqVO pageReqVO) {
        PageResult<RecipePointDO> pageResult = recipePointMapper.selectPage(pageReqVO);
        Set<Long> unitIds = pageResult.getList().stream()
                .filter(Objects::nonNull)
                .map(RecipePointDO::getDataUnit)
                .filter(dataUnit -> dataUnit != null && !dataUnit.trim().isEmpty())
                .filter(dataUnit -> dataUnit.matches("\\d+"))  // 确保是纯数字
                .map(Long::valueOf)
                .collect(Collectors.toSet());
        Map<Long, ErpProductUnitDO> unitMap = productUnitService.getProductUnitMap(unitIds);
        List<RecipePointDO> recipePointDOList = BeanUtils.toBean(pageResult.getList(), RecipePointDO.class, recipePoint -> {
            Long unitId = null;
            try {
                unitId = Long.valueOf(recipePoint.getDataUnit());
            } catch (NumberFormatException e) {
                return;
            }
            MapUtils.findAndThen(unitMap, unitId,
                    unit -> recipePoint.setDataUnitName(unit.getName()));
        });
        return new PageResult<>(recipePointDOList, pageResult.getTotal());
    }

    @Override
    public RecipePointDO getRecipePoint(Long id) {
        if (id == null) {
            return null;
        }
        return Optional.ofNullable(recipePointMapper.selectById(id))
                .orElse(null);
    }
    @Override
    public List<RecipePointDO> getRecipePointPageList(Long recipeId) {
        return recipePointMapper.selectList(recipeId);
    }
}