package com.xtd.project.system.service.impl;

import com.xtd.common.exception.BaseException;
import com.xtd.common.utils.DateUtils;
import com.xtd.common.utils.tree.TreeParser;
import com.xtd.project.system.domain.DbMateriel;
import com.xtd.project.system.domain.vo.TreeNodeVo;
import com.xtd.project.system.mapper.DbMaterielMapper;
import com.xtd.project.system.service.IDbMaterielService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 物料Service业务层处理
 *
 * @author xtd
 * @date 2020-04-07
 */
@Service
public class DbMaterielServiceImpl implements IDbMaterielService {
    @Autowired
    private DbMaterielMapper dbMaterielMapper;

    /**
     * 查询物料
     *
     * @param mId 物料ID
     * @return 物料
     */
    @Override
    public DbMateriel selectDbMaterielById(Long mId) {
        return dbMaterielMapper.selectDbMaterielById(mId);
    }

    /**
     * 查询物料列表
     *
     * @param dbMateriel 物料
     * @return 物料
     */
    @Override
    public List<DbMateriel> selectDbMaterielList(DbMateriel dbMateriel) {
        return dbMaterielMapper.selectDbMaterielList(dbMateriel);
    }

    /**
     * 新增物料
     *
     * @param dbMateriel 物料
     * @return 结果
     */
    @Override
    public int insertDbMateriel(DbMateriel dbMateriel) {

        dbMateriel.setCreateTime(DateUtils.getNowDate());
        return dbMaterielMapper.insertDbMateriel(dbMateriel);
    }

    /**
     * 修改物料
     *
     * @param dbMateriel 物料
     * @return 结果
     */
    @Override
    public int updateDbMateriel(DbMateriel dbMateriel) {
        dbMateriel.setUpdateTime(DateUtils.getNowDate());
        return dbMaterielMapper.updateDbMateriel(dbMateriel);
    }

    /**
     * 批量删除物料
     *
     * @param mIds 需要删除的物料ID
     * @return 结果
     */
    @Override
    public int deleteDbMaterielByIds(Long[] mIds) {
        DbMateriel dbMateriel=new DbMateriel();
        for (Long mId : mIds) {
            dbMateriel.setParentId(mId);
            List<DbMateriel> dbMateriels = dbMaterielMapper.checkData(mId);
            if(dbMateriels.size()>0) {
                throw new BaseException("200", "下级存在数据无法删除!");
            }
        }
        return dbMaterielMapper.deleteDbMaterielByIds(mIds);
    }

    /**
     * 删除物料信息
     *
     * @param mId 物料ID
     * @return 结果
     */
    @Override
    public int deleteDbMaterielById(Long mId) {
        return dbMaterielMapper.deleteDbMaterielById(mId);
    }

    @Override
    public List<TreeNodeVo> treelist() {
        List<TreeNodeVo> dbMateriels = dbMaterielMapper.treelist();
        List<TreeNodeVo> treeList = TreeParser.getTreeList(0L, dbMateriels);
        return treeList;
    }
}
