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 selectPrimary(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));
    }

    @Override
    public List<String> selectTenantIds() {
        return sysTenantDatasourceMapper.selectTenantIds();
    }

    @Override
    public void setBackupDatasourceExcludeId(String tenantId, String excludeId) {
        sysTenantDatasourceMapper.setBackupDatasourceExcludeId(tenantId,excludeId,BaseEnum.NO.getCode());
    }

    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.getIsPrimary()), SysTenantDatasource::getIsPrimary, param.getIsPrimary());
        return wrapper;
    }
}
