<template>
  <div class="app-container">
    <ContainerLayout :options="view.layout" ref="layout" class="body-content" @resize="resize">
      <div slot="north">
        <div class="title" v-if="view.showTitle" ref="title">{{$_i18n(view.title)||"未设置标题"}}</div>
        <CustomToolbar v-show="view.showToolbar" ref="toolbar" :fid="fid" @click="$page_toolbar_clickHandler"
                       @ready="$_page_toolbar_initComplete" @resize="resize" @completed="completed"
                       :queryParams="queryParams" ></CustomToolbar>
      </div>
      <div ref="chart" class="chart" :style="style"></div>
      <!--使用vue动态组件加载适配-->
      <component v-if="view.layout.south && view.layout.south.component!=null && view.layout.south.visible"
                 slot="south" ref="south" :is="view.layout.south.component" :params="view.layout.south.params">
      </component>
      <!--使用vue动态组件加载适配-->
      <component v-if="view.layout.east && view.layout.east.component!=null && view.layout.east.visible"
                 slot="east" ref="east" :is="view.layout.east.component" :params="view.layout.east.params">
      </component>
    </ContainerLayout>
    <Dialog refs="dialog" :title="dialog.title" :visible.sync="dialog.visible" :destroy-on-close="dialog.destroyOnClose"
            :width="dialog.width" :height="dialog.height" :close-on-click-modal="dialog.modalClose"
            :parentClass="view.parentClass" :custom-class="view.customClass"
            :before-close="handleDialogClose" :modal-append-to-body="false" :close-on-press-escape="false">
      <component v-if="dialog.visible" ref="south" :is="dialog.component" :params="dialog.params"></component>
      <span v-if="dialog.footer&&dialog.footer.visible" slot="footer" class="dialog-footer">
          <el-button @click="dialog.visible = false">取 消</el-button>
          <el-button type="primary" @click="dialog.visible = false">确 定</el-button>
        </span>
    </Dialog>
  </div>
</template>
<script>
    import resize from '../../utils/mixins/resize';
    import page from '../Common/page';
    import * as echarts from 'echarts'
    require('echarts/theme/macarons');
    export default {
        name: "EChartView",
        mixins: [resize, page],//监听外部框架的大小改变事件
        props: {
            width: {type: String, default: "100%"},
            height: {type: String, default: "100%"}
        },
        data() {
            return {
                chart: null,
                view: {//布局控制配置
                    layout: {
                        north: {visible: true, resize: false, size: "auto"},
                        south: {visible: false, size: "50%", params: {showTitle: true}},
                    }, chart: {
                        title: {text: "", left: "center"},
                        color: ['#4fbaff', '#00d989', '#6468ff', '#9b64ff', '#a8ee00', '#ffbcbd', '#efff08', '#fac400', '#ffa636', '#c1c1c1', '#949494', '#ff79a8'],
                        //['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83',  '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
                        dataset: {},
                        tooltip: {},
                        toolbox: {
                            show: true,
                            right:20,
                            feature: {
                                restore: {show: false},
                                saveAsImage: {show: true}
                            }
                        },
                        grid:{containLabel: true},
                        xAxis: {
                            type: "category",
                            splitLine: {show: false}
                        },
                        yAxis: {
                            type: "value"
                        },
                        legend: {enabled: true, top: 'bottom'},
                        series: {
                            type: "line"
                            , pie: {
                                xAxis: {show: false}, yAxis: {show: false},
                                animationEasing:'cubicInOut',animationDuration:1000,
                                tooltip: {trigger: 'item', formatter: "{a}<br/>{b}:{c} ({d}%)"},
                                itemStyle: {normal: {label: {show: true, formatter: "{b}:{c} ({d}%)"}}}
                            } //个性属性
                            , bar: {
                                xAxis: {show: true}, yAxis: {show: true},
                                barMaxWidth: "30%",
                                itemStyle: {normal: {label: {show: true}}}
                            } //emphasis: {barBorderRadius: 30},normal:{barBorderRadius:[5,5,0,0]}}//支持圆角
                            , line: {xAxis: {show: true}, yAxis: {show: true}}
                            , lineArea: {type: "line", xAxis: {show: true}, yAxis: {show: true},
                                areaStyle: {}}
                            , boardStar: {
                                grid: {left: '10%', bottom: '10%'},
                                xAxis: {
                                    axisLabel: {color: "white", rotate: 0},
                                    axisLine: {lineStyle: {color: '#76B6D7'}}
                                },
                                yAxis: {axisLabel: {color: "white"}, axisLine: {lineStyle: {color: '#76B6D7'}}},
                                legend: {textStyle: {color: "white"}}
                            }
                        }
                    }
                }
            }
        },
      async created() {
            this.$_page_getRouter();
            await this.initFormConfig();
        }, mounted() {
            this.$refs.layout.updateLayout(this.view.layout);
            this.initChart();
        },
        computed: {
            style() {
                return {width: this.width, height: this.height};
            }
        },
        beforeDestroy() {
            if (!this.chart) {
                return
            }
            this.chart.dispose()
            this.chart = null
        },
        methods: {
            initChart() {
                this.chart = echarts.init(this.$refs.chart, 'macarons')
            },
            customQuery(params) {
                this.$core.extend(this.queryParams, params);//解决搜索时，不会联动分页控件的问题
                let options = this.$core.extend({}, this.queryParams);
                this.clearData();
                if (options.jid !== this.jid) {
                    this.jid = options.jid;
                }
                delete options.jid;
                if(options.title){
                    this.view.chart.title.text=options.title;
                    delete options.title;
                }
                if (this.jid) {
                    params.loading = true;
                    this.$http(this.$store.state.api.json.loadData + this.jid, {data: options}).then((res) => {
                        params.loading = false;
                        this.$nextTick(() => {
                            //这里处理数据规则成echart格式
                            // let setting=Object.assign({series:[]},this.view.chart,options);
                            let setting=this.$core.merge(true,{series:[],legend:{data:[]}},this.view.chart,options);
                            setting= this.dataProcessForShow(res.data, setting);
                            this.chart.setOption(setting);
                        });
                    })
                }
            },
          updatePageParams(pageParams) {
                if (pageParams.reportName) {
                    this.view.title = pageParams.reportName;
                    delete pageParams.reportName;
                }
                if (pageParams.jid) {
                    this.jid = pageParams.jid; //拦截无穷递归
                }
                if(pageParams.title){
                    this.view.chart.title.text=pageParams.title;
                }
            }, resize() {
                if(this.chart&&this.chart.resize)
                    this.chart.resize();
            }, completed() {
                //this.$core.debug().log("收到工具栏加载完成事件");
            }, clearData() {
                if(this.chart)
                    this.chart.clear();
            }, dataProcessForShow(data, setting) {
                if (data.length > 0) {
                    //有全局参数控制图表类型，要求数据中不含类型
                    if (this.queryParams.type && !data[0].type) {
                        for (let name in data[0]) {
                            if (name != "name" && name != "type") {
                                let series = {type: this.queryParams.type};
                                this.$core.merge(true, setting, setting.series[this.queryParams.type]);//载入配置到全局配置
                                series = this.$core.merge(series, setting.series[this.queryParams.type]);//载入配置到当前数据
                                setting.series.push(series);
                            }
                        }
                    }
                    if (data[0].type) {
                        //重新组织数据
//           options= merge({series:[]},defaults,options);
                        for (let i = 0; i < data.length; i++) {
                            if (data[i].series != null) {
                                //支持
                                let index = Array.FindDataIndex(setting.series, {name: data[i].series});
                                if (index == -1) {//如果存在多条数据
                                    index = setting.series.length;
                                    let series = {
                                        name: data[i]["series"],
                                        type: data[i]["type"],
                                        stack: data[i]["stack"],
                                        data: []
                                    };
                                    this.$core.merge(true, setting, setting.series[data[i]["type"]]);//载入配置到全局配置
                                    series = this.$core.merge(series, setting.series[data[i]["type"]]);//载入配置到当前数据
                                    if (data[i]["smooth"])
                                        series.smooth = true;
                                    setting.series.push(series);
                                    if(data[i].type!="pie")
                                      setting.legend.data.push(data[i].series);
                                }
                                if (data[i].name) {//命名模式
                                    setting.series[index].data.push(data[i]);
                                    if (data[i].type == "pie") {
                                        setting.legend.data.push(data[i].name);
                                        //roseType:'radius', 根据数据大小显示饼图，有时也不好看，后期考虑是否加入支持
                                    }
                                } else { //时间模式
                                    if ((data[i].x + "").length == 13 && new Date(data[i].x) != "Invalid Date")
                                        data[i].x = new Date(data[i].x);
                                    setting.series[index].data.push([data[i].x, data[i].y, data[i].z]);
                                }
                            }
                        }
                        // return ;
                    }
                    if (typeof (data[0].x) == "object") {
                        setting.xAxis.type = "time";
                        setting.xAxis.axisLabel = {
                            rotate: data[0].rotate || 0, formatter: function (val) {
                                return new Date(val).format(data[0].format || "yyyy-MM-dd HH:mm:ss");
                            }
                        };
                        setting.title.subtext = "拖动可以缩放";
                        setting.dataZoom = [
                            {show: true,realtime: true,start: 0,end: 100,bottom:"25px"},
                            {type: 'inside',realtime: true,start: 0,end: 100}
                        ];
                        setting.toolbox.feature.restore=true;//仅在开发缩放模式下，才打开还原功能。
                    }
                    if (this.queryParams.type == "pie") {
                        setting.xAxis.show = false;
                        setting.yAxis.show = false;
                    }
                }
                if (data.length == 0) {
                    setting.xAxis.show = false;
                    setting.yAxis.show = false;
                    setting.title.subtext = "查无数据";
                } else {
                    if (setting.title.subtext == null)//洗掉因参数融合造成的副标题不会消失的问题
                        setting.title.subtext = null;
                }
                setting.dataset.source = data;
                this.$core.debug().log("图表实际绘制配置",setting);


                return setting;
            }
        }
    }
</script>

