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.List;

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

    private final SysTenantDatasourceService sysTenantDatasourceService;

    @Override
    public List<DynamicDataSource> loadAllTenantDatasource() {
        SysTenantDatasourceParam param = new SysTenantDatasourceParam();
        param.setIsUse(BaseEnum.YES.getCode());
        List<SysTenantDatasource> datasourceList = sysTenantDatasourceService.selectList(param);
        return transform(datasourceList);
    }

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