package com.zt.plat.module.base.service.unitQuantity;

import cn.hutool.core.collection.CollUtil;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import com.zt.plat.module.base.controller.admin.unitQuantity.vo.*;
import com.zt.plat.module.base.dal.dataobject.unitQuantity.UnitQuantityDO;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;

import com.zt.plat.module.base.dal.dao.unitQuantity.UnitQuantityMapper;
import com.zt.plat.module.base.dal.dao.quantityUnitRelation.QuantityUnitRelationMapper;
import com.zt.plat.module.base.dal.dao.untInfo.UntInfoMapper;
import com.zt.plat.module.base.dal.dataobject.quantityUnitRelation.QuantityUnitRelationDO;
import com.zt.plat.module.base.dal.dataobject.untInfo.UntInfoDO;
import java.util.stream.Collectors;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.framework.common.util.collection.CollectionUtils.convertList;
import static com.zt.plat.module.unitmanagement.enums.UnitErrorCodeConstants.*;

/**
 * 计量单位量 Service 实现类
 *
 * @author 后台管理-1
 */
@Service
@Validated
public class UnitQuantityServiceImpl implements UnitQuantityService {

    @Resource
    private UnitQuantityMapper unitQuantityMapper;

    @Resource
    private QuantityUnitRelationMapper quantityUnitRelationMapper;

    @Resource
    private UntInfoMapper untInfoMapper;

    @Override
    public UnitQuantityRespVO createUnitQuantity(UnitQuantitySaveReqVO createReqVO) {
        // 插入
        UnitQuantityDO unitQuantity = BeanUtils.toBean(createReqVO, UnitQuantityDO.class);
        unitQuantityMapper.insert(unitQuantity);
        // 返回
        return BeanUtils.toBean(unitQuantity, UnitQuantityRespVO.class);
    }

    @Override
    public void updateUnitQuantity(UnitQuantitySaveReqVO updateReqVO) {
        // 校验存在
        validateUnitQuantityExists(updateReqVO.getId());
        // 更新
        UnitQuantityDO updateObj = BeanUtils.toBean(updateReqVO, UnitQuantityDO.class);
        unitQuantityMapper.updateById(updateObj);
    }

    @Override
    public void deleteUnitQuantity(Long id) {
        // 校验存在
        validateUnitQuantityExists(id);
        // 删除
        unitQuantityMapper.deleteById(id);
    }

    @Override
        public void deleteUnitQuantityListByIds(List<Long> ids) {
        // 校验存在
        validateUnitQuantityExists(ids);
        // 删除
        unitQuantityMapper.deleteByIds(ids);
        }

    private void validateUnitQuantityExists(List<Long> ids) {
        List<UnitQuantityDO> list = unitQuantityMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(UNIT_QUANTITY_NOT_EXISTS);
        }
    }

    private void validateUnitQuantityExists(Long id) {
        if (unitQuantityMapper.selectById(id) == null) {
            throw exception(UNIT_QUANTITY_NOT_EXISTS);
        }
    }

    @Override
    public UnitQuantityDO getUnitQuantity(Long id) {
        return unitQuantityMapper.selectById(id);
    }

    @Override
    public PageResult<UnitQuantityDO> getUnitQuantityPage(UnitQuantityPageReqVO pageReqVO) {
        return unitQuantityMapper.selectPage(pageReqVO);
    }

    @Override
    public List<UnitQuantityTreeRespVO> getUnitQuantityTree() {
        // 1. 查询所有量纲
        List<UnitQuantityDO> quantities = unitQuantityMapper.selectList();

        // 2. 查询所有关联关系
        List<QuantityUnitRelationDO> relations = quantityUnitRelationMapper.selectList();

        // 3. 查询所有单位
        List<UntInfoDO> units = untInfoMapper.selectList();
        Map<Long, UntInfoDO> unitMap = units.stream()
                .collect(Collectors.toMap(UntInfoDO::getId, u -> u));

        // 4. 组装树形结构
        return quantities.stream().map(quantity -> {
            UnitQuantityTreeRespVO treeVO = new UnitQuantityTreeRespVO();
            treeVO.setId(quantity.getId());
            treeVO.setName(quantity.getName());
            treeVO.setSymbol(quantity.getSymbol());
            treeVO.setDsp(quantity.getDsp());

            // 获取该量纲下的所有单位
            List<UnitQuantityTreeRespVO.UnitItemVO> unitItems = relations.stream()
                    .filter(r -> r.getUntQtyId().equals(quantity.getId()))
                    .map(r -> {
                        UnitQuantityTreeRespVO.UnitItemVO unitItem = new UnitQuantityTreeRespVO.UnitItemVO();
                        unitItem.setRelationId(r.getId());
                        unitItem.setId(r.getUntId());
                        unitItem.setIsBse(r.getIsBse());

                        // 填充单位信息
                        UntInfoDO unit = unitMap.get(r.getUntId());
                        if (unit != null) {
                            unitItem.setName(unit.getName());
                            unitItem.setSmb(unit.getSmb());
                        }

                        return unitItem;
                    })
                    .collect(Collectors.toList());

            treeVO.setUnits(unitItems);
            return treeVO;
        }).collect(Collectors.toList());
    }

}