package com.hzya.frame.webapp.web.init;
import com.baomidou.dynamic.datasource.DynamicRoutingDataSource;
import com.hzya.frame.util.AESUtil;
import lombok.RequiredArgsConstructor;
import org.flywaydb.core.Flyway;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.sql.DataSource;

@Configuration
@RequiredArgsConstructor
@EnableTransactionManagement
public class FlywayConfig {

    @Value("${spring.flyway.enabled}")
    private String enabled;
    @Value("${spring.flyway.clean-disabled}")
    private boolean cleanDisabled;
    @Value("${spring.flyway.locations}")
    private String locations;
    @Value("${spring.flyway.table}")
    private String table;
    @Value("${spring.flyway.placeholder-replacement}")
    private boolean placeholderReplacement;
    @Value("${spring.flyway.baseline-on-migrate}")
    private boolean baselineOnMigrate;
    @Value("${spring.flyway.validate-on-migrate}")
    private boolean validateOnMigrat;
    @Value("${spring.flyway.sql-migration-prefix}")
    private String sqlMigrationPrefix;
    @Value("${spring.flyway.sql-migration-separator}")
    private String sqlMigrationSeparator;
    @Value("${spring.flyway.sql-migration-suffixes}")
    private String sqlMigrationSuffixes;
    @Value("${spring.datasource.dynamic.datasource.master.url}")
    private  String url;
    @Value("${spring.datasource.dynamic.datasource.master.username}")
    private  String username;
    @Value("${spring.datasource.dynamic.datasource.master.password}")
    private  String password;
    @Resource
    private DataSource dataSource;


    @PostConstruct
    public void migrateOrder() {
        if("false".equals(enabled)){
            String pwd = AESUtil.decrypt(password);
            DynamicRoutingDataSource ds = (DynamicRoutingDataSource) dataSource;
            DataSource dsDatasource = null;

            dsDatasource = ds.getDataSource("master");
            // 将路径转换
            Flyway flyway = Flyway.configure()
                    //.dataSource(url,username,pwd)
                    .dataSource(dsDatasource)
                    .cleanDisabled(cleanDisabled)
                    .locations(locations)
                    .table(table)
                    .encoding("utf-8")
                    .outOfOrder(true)
                    .baselineOnMigrate(true)
                    .validateOnMigrate(baselineOnMigrate)
                    .validateOnMigrate(validateOnMigrat)
                    .sqlMigrationPrefix(sqlMigrationPrefix)
                    .sqlMigrationSeparator(sqlMigrationSeparator)
                    .sqlMigrationSuffixes(sqlMigrationSuffixes)
                    .placeholderReplacement(placeholderReplacement)
                    .load();
            flyway.migrate();
        }
    }

}
