package com.ecep.contract.cloud.u8;


import com.ecep.contract.ds.other.service.SysConfService;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;

@Lazy
@Component
@ConditionalOnBean(YongYouU8Service.class)
public class U8DataSourceFactory {
    @Lazy
    @Autowired
    private SysConfService service;

    public U8DataSourceFactory() {
        System.out.println("U8DataSourceFactory.U8DataSourceFactory");
    }

    @Lazy
    @Bean
    // @ConfigurationProperties(prefix = "u8.datasource")
    public DataSource MSSQL_Server() {
        System.out.println("U8DataSourceFactory.MSSQL_Server");

        String host = service.get("u8.db.server.ip", "192.168.1.1");
        String database = service.get("u8.db.database", "UF_DATA");
        String username = service.get("u8.db.server.name", "sa");
        String password = service.get("u8.db.server.password", "");
        boolean encrypt = service.get("u8.db.server.encrypt", false);
        boolean trustServerCertificate = service.get("u8.db.server.trustServerCertificate", true);

        String url = "jdbc:sqlserver://" +
                host +
                ";databaseName=" +
                database +
                ";encrypt=" +
                encrypt +
                ";trustServerCertificate=" +
                trustServerCertificate
//                +  ";sslProtocol=TLSv1"
                ;

        HikariDataSource source = DataSourceBuilder.create()
                .type(HikariDataSource.class)
                .url(url)
                .username(username)
                .password(password)
                .driverClassName("com.microsoft.sqlserver.jdbc.SQLServerDriver")
                .build();
        source.setMinimumIdle(0);
        return source;
    }
}
