package com.tofly.watermeter.custom.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tofly.common.core.util.StringUtil;
import com.tofly.common.oauth.exception.ToflyDeniedException;
import com.tofly.watermeter.custom.service.EquipmentService;
import com.tofly.watermeter.entity.Qfcbsbgl;
import com.tofly.watermeter.service.QfcbsbglService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author FlashWJL
 * @date 2021/4/14 15:55
 */
@Service
@AllArgsConstructor
public class EquipmentServiceImpl implements EquipmentService {

    private final QfcbsbglService cbsbglService;

    @Override
    public boolean saveEqui(Qfcbsbgl qfcbsbgl) {
        String equiBh = qfcbsbgl.getSbbh();
        String state = qfcbsbgl.getState();
        Date lqsj = qfcbsbgl.getLqsj();
        Long lqry = qfcbsbgl.getCyry();
        if (StringUtil.isEmpty(equiBh)) {
            throw new ToflyDeniedException("请输入设备编号");
        }
        //已发放
        if ("1".equals(state)) {
            if (StringUtil.isNull(lqsj)) {
                throw new ToflyDeniedException("请选择领取时间");
            }
            if (StringUtil.isNull(lqry)) {
                throw new ToflyDeniedException("请选择领取人员");
            }
        }
        //保存之前需要判断是否有相同的设备编码
        Qfcbsbgl sb = cbsbglService.getOne(Wrappers.<Qfcbsbgl>lambdaQuery().eq(Qfcbsbgl::getSbbh, equiBh).select(Qfcbsbgl::getId));
        if (StringUtil.isNotNull(sb)) {
            throw new ToflyDeniedException("设备编号不能重复：" + equiBh);
        }
        return cbsbglService.save(qfcbsbgl);
    }

    @Override
    public boolean removeById(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            //先查询该设备是否已经有人使用，如果有人使用则不能删除
            Qfcbsbgl qfcbsbgl = cbsbglService.getById(id);
            if (StringUtil.isNull(qfcbsbgl)){
                throw new ToflyDeniedException("请正确选择设备");
            }
            if (qfcbsbgl.getState().equals("1")) {
                throw new ToflyDeniedException("该设备正在使用中，暂无法删除");
            }
            cbsbglService.removeById(id);
        }
        return true;
    }

}
