<template>
    <el-dialog
        v-dialogDrag
        v-dialogLoading="dialogLoading"
        :title="title"
        :visible.sync="dialogShow"
        width="100%"
        :before-close="doClose"
        :close-on-click-modal="false"
        :modal="false"
        fullscreen
    >
        <div :id="runPlanId" v-loading="loading" />
    </el-dialog>
</template>

<script>
    import { mapGetters } from 'vuex';
    import { getPublishMapInfo } from '@/api/jmap/map';
    import { timeFormat } from '@/utils/date';
    import echarts from 'echarts';
    import {toTimeStamp, formatDuring} from '@/utils/date';

    // 运行图预览
    export default {
        name: 'RunPlanView',
        props: {
            group: {
                type: String,
                required: true
            }
        },
        data() {
            return {
                dialogShow: false,
                loading: true,
                runPlanId: 'run-plan-view',
                myChart: null,
                PlanConvert: {},
                series: [],
                option: {
                    title: {
                        text: '',
                        left: 'center'
                    },
                    grid: {
                        top: '30px',
                        left: '120px',
                        right: '40px',
                        bottom: '80px',
                        containLabel: true,
                        backgroundColor: 'floralwhite'
                    },
                    toolbox: {
                        // right: '20px',
                        // feature: {
                        //     dataZoom: {
                        //         yAxisIndex: 'none'
                        //     },
                        //     restore: {},
                        //     saveAsImage: {}
                        // }
                    },
                    tooltip: {
                        axisPointer: {
                            trigger: 'item',
                            type: 'cross'
                        },
                        formatter: this.axisTooltip,
                        borderWidth: 1
                    },
                    xAxis: [
                        {
                            type: 'category',
                            boundaryGap: false,
                            data: [],
                            axisLine: {
                                onZero: false,
                                lineStyle: {
                                    width: 2,
                                    color: '#d14a61'
                                }
                            },
                            axisLabel: {
                                formatter: this.xAxisLableFormat,
                                textStyle: {
                                    color: '#333'
                                }
                            },
                            axisPointer: {
                                snap: true,
                                label: {
                                    formatter: this.xAxisPointFormat,
                                    backgroundColor: 'rgb(255,0,0,0.5)',
                                    color: 'white'
                                }
                            }
                        }
                    ],
                    yAxis: {
                        type: 'value',
                        splitLine: {
                            show: false
                        },
                        axisTick: {
                            show: false
                        },
                        axisLine: {
                            onZero: false,
                            lineStyle: {
                                width: 2,
                                color: '#d14a61'
                            }
                        },
                        axisLabel: {
                            interval: 'auto',
                            formatter: this.yAxisLableFormat
                        },
                        axisPointer: {
                            xAxisIndex: 'all',
                            label: {
                                formatter: this.yAxisPointFormat,
                                backgroundColor: 'rgb(0,100,0,0.5)',
                                color: 'white'
                            }
                        },
                        min: 0,
                        max: 0
                    },
                    // graphic: {
                    // 	type: 'line',
                    // 	progressive: true
                    // },
                    series: [],
                    dataZoom: [
                        {
                            type: 'inside'
                        },
                        {
                            fiterMode: 'filter',
                            handleIcon: 'M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
                            handleSize: '80%',
                            handleStyle: {
                                color: '#fff',
                                shadowBlur: 3,
                                shadowColor: 'rgba(0, 0, 0, 0.6)',
                                shadowOffsetX: 2,
                                shadowOffsetY: 2
                            },
                            bottom: '25px'
                        }
                    ]
                },
                absoluteTime: 2 * 3600,
                indexKmRangeMap: {},
                runPlanData: {},
                dialogLoading: false,
                initialPlanData: []
            };
        },
        computed: {
            ...mapGetters('runPlan', [
                'stations'
            ]),
            title() {
                return this.$t('display.runPlan.previewRunDiagram');
            }
        },
        watch: {
            '$store.state.runPlan.planLoadedCount': async function () {
                try {
                    await this.loadChartPage();
                    if (this.dialogShow) {
                        await this.loadInitData(this.series);
                    }
                } catch (e) {
                    console.error(e);
                } finally {
                    this.loading = false;
                }
            },
            '$store.state.runPlan.planUpdateCount': function () {
                this.updateRunPlanData(this.$store.state.runPlan.updateData);
            },
            '$store.state.app.windowSizeCount': function() {
                this.reSize({ width: this.$store.state.app.width, height: this.$store.state.app.height - 55 });
            }
        },
        mounted() {
            getPublishMapInfo(this.$route.query.mapId).then(res=>{
                this.PlanConvert = this.$theme.loadPlanConvert(res.data.lineCode);
                this.initialPlanData = this.$store.state.runPlan.planData;
                this.loadChartPage();
            });
        },
        beforeDestroy() {
            if (this.myChart && this.myChart.isDisposed) {
                this.myChart.dispose();
                this.myChart = null;
            }
        },
        methods: {
            async  doShow() {
                try {
                    this.dialogLoading = true;
                    this.dialogShow = true;
                    this.loadInitData(this.series);
                } catch (e) {
                    console.error(e);
                } finally {
                    this.dialogLoading = false;
                }
            },
            async doClose() {
                this.dialogShow = false;
            },
            async loadChartPage() {
                const stations = this.$store.state.runPlan.stations;
                const planData = this.$store.state.runPlan.planData;
                this.series = [];
                this.kmRangeCoordMap = this.PlanConvert.convertStationsToMap(stations);
                this.pushModels(this.series, [this.PlanConvert.initializeYaxis(stations)]);
                this.pushModels(this.series, this.PlanConvert.convertDataToModels(planData, stations, this.kmRangeCoordMap, { width: 1, color: '#000' }));
            },
            async loadInitData(series) {
                this.myChart && this.myChart.showLoading();
                await this.xAxisInit();
                await this.yAxisInit();
                await this.loadInitChart(series);
                this.myChart && this.myChart.hideLoading();
            },
            loadInitChart(series) {
                return new Promise((resolve, reject) => {
                    try {
                        if (this.myChart && this.myChart.isDisposed) {
                            this.myChart.clear();
                        }
                        let startValue = 3600 + this.PlanConvert.TranslationTime;
                        const offsetTime = 3600;
                        const initTime = toTimeStamp(formatDuring(this.$store.state.training.initTime));
                        startValue = initTime - this.PlanConvert.TranslationTime;
                        this.option.dataZoom[0].startValue = this.option.dataZoom[1].startValue = startValue - offsetTime;
                        this.option.dataZoom[0].endValue = this.option.dataZoom[1].endValue = startValue + offsetTime;
                        this.option.series = series;
                        this.myChart = echarts.init(document.getElementById(this.runPlanId));
                        if (this.myChart) {
                            this.myChart.setOption(this.option);
                            this.reSize({ width: document.documentElement.clientWidth -10, height: document.documentElement.clientHeight - 55 });
                            this.myChart.on('click', this.mouseClick);
                        }
                        resolve(true);
                    } catch (error) {
                        reject(error);
                    }
                });
            },
            updateRunPlanData(data) {
                const stations = this.$store.state.runPlan.stations;
                const planData = this.$store.state.runPlan.planData;
                const initialPlanData = this.$store.state.runPlan.initialPlanData;
                if (data[0] && initialPlanData[data[0].serviceNumber]) {
                    Object.keys(initialPlanData[data[0].serviceNumber].trainMap).forEach(item => {
                        if (initialPlanData[data[0].serviceNumber].trainMap[item+''].tripNumber == data[0].tripNumber) {
                            data[0].directionCode =  initialPlanData[data[0].serviceNumber].trainMap[item + ''].directionCode;
                        }
                    });
                }
                if (data[0]) {
                    data[0].secondTime = data[0].second;
                }
                this.series = this.PlanConvert.updateDataToModels(data, stations, this.kmRangeCoordMap,
                    planData, this.series, { color: '#FF00DE', width: 0.5 }
                );
                this.myChart && this.myChart.setOption({ series: this.series });
            },
            pushModels(series, models) {
                if (models && models.length) {
                    models.forEach(elem => {
                        if (elem) {
                            series.push(elem);
                        }
                    });
                }

                return series;
            },
            popModels(series, models) {
                if (models && models.length) {
                    models.forEach(elem => {
                        const index = series.indexOf(elem);
                        if (index >= 0) {
                            series.split(index, 1);
                        }
                    });
                }

                return series;
            },
            xAxisPointFormat(params) {
                return timeFormat(params.value);
            },
            yAxisPointFormat(params) {
                return this.PlanConvert.computedFormatYAxis(this.stations, params);
            },
            xAxisLableFormat(value, index) {
                if (value % 60 === 0) {
                    return timeFormat(value);
                }
            },
            yAxisLableFormat(value, index) {
                return '';
            },
            xAxisInit() {
                const list = [];
                for (var time = this.PlanConvert.TranslationTime; time < 3600 * 24 + this.PlanConvert.TranslationTime; time++) {
                    list.push(time);
                }
                this.option.xAxis[0].data = list;
            },
            yAxisInit() {
                if (Object.keys(this.PlanConvert).length) {
                    this.option.yAxis.min = this.PlanConvert.computedYaxisMinValue(this.stations);
                    this.option.yAxis.max = this.PlanConvert.computedYaxisMaxValue(this.stations);
                }
            },
            axisTooltip(param) {
                const station = this.stations[Math.floor((param.data[1] - this.PlanConvert.EdgeHeight) / this.PlanConvert.CoordMultiple)] || { name: '', kmRange: '' };
                return [
                    `Point Data <hr size=1 style="margin: 3px 0">`,
                    `${this.$t('display.runPlan.stationName')}: ${station.name}<br>`,
                    `${this.$t('display.runPlan.stationMark')}: ${station.kmRange} km <br>`,
                    `${this.$t('display.runPlan.arrivalTime')}: ${timeFormat(param.data[0] + this.PlanConvert.TranslationTime)} (${param.data[0]})<br>`
                ].join('');
            },
            settingExac(data) {
                this.absoluteTime = Math.abs(parseInt(data.endValue) - parseInt(data.startValue)) / 1000;
                this.myChart && this.myChart.setOption({
                    xAxis: this.option.xAxis,
                    yAxis: this.option.yAxis
                });

                this.myChart && this.myChart.dispatchAction({
                    type: 'dataZoom',
                    dataZoomIndex: [0, 1],
                    startValue: parseInt(data.startValue / 1000),
                    endValue: parseInt(data.endValue / 1000)
                });
            },
            run(start) {
                this.myChart && this.myChart.dispatchAction({
                    type: 'dataZoom',
                    dataZoomIndex: [0, 1],
                    startValue: parseInt(start - this.absoluteTime / 2),
                    endValue: parseInt(start + this.absoluteTime / 2)
                });
                this.loadInitData(this.series);
            },
            reSize(opt) {
                if (this.myChart) {
                    this.myChart.resize({ width: opt.width, height: opt.height, silent: false });
                }
            }
        }
    };
</script>
<style scoped rel="stylesheet/scss" lang="scss">
    /deep/ {
        .el-dialog__body {
            padding: 0px !important;
            background-color: floralwhite !important;
        }
    }
</style>
