package com.usky.data.service.impl;

import com.usky.data.domain.DataLink;
import com.usky.data.mapper.DataLinkMapper;
import com.usky.data.service.DataLinkService;
import com.usky.common.mybatis.core.AbstractCrudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.List;

/**
 * <p>
 * 数据中心_数据连接表 服务实现类
 * </p>
 *
 * @author fyc
 * @since 2026-01-23
 */
@Service
public class DataLinkServiceImpl extends AbstractCrudService<DataLinkMapper, DataLink> implements DataLinkService {

    @Autowired
    private DataLinkMapper dataLinkMapper;

    @Override
    public boolean testDbConnection(DataLink dataLink) {
        Connection connection = null;
        try {
            // 根据数据库类型加载驱动
            String driverClass = getDriverClass(dataLink.getDbType());
            Class.forName(driverClass);

            // 构建连接URL
            String url = buildJdbcUrl(dataLink);

            // 建立连接
            connection = DriverManager.getConnection(url, dataLink.getDbName(), dataLink.getPassword());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public boolean isExistByFullName(String fullName, Integer id) {
        int count = dataLinkMapper.countByFullName(fullName, id);
        return count > 0;
    }

    @Override
    public List<DataLink> getList() {
        return dataLinkMapper.selectList(null);
    }

    @Override
    public List<DataLink> getList(int page, int pageSize, String keyword) {
        // 计算起始索引
        int startIndex = (page - 1) * pageSize;
        return dataLinkMapper.selectPageList(startIndex, pageSize, keyword);
    }

    /**
     * 根据数据库类型获取驱动类名
     */
    private String getDriverClass(String dbType) {
        switch (dbType.toLowerCase()) {
            case "mysql":
                return "com.mysql.cj.jdbc.Driver";
            case "oracle":
                return "oracle.jdbc.OracleDriver";
            case "sqlserver":
                return "com.microsoft.sqlserver.jdbc.SQLServerDriver";
            case "postgresql":
                return "org.postgresql.Driver";
            default:
                throw new IllegalArgumentException("不支持的数据库类型: " + dbType);
        }
    }

    /**
     * 构建JDBC连接URL
     */
    private String buildJdbcUrl(DataLink dataLink) {
        String dbType = dataLink.getDbType().toLowerCase();
        String host = dataLink.getHost();
        Integer port = dataLink.getPort();
        String dbName = dataLink.getDbName();

        switch (dbType) {
            case "mysql":
                return String.format("jdbc:mysql://%s:%d/%s?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%%2B8",
                        host, port, dbName);
            case "oracle":
                // Oracle支持SID和Service Name两种方式
                if (dataLink.getServiceName() != null && !dataLink.getServiceName().isEmpty()) {
                    return String.format("jdbc:oracle:thin:@//%s:%d/%s", host, port, dataLink.getServiceName());
                } else {
                    return String.format("jdbc:oracle:thin:@%s:%d:%s", host, port, dbName);
                }
            case "sqlserver":
                return String.format("jdbc:sqlserver://%s:%d;databaseName=%s;encrypt=false", host, port, dbName);
            case "postgresql":
                return String.format("jdbc:postgresql://%s:%d/%s", host, port, dbName);
            default:
                throw new IllegalArgumentException("不支持的数据库类型: " + dbType);
        }
    }
}
