package com.yeejoin.equipmanage.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yeejoin.equipmanage.common.entity.Unit;
import com.yeejoin.equipmanage.common.exception.CommonException;
import com.yeejoin.equipmanage.mapper.UnitMapper;
import com.yeejoin.equipmanage.service.IUnitService;

/**
 * 计量单位 服务实现类
 *
 * @author wujiang
 * @date 2020-07-07
 */
@Service
public class UnitServiceImpl extends ServiceImpl<UnitMapper, Unit> implements IUnitService {

	@Override
	public List<Map<String, Object>> getUnitClassification() {
		List<Map<String, Object>> lists = this.baseMapper.getUnitClassification();
		for (Map<String, Object> map : lists) {
			if (map.get("code").toString().length() < 4) {
				map.put("code", "0" + map.get("code"));
			}
		}
		return lists;
	}

	@Override
	public Unit saveUnit(Unit unit) {
		QueryWrapper<Unit> unitQueryWrapper = new QueryWrapper<>();
	 	unitQueryWrapper.lambda().eq(Unit::getName, unit.getName());
	 	int count = this.count(unitQueryWrapper);
	 	if(count>0){
	 		throw new CommonException(0, "名称重复");
	 	}
		if(ObjectUtils.isEmpty(unit.getParentId())){
			unit.setCode(this.baseMapper.getUnitFirstLevelCode());
	 	}else{
	 		unit.setCode(this.baseMapper.getUnitSecondLevelCode(unit.getParentId()));
	 	}
		this.save(unit);
		return unit;
	}

	@Override
	public List<Unit> getUnitList(Unit unit) {
		// TODO Auto-generated method stub
		return this.baseMapper.getUnitList(unit.getName());
	}

	@Override
	public List<Unit> getUnitListsById(List<String> ids) {
		List<Unit> list = new ArrayList<>();
		for (String id : ids) {
			Unit unit = this.baseMapper.getOne(id);
			list.add(unit);
		}
		return list;
	}

}
