package cd.casic.module.machine.dal.mysql;

import cd.casic.framework.commons.pojo.PageResult;
import cd.casic.framework.mybatis.core.mapper.BaseMapperX;
import cd.casic.framework.mybatis.core.query.LambdaQueryWrapperX;
import cd.casic.module.machine.controller.vo.MachineInfoVO;
import cd.casic.module.machine.dal.dataobject.MachineInfoDO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

@Mapper
public interface MachineInfoMapper extends BaseMapperX<MachineInfoDO> {
    default Boolean existsByTag(String tag) {
        return selectOne(new QueryWrapper<MachineInfoDO>().eq("tag", tag)) != null;
    }

    default void updateStatus(Long machineInfoId, Integer status) {
        UpdateWrapper<MachineInfoDO> set = new UpdateWrapper<>();
        set.eq("id", machineInfoId).set("status", status);
        this.update(null, set);
    }

    default void bindingSecretKey(List<Long> machineInfoIds, Long secretKeyId,Boolean enableBind) {
        UpdateWrapper<MachineInfoDO> wrapper = new UpdateWrapper<>();
        wrapper.in("id", machineInfoIds);
        if (enableBind){
             wrapper.set("secret_key_id", secretKeyId);// 匹配 ID 集合
        }else {
            wrapper.set("secret_key_id", null);
        }
        this.update(null, wrapper);
    }

    default PageResult<MachineInfoDO> selectPage(MachineInfoVO machineInfoVO) {
        LambdaQueryWrapperX<MachineInfoDO> machineInfoDOLambdaQueryWrapperX = new LambdaQueryWrapperX<MachineInfoDO>()
            .likeIfPresent(MachineInfoDO::getName, machineInfoVO.getName())
            .likeIfPresent(MachineInfoDO::getTag, machineInfoVO.getTag())
            .likeIfPresent(MachineInfoDO::getDescription, machineInfoVO.getDescription())
            .likeIfPresent(MachineInfoDO::getUsername, machineInfoVO.getUsername())
            .likeIfPresent(MachineInfoDO::getHostIp, machineInfoVO.getHostIp());
        if (machineInfoVO.getStatus() != -1) {
            machineInfoDOLambdaQueryWrapperX.eqIfPresent(MachineInfoDO::getStatus, machineInfoVO.getStatus());
        }
        return selectPage(machineInfoVO, machineInfoDOLambdaQueryWrapperX);
    }

    default List<MachineInfoDO> selectBindMachineBySecretKey(Long secretKeyId) {
        LambdaQueryWrapperX<MachineInfoDO> lambdaQueryWrapperX = new LambdaQueryWrapperX<MachineInfoDO>()
            .eq(MachineInfoDO::getSecretKeyId, secretKeyId);
        return selectList(lambdaQueryWrapperX);
    }

}
