/**
 *  @extends startChart
 *  @abstract title (柱状,饼状)单条数据渲染时的标题
 *  @abstract type 参数（可选） 默认基础折线图
 *  @abstract xname X轴的名称数组
 *  @abstract yname Y轴的单位（多条柱状图）
 *  @emits series 数据 有两种写法
 *  @abstract series多条写法 [{ name: 'name', data: [1, 1, 1, 1, 1] }]
 *  @abstract series单条写法 [1, 1, 1, 1, 1] 
 */

// 单条数据
let data = { type: 'line', xname: [], series: [{ name: 'name', data: [1, 1, 1, 1, 1] }], title: '', yname: ['套', '㎡'] }
// 多条数据
let datas = { type: 'lines', xname: [], series: [{ name: '', data: [] }], title: '' }
function numFormat(num: string | number) {
    num = num == undefined ? 0 : num;
    let c = (num.toString().indexOf('.') !== -1) ? num.toLocaleString() : num.toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
    return c;
}

// 转为万元
function formatNumber(num: string | number) {
    num = Number(num);
    if (num == 0) {
        return num + "";
    } else {
        if ((num / 10000).toFixed(2) == "0") {
            //小于100的保留2位
            return (num / 100).toFixed(4)
        } else {
            // parseFloat() 去掉后面不用的0，如50.00
            //大于100的保留2位
            return parseFloat((num / 10000).toFixed(2))
        }
    }
}


export type DomeCharts = DomeChart

interface DomeChart {
    title?: string,
    type?: string,
    xname?: Array<string>
    yname?: Array<any>
    series?: Array<any>
}

export function startChart(chartdata: DomeChart) {
    // 判断type渲染数据
    let opt = chart.ifType(chartdata)
    return opt
}

const chart = {
    // 判断type渲染数据
    ifType(chartdata: DomeChart) {
        chartdata.type = !chartdata.type ? 'line' : chartdata.type
        // 折线图
        if (chartdata.type == 'line') return this.lineoption(chartdata)
        if (chartdata.type == 'lines') return this.linesoption(chartdata)

        // 柱状图
        if (chartdata.type == 'bar') return this.baroption(chartdata)
        if (chartdata.type == 'bars') return this.barsoption(chartdata)

        // 饼状图
        if (chartdata.type == 'pie') return this.pieoption(chartdata)
        if (chartdata.type == 'pies') return this.piesoption(chartdata)
        if (chartdata.type == 'piemore') return this.piemoreoption(chartdata)
    },
    // 饼状图其他方式渲染
    piemoreoption(data: object | any) {
        let _data: any = []
        data.series.forEach((res: any) => {
            _data.push({ name: res.name, value: res.data })
        });
        // 默认左侧
        let _legend: any = { orient: 'vertical', left: 'left' }
        if (data.float == 'right') {
            _legend = { orient: 'vertical', top: "50", left: 'right' }
        }
        if (data.float == 'topcenter') {
            _legend = { top: "0", orient: 'horizontal' }
        }
        if (data.float == 'bottomcenter') {
            _legend = { bottom: "0", orient: 'horizontal' }
        }

        let _label: any = { show: false }
        if (data.label == '0') {
            _label = { show: true, formatter: '{b}({d}%)' }
        }
        if (data.label == '1') {
            _label = { show: true, position: "inside", formatter: '{b}({d}%)' }

        }
        let _labelLine: any = {}

        if (data.labelLine == '0') {
            _labelLine = { show: false }
        }
        _legend = data.legend != undefined ? data.legend : _legend

        let _tooltip = data.tooltip == undefined ? { tooltip: { trigger: 'item' } } : { tooltip: data.tooltip };

        return {
            ..._tooltip,
            legend: _legend,
            series: [{ name: data.title, labelLine: _labelLine, label: _label, type: 'pie', radius: ['30%', '60%'], data: _data, center: data.center ? data.center : ['50%', '50%'] }]
        }
    },
    // 饼状图渲染方法-多条
    piesoption(data: object | any) {
        let _data: any = []
        data.series.forEach((res: any) => {
            _data.push({ name: res.name, value: res.data })
        });
        return {
            tooltip: { trigger: 'item' },
            legend: { left: data.bottom, y: 'bottom', x: 'center' },
            series: [{
                label: data.label != undefined ? { show: true, position: "inside", formatter: '{d}%' } : null,
                labelLine: data.label != undefined ? { length: 5, length2: 4, smooth: true } : null,
                name: data.title, type: 'pie', radius: ['40%', '70%'], center: ['50%', '40%'], itemStyle: { borderRadius: 10, borderColor: '#fff', borderWidth: 2 }, data: _data
            }]
        }
    },
    // 饼状图渲染方法-单条
    pieoption(data: object | any) {
        let _data: any = []
        data.series.forEach((res: any) => {
            _data.push({ name: res.name, value: res.data })
        });
        return {
            tooltip: { trigger: 'item' },
            legend: { orient: 'vertical', left: 'left' },
            series: [{ name: data.title, type: 'pie', label: { show: false }, data: _data }]
        }
    },
    // 柱状图渲染方法-多条  max-Y轴最大值
    barsoption(data: object | any) {
        let yname: any = [], //Y轴的名字
            lenname: Array<string> = [], //各个字段名字
            _data: Array<object> = []; //数据
        if (data.yAxis == undefined) {
            data.yname.forEach((res: any) => {
                yname.push({ type: 'value', axisLabel: { formatter: `{value} ${res}` }, max: data.max })
            })
        } else {
            yname = data.yAxis
        }
        data.series.forEach((res: any, index: number) => {
            lenname.push(res.name)
            _data.push({
                name: res.name,
                type: res.type == undefined ? 'bar' : res.type,
                yAxisIndex: index,
                tooltip: { valueFormatter: function (value: any) { let name: any; if (data.iswy) { name = numFormat(formatNumber(value)) + '万' + data.yname[index]; } else { name = (data.isd ? numFormat(value) : value) + data.yname[index]; } return name; } },
                data: res.data
            })
        })
        let colors = data.color == undefined ? {} : { color: data.color }
        return {
            ...colors,
            tooltip: { trigger: 'axis', axisPointer: { type: 'cross', crossStyle: { color: '#999' } } },
            grid: { left: '3%', right: '3%', bottom: '2%', containLabel: true },
            legend: { data: lenname },
            xAxis: [{ type: 'category', data: data.xname, axisPointer: { type: 'shadow' } }],
            yAxis: yname,
            series: _data
        }
    },
    // 柱状图渲染方法-单条
    baroption(data: Object | any) {
        return {
            tooltip: { trigger: 'axis', axisPointer: { type: 'shadow' } },
            grid: { left: '0%', right: '3%', bottom: '2%', containLabel: true },
            xAxis: [{ type: 'category', data: data.xname, axisTick: { alignWithLabel: true } }],
            yAxis: [{ type: 'value' }],
            series: [{ name: data.title, type: 'bar', data: data.series, tooltip: { valueFormatter: function (value: any) { return value + 'm²'; } }, }]
        }
    },
    // 折线图渲染方法-多条
    linesoption(data: Object | any) {
        let _data: any = [],
            yname: any = [];
        data.series.forEach((res: any) => {
            _data.push({ name: res.name, type: 'line', data: res.data })
        });
        data.yname.forEach((res: any) => {
            yname.push({ type: 'value', axisLabel: { formatter: `{value}` } })
        })
        let _legend: any = {};

        return {
            legend: _legend,
            tooltip: {
                trigger: 'axis',
                formatter: function (params: any) {
                    var relVal = params[0].name
                    for (var i = 0, l = params.length; i < l; i++) {
                        if (data.yname[0] == '万㎡') {
                            let num = formatNumber(params[i].value)
                            relVal += '<br/>' + params[i].marker + params[i].seriesName + '：' + numFormat(num) + data.yname[0]
                        } else {
                            relVal += '<br/>' + params[i].marker + params[i].seriesName + '：' + numFormat(params[i].value) + data.yname[0]
                        }

                    }
                    return relVal
                }
            },
            grid: { left: '0%', right: '3%', bottom: '0%', containLabel: true },
            xAxis: { type: 'category', boundaryGap: false, data: data.xname },
            yAxis: yname,
            series: _data
        }
    },
    // 折线图渲染方法-单条
    lineoption(data: Object | any) {
        // label: { show: true, formatter: function (params: any) { return `${params.value} ${data.yname}` } }
        let _data = [{ type: data.type, data: data.series }]
        let yname = {}
        if (data.yname != undefined) {
            yname = { type: 'value', axisLabel: { formatter: `{value} ${data.yname}` } }
        }
        return {
            xAxis: { type: 'category', data: data.xname },
            grid: { left: '6%', right: '3%', bottom: '6%' },
            tooltip: {
                trigger: 'axis',
                formatter: function (params) {
                    var sum = params[0].value.toString().length;
                    var relVal = ''
                    if(sum < 5){
                        relVal = params[0].name+ ' ' + params[0].value + ' ' +  data.yname
                    }else {
                        relVal = params[0].name+ ' ' + numFormat(params[0].value) + ' ' +  data.yname
                    }
                    if(data.yname == 'm²'){
                        relVal = params[0].name+ ' ' + numFormat(formatNumber(params[0].value)) + '万' +  data.yname
                    }
                    // params 是一个数组，数组中包含每个系列的数据信息
                    return relVal;
                }

            },
            yAxis: yname,
            series: _data
        }
    }
}

// { valueFormatter: function (value: any) { let name: any; if (data.iswy) { name = numFormat(formatNumber(value)) + '万' + data.yname[index]; } else { name = (data.isd ? numFormat(value) : value) + data.yname[index]; } return name; } },