package com.artfess.security.manager.impl;

import com.artfess.base.manager.impl.BaseManagerImpl;
import com.artfess.security.dao.SecurityMachineDao;
import com.artfess.security.manager.SecurityMachineManager;
import com.artfess.security.model.SecurityMachine;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * 安全中心  ---  涉密计算机维护表 服务实现类
 *
 * @company 阿特菲斯
 * @author cs
 * @since 2021-03-04
 */
@Service
public class SecurityMachineManagerImpl extends BaseManagerImpl<SecurityMachineDao, SecurityMachine> implements SecurityMachineManager {

    @Override
    @Transactional
    public String saveMachine(SecurityMachine machine) {
        Assert.notNull(machine, "保存信息不能为空！");
        int num = this.checkSameCode(machine.getId(),machine.getCode());
        if(num>0){
            throw new RuntimeException("编码【"+machine.getCode()+"】重复！");
        }
        int ipNum = this.checkSameIp(machine.getId(),machine.getIp());
        if(ipNum>0){
            throw new RuntimeException("已存在IP为：【"+machine.getIp()+"】的机器！");
        }
        if(StringUtils.isBlank(machine.getId())) {
            this.baseMapper.insert(machine);
        }else{
            this.baseMapper.updateById(machine);
        }
        return machine.getId();
    }

    public int checkSameCode(String id,String code) {
        Assert.hasText(code, "编码不能为空");
        QueryWrapper<SecurityMachine> queryWrapper = new QueryWrapper();
        queryWrapper.eq("code_", code);
        queryWrapper.ne(StringUtils.isNotBlank(id), "id_",id);
        int num = this.baseMapper.selectCount(queryWrapper);
        return num;
    }

    public int checkSameIp(String id,String ip) {
        Assert.hasText(ip, "ip不能为空");
        QueryWrapper<SecurityMachine> queryWrapper = new QueryWrapper();
        queryWrapper.eq("ip_", ip);
        queryWrapper.ne(StringUtils.isNotBlank(id), "id_",id);
        int num = this.baseMapper.selectCount(queryWrapper);
        return num;
    }
}
