package com.usoftchina.bi.server.service.dataSource;

import com.usoftchina.bi.core.base.RepCode;
import com.usoftchina.bi.core.base.RepEntity;
import com.usoftchina.bi.server.dao.chart.ChartsConfigMapper;
import com.usoftchina.bi.server.dao.chart.ShowChartsMapper;
import com.usoftchina.bi.server.model.vo.configVo.ColumnScreenInfo;
import com.usoftchina.bi.server.service.chart.GetChartsDataUtilService;
import com.usoftchina.bi.server.service.chart.ChartsUtilService;
import com.usoftchina.bi.core.jdbc.DynamicDataSourceContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ColumnScreenService {
    @Autowired
    ShowChartsMapper showChartsMapper;
    @Autowired
    GetChartsDataUtilService getChartsDataUtilService;
    @Autowired
    ChartsConfigMapper chartsConfigMapper;
    @Autowired
    ChartsUtilService chartsUtilService;

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

    public RepEntity getScreenData(ColumnScreenInfo columnScreenInfo, String token){
        //取表名
        int id = columnScreenInfo.getId();
        String tableName = chartsUtilService.getSqlStr(token, id, 0);
        if ("".equals(tableName)){
            return new RepEntity(RepCode.NoAuthority);
        }

        List<Object> data = new ArrayList<>();

        int baseId = getChartsDataUtilService.getBaseId(id);
        logger.info("切换数据库: {}", baseId);

        try{
            if (!DynamicDataSourceContextHolder.isContainsDataSource(baseId)) {
                logger.info("数据源:{} 不存在,使用默认的数据源", baseId);
                return new RepEntity(RepCode.DataSourceNull);
            } else {
                logger.info("使用数据源：{}", baseId);
                DynamicDataSourceContextHolder.setDataSourceType(baseId);
            }
            data =  showChartsMapper.getScreenData(columnScreenInfo.getColumnName(), tableName, columnScreenInfo.getKeyword(), columnScreenInfo.getCount());
        }catch (Exception e){
            e.printStackTrace();
            if (e.getCause().getMessage().contains("ORA-00904:")) {
                return new RepEntity(RepCode.erro.getCode(), "数据源" + e.getCause().getMessage().replace("ORA-00904:", "").replaceAll("标识符", "列"), null);
            }
            return new RepEntity(RepCode.erro.getCode(), e.getCause().getMessage(), null);
        }finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
        return new RepEntity(RepCode.success, data);
    }

    /*
    通过数据源ID获取列的值
     */
    public RepEntity<List<Object>> getScreenByBaseId(ColumnScreenInfo columnScreenInfo){
        //取表名
        int connectId = columnScreenInfo.getId();
        String tableName = chartsConfigMapper.getTableNameByBase(connectId);
        if (tableName == null || "".equals(tableName)){
            return new RepEntity(RepCode.nullTableName);
        }else {
            tableName = "(" + tableName +")";
        }

        List<Object> data = new ArrayList<>();

        int baseId =  getChartsDataUtilService.getBaseIdByConnect(connectId);
        logger.info("切换数据库={}", baseId);

        try{
            if (!DynamicDataSourceContextHolder.isContainsDataSource(baseId)) {
                logger.info("数据源: {}不存在,使用默认的数据源", baseId);
                return new RepEntity(RepCode.DataSourceNull);
            } else {
                logger.info("使用数据源：{}", baseId);
                DynamicDataSourceContextHolder.setDataSourceType(baseId);
            }
            data =  showChartsMapper.getScreenData(columnScreenInfo.getColumnName(), tableName, columnScreenInfo.getKeyword(), columnScreenInfo.getCount());
        }catch (Exception e){
            e.printStackTrace();
            if (e.getCause().getMessage().contains("ORA-00904:")) {
                return new RepEntity(RepCode.erro.getCode(), "数据源" + e.getCause().getMessage().replace("ORA-00904:", "").replaceAll("标识符", "列"), null);
            }
            return new RepEntity(RepCode.erro.getCode(), e.getCause().getMessage(), null);
        }finally {
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
        return new RepEntity(RepCode.success, data);
    }

    /**
     * 通过多个数据源ID获取列的值
     * @param columnScreenInfo
     * @return
     */
    public RepEntity getScreenByBaseIds(List<ColumnScreenInfo> columnScreenInfo){
        List<Object> dataList = new ArrayList<>();
        for (ColumnScreenInfo info : columnScreenInfo) {
            dataList.addAll(getScreenByBaseId(info).getData());
        }
        List<Object> result = dataList.stream().distinct().collect(Collectors.toList());
        if (result.size() > 20) {
            return new RepEntity(RepCode.success, result.subList(0, 20));
        }else {
            return new RepEntity(RepCode.success, result);
        }
    }

}
