package com.maintain.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import com.maintain.common.core.domain.entity.SysDept;
import com.maintain.common.utils.StringUtils;
import com.maintain.common.core.page.TableDataInfo;
import com.maintain.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.maintain.common.utils.TreeBuildUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.maintain.business.domain.bo.ErpMaterialTypeBo;
import com.maintain.business.domain.vo.ErpMaterialTypeVo;
import com.maintain.business.domain.ErpMaterialType;
import com.maintain.business.mapper.ErpMaterialTypeMapper;
import com.maintain.business.service.IErpMaterialTypeService;

import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 物资分类Service业务层处理
 *
 * @author liushuai
 * @date 2025-04-03
 */
@RequiredArgsConstructor
@Service
public class ErpMaterialTypeServiceImpl implements IErpMaterialTypeService {

    private final ErpMaterialTypeMapper baseMapper;

    /**
     * 查询物资分类
     */
    @Override
    public ErpMaterialTypeVo queryById(Long typeId){
        return baseMapper.selectVoById(typeId);
    }

    /**
     * 查询物资分类列表
     */
    @Override
    public TableDataInfo<ErpMaterialTypeVo> queryPageList(ErpMaterialTypeBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ErpMaterialType> lqw = buildQueryWrapper(bo);
        Page<ErpMaterialTypeVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询物资分类树
     *
     * @param bo
     */
    @Override
    public List<Tree<Long>> queryTreeList(ErpMaterialTypeBo bo) {
        LambdaQueryWrapper<ErpMaterialType> lqw = buildQueryWrapper(bo);
        List<ErpMaterialType> typeList = baseMapper.selectList(lqw);
        return buildTypeTreeSelect(typeList);
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param typeList 类型列表
     * @return 下拉树结构列表
     */
    public List<Tree<Long>> buildTypeTreeSelect(List<ErpMaterialType> typeList) {
        if (CollUtil.isEmpty(typeList)) {
            return CollUtil.newArrayList();
        }
        return TreeBuildUtils.build(typeList, (type, tree) ->
            tree.setId(type.getTypeId())
                .setParentId(type.getParentId())
                .setName(type.getTypeName())
                .setWeight(type.getOrderNum()));
    }

    /**
     * 查询物资分类列表
     */
    @Override
    public List<ErpMaterialTypeVo> queryList(ErpMaterialTypeBo bo) {
        LambdaQueryWrapper<ErpMaterialType> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ErpMaterialType> buildQueryWrapper(ErpMaterialTypeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ErpMaterialType> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTypeName()), ErpMaterialType::getTypeName, bo.getTypeName());
        lqw.eq(bo.getParentId() != null, ErpMaterialType::getParentId, bo.getParentId());
        lqw.eq(StringUtils.isNotBlank(bo.getAncestors()), ErpMaterialType::getAncestors, bo.getAncestors());
        lqw.eq(bo.getOrderNum() != null, ErpMaterialType::getOrderNum, bo.getOrderNum());
        lqw.orderByAsc(ErpMaterialType::getParentId);
        lqw.orderByAsc(ErpMaterialType::getOrderNum);
        return lqw;
    }

    /**
     * 新增物资分类
     */
    @Override
    public Boolean insertByBo(ErpMaterialTypeBo bo) {
        ErpMaterialType add = BeanUtil.toBean(bo, ErpMaterialType.class);
        validEntityBeforeSave(add);
        LambdaQueryWrapper<ErpMaterialType> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(ErpMaterialType::getTypeName, add.getTypeName());
        if (!baseMapper.selectList(queryWrapper).isEmpty()) {
            throw new RuntimeException("类型名称已存在，请调整后再试");
        }
        ErpMaterialTypeVo materialTypeVo = baseMapper.selectVoById(add.getParentId());
        add.setAncestors(materialTypeVo.getAncestors() + StringUtils.SEPARATOR + add.getParentId());
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setTypeId(add.getTypeId());
        }
        return flag;
    }

    /**
     * 修改物资分类
     */
    @Override
    public Boolean updateByBo(ErpMaterialTypeBo bo) {
        ErpMaterialType update = BeanUtil.toBean(bo, ErpMaterialType.class);
        validEntityBeforeSave(update);
        LambdaQueryWrapper<ErpMaterialType> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.ne(ErpMaterialType::getTypeId, update.getTypeId()).eq(ErpMaterialType::getTypeName, update.getTypeName());
        if (!baseMapper.selectList(queryWrapper).isEmpty()) {
            throw new RuntimeException("类型名称已存在，请调整后再试");
        }
        if (update.getParentId() > 0) {
            ErpMaterialTypeVo materialTypeVo = baseMapper.selectVoById(update.getParentId());
            update.setAncestors(materialTypeVo.getAncestors() + StringUtils.SEPARATOR + update.getParentId());
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ErpMaterialType entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除物资分类
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
