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

import cn.hutool.core.bean.BeanUtil;
import com.qiaoba.common.base.enums.BaseEnum;
import com.qiaoba.common.base.enums.DataBaseEnum;
import com.qiaoba.common.database.entity.DynamicDataSource;
import com.qiaoba.common.database.service.DynamicDatasourceService;
import com.qiaoba.module.tenant.entity.SysTenantDatasource;
import com.qiaoba.module.tenant.entity.param.SysTenantDatasourceParam;
import com.qiaoba.module.tenant.service.SysTenantDatasourceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 动态数据源接口
 *
 * @author ailanyin
 * @version 1.0
 * @since 2023/6/9 13:16
 */
@Service
@RequiredArgsConstructor
public class DynamicDatasourceServiceImpl implements DynamicDatasourceService {

    private final SysTenantDatasourceService sysTenantDatasourceService;

    @Override
    public Map<String, List<DynamicDataSource>> loadAllTenantDatasource() {
        Map<String, List<DynamicDataSource>> datasourceMap = new LinkedHashMap<>();
        List<String> tenantIds = sysTenantDatasourceService.selectTenantIds();
        for (String tenantId : tenantIds) {
            List<SysTenantDatasource> datasourceList = sysTenantDatasourceService.selectList(new SysTenantDatasourceParam(tenantId));
            datasourceMap.put(tenantId, transform(datasourceList));
        }
        return datasourceMap;
    }

    @Override
    public void changePrimaryDatasource(String tenantId, String datasourceId) {
        // 将该数据源设置为主要数据源
        SysTenantDatasource sysTenantDatasource = new SysTenantDatasource();
        sysTenantDatasource.setDatasourceId(datasourceId);
        sysTenantDatasource.setIsPrimary(BaseEnum.YES.getCode());
        sysTenantDatasourceService.updateById(sysTenantDatasource);
        // 将该租户下的其他数据源设置为非主要数据源
        sysTenantDatasourceService.setBackupDatasourceExcludeId(tenantId, datasourceId);
    }

    private List<DynamicDataSource> transform(List<SysTenantDatasource> datasourceList) {
        List<DynamicDataSource> dynamicDataSourceList = new ArrayList<>();
        for (SysTenantDatasource datasource : datasourceList) {
            DynamicDataSource dynamicDataSource = BeanUtil.copyProperties(datasource, DynamicDataSource.class);
            dynamicDataSource.setInitialSize(datasource.getInitCount());
            dynamicDataSource.setMinIdle(datasource.getMinCount());
            dynamicDataSource.setMaxActive(datasource.getMaxCount());
            dynamicDataSource.setDriver(DataBaseEnum.getDriver(datasource.getType()));
            dynamicDataSource.setUrl(DataBaseEnum.getUrl(datasource.getType(), datasource.getIp(), datasource.getPort(), datasource.getName()));
            dynamicDataSourceList.add(dynamicDataSource);
        }
        return dynamicDataSourceList;
    }
}
