package com.zm.order.tool.server.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @author nianchang
 * @ClassName CyMarketingConfig
 * @date 2021/11/24 2:36 下午
 */
@Configuration
@MapperScan(basePackages = {"com.zm.order.tool.server.cymarketing"},
        sqlSessionTemplateRef = "cyMarketingDataSqlSessionTemplate")
@EnableConfigurationProperties(CyMarketingProperty.class)
public class CyMarketingConfig {

    private static final Logger logger = LoggerFactory.getLogger(CyMarketingConfig.class);

    @Autowired
    private CyMarketingProperty property;

    @Bean(name = "cyMarketingDataDataSource")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(property.getUrl());
        dataSource.setUsername(property.getUserName());
        dataSource.setPassword(property.getPassword());
        dataSource.setDriverClassName(property.getDriverClassName());
        logger.info("init temp data data source success");
        return dataSource;
    }

    @Bean("cyMarketingDataSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(
            @Value("${mybatis.cy.marketing.mapper-locations}") String mapperLocations,
            @Value("${mybatis.config-location}") String configLocation
    ) throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource());
        Resource[] mapperLocationsResource = new PathMatchingResourcePatternResolver().getResources(mapperLocations);
        sqlSessionFactoryBean.setMapperLocations(mapperLocationsResource);
        sqlSessionFactoryBean.setConfigLocation(
                new PathMatchingResourcePatternResolver().getResource(configLocation)
        );
        return sqlSessionFactoryBean.getObject();
    }

    @Bean("cyMarketingDataSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("cyMarketingDataSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
        return sqlSessionTemplate;
    }
}
