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

import com.usoftchina.bi.core.base.RepCode;
import com.usoftchina.bi.core.base.RepEntity;
import com.usoftchina.bi.core.utils.CalculationJudgeUtil;
import com.usoftchina.bi.server.dao.chart.ChartsConfigMapper;
import com.usoftchina.bi.server.dao.chart.ShowChartsMapper;
import com.usoftchina.bi.server.model.bo.*;
import com.usoftchina.bi.server.model.vo.configVo.PieConfigInfo;
import com.usoftchina.bi.server.model.vo.dataVo.ChartsDataInfo;
import com.usoftchina.bi.core.jdbc.DynamicDataSourceContextHolder;
import com.usoftchina.bi.server.utils.ScreenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@Service
public class ShowPieService {
    @Autowired
    ShowChartsMapper showChartsMapper;
    @Autowired
    TimeConverterUtil timeConverterUtil;
    @Autowired
    ChartsConfigMapper chartsConfigMapper;
    @Autowired
    ScreenUtil screenUtil;
    @Autowired
    GetChartsDataUtilService getChartsDataUtilService;
    @Autowired
    ChartsUtilService chartsUtilService;

    /*
    Pie数据展示
     */
    public RepEntity showPie(PieConfigInfo pieConfigInfo, String token, int dashId, String styleConfig){
        ChartsDataInfo<PieSeries> chartsDataInfo = new ChartsDataInfo();
        chartsDataInfo.setStyleConfig(styleConfig);
        TimeReture timeReture = new TimeReture();
        if (pieConfigInfo == null || "".equals(pieConfigInfo)){
            return new RepEntity(RepCode.Null);
        }
        int id = pieConfigInfo.getId();
        //获取列配置
        ChartsColumnConfig chartsColumn = chartsConfigMapper.getChartsColumn(id);
        if (chartsColumn == null || "".equals(chartsColumn)){
            return new RepEntity(RepCode.Null);
        }
        chartsDataInfo.setChartsColumnConfig(chartsColumn);
        String tableName = chartsUtilService.getSqlStr(token, id, dashId);
        if ("".equals(tableName)){
            return new RepEntity(RepCode.NoAuthority);
        }

        int baseId = getChartsDataUtilService.getBaseId(id);
        try{
            if (!DynamicDataSourceContextHolder.isContainsDataSource(baseId)) {
                return new RepEntity(RepCode.DataSourceNull);
            } else {
                DynamicDataSourceContextHolder.setDataSourceType(baseId);
            }

        String xColumn = pieConfigInfo.getLegendData().getColumnRename();
        String yColumn = pieConfigInfo.getSeries().getColumnRename();
        String xColumnType = pieConfigInfo.getLegendData().getColumnType();

        String xAxisType = pieConfigInfo.getLegendData().getShowDataType();

        if (xColumn == null || "".equals(xColumn) || yColumn == null || "".equals(yColumn)){
            return new RepEntity(RepCode.nullAxis);
        }

        String yType = pieConfigInfo.getSeries().getShowDataType();
        String yAxisType = CalculationJudgeUtil.Judge(yType);


        PieSeries series = new PieSeries();
        List<PieSeriesMap> value = new ArrayList<PieSeriesMap>();
        List<PieSeries> serieses = new ArrayList<PieSeries>();    //生成柱状图的系列
        List<String> xAxisData = new ArrayList<String>();  //X轴自己用
        List<String> xData = new ArrayList<String>();      //X轴前端用

        //取筛选列表
        List<Screen> screens = pieConfigInfo.getFilters();
        ScreenStr scr = new ScreenStr();
        String screen = "";               //正常筛选条件
        String screenToColumn = "";       //跟目标列相同的筛选条件
        String screenToColumnS = "";       //跟目标列相同的筛选条件
        if ("".equals(screens) || screens == null || screens.size() == 0){
            screen = "";
        }else {
            scr = screenUtil.screensUtil(screens, xColumn, xColumnType);
            screen = scr.getRet();
            screenToColumn = scr.getWithColumnRet();
            StringBuilder sb = new StringBuilder(screenToColumn);
            if (screenToColumn != null && !("".equals(screenToColumn))){
                screenToColumnS = screenToColumn + " " + screen;               //and
                screenToColumn = String.valueOf(sb .replace(1, 5, "where "));
                screen = screenToColumn + " " + screen;         //where
            } else {
                StringBuilder sb1 = new StringBuilder(screen);
                screenToColumnS = screen;
                screen = String.valueOf(sb1 .replace(1, 5, "where "));
            }
        }

        //X轴
        //判断是否为日期类型
        if ("time".equals(xColumnType)){
            timeReture = timeConverterUtil.timeConverter(xColumn, tableName, xAxisType, screen, pieConfigInfo.getMaxCount());
            xAxisData = timeReture.getValues();
            chartsDataInfo.setTooMany(timeReture.isOverdose());
            xData = timeConverterUtil.toRespons(xAxisData,xAxisType );
        }else {
            int count = showChartsMapper.getNumForX(xColumn, tableName);
            if (count > pieConfigInfo.getMaxCount()){
                chartsDataInfo.setTooMany(true);
            }
            xAxisData = showChartsMapper.getXAxis(xColumn, tableName, screen, pieConfigInfo.getMaxCount());

        }
        if ("".equals(xAxisData) || xAxisData == null || xAxisData.size() == 0){
            return new RepEntity(RepCode.Null);
        }
        if ("week".equals(xAxisType) || "month".equals(xAxisType) || "quarter".equals(xAxisType)){
            chartsDataInfo.setxAxis(xData);
        }else {
            chartsDataInfo.setxAxis(xAxisData);
        }

        //无分组时Y值
        Iterator itX = xAxisData.iterator();
        while (itX.hasNext()){
            String xdata = (String)itX.next();
            if ("".equals(xdata) || xdata == null){
                //continue;
            }
            double valueOne = 0;
            String valueOnes = null;
            PieSeriesMap pieSeriesMap = new PieSeriesMap();
            if ("time".equals(xColumnType)){
                valueOnes = timeConverterUtil.getTimeValueConverter(yColumn, xColumn, tableName, yAxisType, xAxisType, xdata, screenToColumnS);
            }else {
                if (xdata == null || "".equals(xdata)){
                    valueOnes = showChartsMapper.getValuesIsNull(yColumn, xColumn, tableName, yAxisType, screenToColumnS);
                }else {
                    valueOnes = showChartsMapper.getXValue(yColumn, xColumn, tableName, yAxisType, xdata, screenToColumnS);
                }
            }
            if (valueOnes == null || "".equals(valueOnes)){
                valueOne = 0;
            }else {
                valueOne = Double.parseDouble(valueOnes);
            }
            pieSeriesMap.setName(xdata);
            pieSeriesMap.setValue(valueOne);
            value.add(pieSeriesMap);
        }

        series.setName(pieConfigInfo.getSeries().getColumnName());
        series.setValue(value);
        serieses.add(series);

        chartsDataInfo.setSerieses(serieses);
        }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, chartsDataInfo);
    }


}
