package com.fjhx.service.material.impl;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjhx.base.StorageBaseEntity;
import com.fjhx.entity.material.MaterialClassify;
import com.fjhx.mapper.material.MaterialClassifyMapper;
import com.fjhx.params.material.MaterialClassifyVo;
import com.fjhx.service.material.MaterialClassifyService;
import com.fjhx.utils.Assert;
import com.fjhx.utils.TreeUtil;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 物料分类 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2022-08-05
 */
@Service
public class MaterialClassifyServiceImpl extends ServiceImpl<MaterialClassifyMapper, MaterialClassify> implements MaterialClassifyService {

    @Override
    public List<JSONObject> tree() {
        return TreeUtil.buildTreeObj(
                list(Wrappers.<MaterialClassify>lambdaQuery()
                        .select(StorageBaseEntity::getId,
                                MaterialClassify::getName,
                                MaterialClassify::getParentId,
                                MaterialClassify::getCode)
                ));
    }

    @Override
    public void add(MaterialClassifyVo materialClassifyVo) {
        Long parentId = materialClassifyVo.getParentId();

        peerNameAndCodeOnly(parentId, materialClassifyVo.getName(), materialClassifyVo.getCode(), null);

        if (parentId == null) {
            materialClassifyVo.setParentId(0L);
        } else if (parentId != 0) {
            MaterialClassify materialClassify = getById(parentId);

            // 赋值父级id集合
            String parentIdSet = materialClassify.getParentIdSet();
            materialClassifyVo.setParentIdSet(
                    (ObjectUtil.isEmpty(parentIdSet) ? "" : parentIdSet + ",") + parentId);

            // 赋值物料编码
            String code = materialClassify.getCode();
            materialClassifyVo.setCode(code + materialClassifyVo.getCode());
        }

        save(materialClassifyVo);
    }

    @Override
    public void edit(MaterialClassifyVo materialClassifyVo) {

        peerNameAndCodeOnly(materialClassifyVo.getParentId(), materialClassifyVo.getName(),
                materialClassifyVo.getCode(), materialClassifyVo.getId());

        updateById(materialClassifyVo);
    }

    /**
     * 保证同级名称和编码不重复
     */
    private void peerNameAndCodeOnly(Long parentId, String name, String code, Long excludeId) {

        Long count = lambdaQuery()
                .eq(MaterialClassify::getParentId, parentId)
                .and(q -> q.eq(MaterialClassify::getName, name).or().eq(MaterialClassify::getCode, code))
                .ne(ObjectUtil.isNotEmpty(excludeId), MaterialClassify::getId, excludeId)
                .count();

        Assert.eqZero(count, "存在相同分类名称或编码");

    }

}
