package com.qiaoba.module.tenant.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiaoba.common.base.enums.BaseEnum;
import com.qiaoba.module.tenant.entity.SysTenantDatasource;
import com.qiaoba.module.tenant.entity.param.SysTenantDatasourceParam;
import com.qiaoba.module.tenant.mapper.SysTenantDatasourceMapper;
import com.qiaoba.module.tenant.service.SysTenantDatasourceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 租户数据源 服务层实现
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/6/7 14:49
 */
@Service
@RequiredArgsConstructor
public class SysTenantDatasourceServiceImpl implements SysTenantDatasourceService {

    private final SysTenantDatasourceMapper sysTenantDatasourceMapper;

    @Override
    public SysTenantDatasource selectMaster(String tenantId) {
        return sysTenantDatasourceMapper.selectOne(paramToWrapper(new SysTenantDatasourceParam(tenantId, BaseEnum.YES.getCode())));
    }

    @Override
    public int insert(SysTenantDatasource sysTenantDatasource) {
        return sysTenantDatasourceMapper.insert(sysTenantDatasource);
    }

    @Override
    public int updateById(SysTenantDatasource sysTenantDatasource) {
        return sysTenantDatasourceMapper.updateById(sysTenantDatasource);
    }

    @Override
    public int deleteByIds(List<String> ids) {
        return sysTenantDatasourceMapper.deleteBatchIds(ids);
    }

    @Override
    public List<SysTenantDatasource> selectList(String tenantId) {
        return sysTenantDatasourceMapper.selectList(paramToWrapper(new SysTenantDatasourceParam(tenantId)));
    }

    @Override
    public List<SysTenantDatasource> selectList(SysTenantDatasourceParam param) {
        return sysTenantDatasourceMapper.selectList(paramToWrapper(param));
    }

    private QueryWrapper<SysTenantDatasource> paramToWrapper(SysTenantDatasourceParam param) {
        QueryWrapper<SysTenantDatasource> wrapper = new QueryWrapper<>();
        wrapper.lambda()
                .eq(StrUtil.isNotBlank(param.getTenantId()), SysTenantDatasource::getTenantId, param.getTenantId())
                .eq(StrUtil.isNotBlank(param.getIsUse()), SysTenantDatasource::getIsUse, param.getIsUse())
                .eq(StrUtil.isNotBlank(param.getIsMaster()), SysTenantDatasource::getIsMaster, param.getIsMaster());

        return wrapper;
    }
}
