/**
 * 将请求返回的图表展示数据解析为前台展示用的config
 */
import moment from 'moment'
import STATISTICS_OPTION from '../components/chartDesigner/sections/statisticsOption.json'

export default function(viewType, data, chartConfig) {
    try {
        let o;
        switch(viewType) {
            case 'bar': {
                o = barOption(data, chartConfig);
                break;
            }
            case 'pie': {
                o = pieOption(data, chartConfig);
                break;
            }
            case 'line': {
                o = lineOption(data, chartConfig);
                break;
            }
            case 'scatter': {
                o = scatterOption(data, chartConfig);
                break;
            }
            case 'aggregateTable': {
                o = aggregateTableOption(data, chartConfig);
                break;
            }case 'dataView' : {
                o = dataViewOption(data, chartConfig);
                break;
            }
            default:{
                o = {};
                break;
            }
        }
        return o;
    }catch(e) {
        console.error(e);
    }
}

function barOption(data, barConfig) {
    let xTitle = barConfig.xAxis?`${barConfig.xAxis.column.label}${barConfig.xAxis.granularity.value?'('+barConfig.xAxis.granularity.label+')':''}`:null
    let yTitle = barConfig.yAxis?`${barConfig.yAxis.column.label}${barConfig.yAxis.gauge.value?'('+barConfig.yAxis.gauge.label+')':''}`:null

    let option = {
        tooltip : {
            trigger: "axis",
            axisPointer: {
                type: "cross",
                label: {
                    backgroundColor: "#6a7985"
                }
            }
        },
        legend: {
            show: true
        },
        grid: {
            left: '10%',
            right: '10%',
            top: 60,
            bottom: 60,
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: data.xAxis,
            name: xTitle || '横轴',
        }],
        yAxis: [{
            name: yTitle || '纵轴',
            type: 'value'
        }],
        series: data.serieses.map(s => {
            return {
                name: s.name,
                type: 'bar',
                data: s.value,
                // stack: s.stack
            }
        }) 
    }
    
    return option;
}

function pieOption(data, pieConfig) {
    let columnName = pieConfig.xAxis.column.label + (pieConfig.xAxis.granularity.value ? '('+pieConfig.xAxis.granularity.label+')' : '');
                    
    let option = {
        tooltip : {
            trigger: 'item',
            formatter: "{a} <br/>{b} : {c} ({d}%)"
        },
        legend: {
            data: data.xAxis
        },
        grid: {
            left: '10%',
            right: '10%',
            top: 60,
            bottom: 60,
            containLabel: true
        },
        series : [
            {
                name: columnName,
                type: 'pie',
                // radius : '55%',
                // center: ['50%', '60%'],
                data: (data.serieses || [])[0].value,
                itemStyle: {
                    emphasis: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };

    return option;
}

function lineOption(data, lineConfig) {
    let xTitle = lineConfig.xAxis?`${lineConfig.xAxis.column.label}${lineConfig.xAxis.granularity.value?'('+lineConfig.xAxis.granularity.label+')':''}`:null
    let yTitle = lineConfig.yAxis?`${lineConfig.yAxis.column.label}${lineConfig.yAxis.gauge.value?'('+lineConfig.yAxis.gauge.label+')':''}`:null
    
    let option = {
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross'
            }
        },
        legend: {
            show: true
        },
        xAxis:  {
            name: xTitle || '横轴',
            type: 'time'
        },
        yAxis: {
            name: yTitle || '纵轴',
            type: 'value'
        },
        
        series: (data.serieses || []).map(s => {
            return {
                name: s.name,
                type: 'line',
                data: s.mdata.map(m => {
                    return [m.date, m.value]
                })
            }
        })
    };

    return option;
}

function scatterOption(data, scatterConfig) {
    let xTitle = scatterConfig.xAxis?`${scatterConfig.xAxis.column.label}${scatterConfig.xAxis.granularity.value?'('+scatterConfig.xAxis.granularity.label+')':''}`:null
    let yTitle = scatterConfig.yAxis?`${scatterConfig.yAxis.column.label}${scatterConfig.yAxis.gauge.value?'('+scatterConfig.yAxis.gauge.label+')':''}`:null
    
    let option = {
        tooltip : {
            showDelay : 0,
            axisPointer:{
                show: true,
                type : 'cross',
                lineStyle: {
                    type : 'dashed',
                    width : 1
                }
            }
        },
        legend: {
            show: true
        },
        xAxis : [
            {
                type : 'value',
                name: xTitle || '横轴',
                scale:true,
                splitLine: {
                    show: false
                }
            }
        ],
        yAxis : [
            {
                type : 'value',
                name: yTitle || '纵轴',
                scale:true,
                splitLine: {
                    show: false
                }
            }
        ],
        series : (data.serieses || []).map(s => {
            return {
                name: s.name,
                type: 'scatter',
                data: s.mdata.map(m => {
                    return [m.date, m.value]
                })
            }
        })
    };

    return option;
}

function aggregateTableOption( data, aggregateTableConfig) {
    const resData = data.valueList;
    const { targetColumn, statistics } = aggregateTableConfig;
    
    let stypes = STATISTICS_OPTION.filter(o => statistics.indexOf(o.value) !== -1);

    let column = {
        title: '分析目标',
        dataIndex: 'targetColumn'
    };
    let targetColumnData = { targetColumn: targetColumn.label };
    let columns = [column];
    let dataSource = [targetColumnData]

    if(aggregateTableConfig.groupBy && aggregateTableConfig.groupBy.length > 0) {
        columns = columns.concat(aggregateTableConfig.groupBy.map(g => {
            return {
                title: g.label,
                dataIndex: g.key
            }
        })).concat(stypes.map(st => {
            return {
                title: st.label,
                dataIndex: st.value
            }
        }));
        dataSource = resData.map(d => {
            let obj = {};
            stypes.map(st => obj[st.value] = d[st.value.toUpperCase()]);
            aggregateTableConfig.groupBy.map(g => obj[g.key] = d[g.key])
            return { ...targetColumnData, ...obj };
        });
    }else {
        columns = columns.concat(stypes.map(st => {
            dataSource = dataSource.map(d => {
                d[st.value] = resData[st.value.toUpperCase()]
                return d
            });
            return {
                title: st.label,
                dataIndex: st.value
            }
        }));
    }

    let option = {
        columns: columns.map(c => {
            let _c = {
                ...c, width: 200
            };
            if(_c.dataIndex === 'percent') {
                return { ..._c, render: (value, record, index) => {
                    return ((+value*100).toFixed(2)) + '%'}
                };
            }else {
                return _c;
            }
        }),
        dataSource: dataSource.map((d, i) => {
            return { ...d, key: i}
        })
    };

    return option;
}

function dataViewOption(data, dataViewConfig) {
    const resData = data.valueList;

    let columns = dataViewConfig.viewColumns || [];
    let dataSource = resData || [];

    console.log(columns);
    let option = {
        columns: columns.map(c => ({
            title: c.label,
            dataIndex: c.name,
            width: 200,
            render: c.type === 'time' ? (v, r, i) => moment(v).format('YYYY-MM-DD') : void(0)
        })),
        dataSource: dataSource.map((d, i) => {
            return { ...d, key: i}
        })
    };

    return option;
}