package digital.laboratory.platform.entrustment.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import digital.laboratory.platform.entrustment.entity.Deliverer;
import digital.laboratory.platform.entrustment.mapper.DelivererMapper;
import digital.laboratory.platform.entrustment.service.DelivererService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 送检员服务实现类
 *
 * @author Zhang Xiaolong created at  2022-08-16
 * @describe 送检员 服务实现类
 */
@Service
public class DelivererServiceImpl extends ServiceImpl<DelivererMapper, Deliverer> implements DelivererService {
	/**
	 * 更新送检员
	 * 以送检员的名字为关键字, 如果同名送检员存在, 更新其他属性; 如果同名送检员不存在, 则新增数据库记录
	 * @param deliverer
	 */
	@Override
	public boolean renew(Deliverer deliverer) {
		if (StrUtil.isBlank(deliverer.getName())) {
			return false;
		}
		List<Deliverer> list = baseMapper.selectList(Wrappers.<Deliverer>query()
				.eq("owner_user_id", deliverer.getOwnerUserId())
						.eq("name", deliverer.getName())
		);
		
		if (list.size() > 0) {
			//== 存在同名送检员, 更新之
			deliverer.setId(list.get(0).getId());
			baseMapper.update(deliverer, Wrappers.<Deliverer>query()
					.eq("owner_user_id", deliverer.getOwnerUserId())
					.eq("name", deliverer.getName())
			);
		}
		else {
			deliverer.setId(IdWorker.get32UUID().toUpperCase());
			baseMapper.insert(deliverer);
		}
		return true;
	}

	@Override
	public Deliverer getByName(String name, String ownerUserId) {
		Deliverer deliverer = baseMapper.selectOne(Wrappers.<Deliverer>query()
				.eq("owner_user_id", ownerUserId)
				.eq("name", name)
		);
		return deliverer;
	}
}
