<template>
    <div class="container" style="padding-bottom: 50px; width: 100%; height: 100%" v-loading="loading">
        <div style="display: flex; align-items: center; justify-content: space-between; width: 100%; height: 34vh; margin-bottom: 40px">
            <div style="width: 48%; height: 100%; margin-bottom: 2vh; position: relative">
                <i class="el-icon-refresh refresh" @click="getCharts('year')"></i>
                <div id="yearchart" style="width: 100%; height: 100%"></div>
            </div>
            <div style="width: 48%; height: 100%; position: relative">
                <i class="el-icon-refresh refresh" @click="getCharts('month')"></i>
                <div id="monthchart" style="width: 100%; height: 100%"></div>
            </div>
        </div>

        <div
            style="
                width: 100%;
                height: auto;
                margin-bottom: 20px;
                background-color: #f4f4f5;
                padding: 10px;
                font-size: 12px;
                color: #909399;
            "
        >
            {{ $t('journalArticleCount.info') }} : {{ $t('journalArticleCount.dataTitle') }} /
            {{ $t('journalArticleCount.transferQuantity') }}
        </div>
        <div style="width: 100%; height: auto; margin-bottom: 20px">
            <jAtableY type="year" ref="yearTableData"></jAtableY>
        </div>

        <div
            style="
                width: 100%;
                height: auto;
                margin-top: 50px;
                margin-bottom: 20px;
                background-color: #f4f4f5;
                padding: 10px;
                font-size: 12px;
                color: #909399;
            "
        >
            {{ $t('journalArticleCount.info') }} : {{ $t('journalArticleCount.dataTitle') }} /
            {{ $t('journalArticleCount.transferQuantity') }}
        </div>
        <div style="width: 100%; height: auto; margin-bottom: 20px !important">
            <jAtableM type="month" ref="monthTableData"></jAtableM>
        </div>
    </div>
</template>

<script>
const jAtableY = () => import('@/components/common/journalArticleTable');
const jAtableM = () => import('@/components/common/journalArticleTable');

export default {
    data() {
        return {
            loading: false,
            yearData: {},
            monthData: {},
            JournalYearData: [],
            JournalMonthData: [],
            user_id: localStorage.getItem('U_id'),
            urlList: {
                year: 'api/Monitor/getArticleNumByYearForChief',
                month: 'api/Monitor/getArticleNumByMonthForChief',
                Journalyear: 'api/Monitor/getArticleNumByYearAndJournalForChief',
                Journalmonth: 'api/Monitor/getArticleNumByMonthAndJournalForChief'
            }
        };
    },
    components: {
        jAtableY,
        jAtableM
    },
    async created() {
        this.loading = true;
        // this.loading = this.$loading({
        //     lock: true,
        //     text: 'Loading...',
        //     spinner: 'el-icon-loading',
        //     background: 'rgba(0, 0, 0, 0.7)'
        // });
        await this.getData('year');
        await this.getData('month');
        await this.getJournalData('year');
        await this.getJournalData('month');
        await this.getCharts('year');
        await this.getCharts('month');
        await this.getTableData();
        this.$forceUpdate();
    },
    async mounted() {},
    methods: {
        handleRefresh() {},
        async getEchartsData() {
            await this.getCharts('year');
            await this.getCharts('month');
            this.$forceUpdate();
        },
        async getCharts(type) {
            var optionsData = await this.getdata(type);

            const chartBox = await this.$echarts.init(document.getElementById(`${type}chart`));
            var option = {};
            option = {
                title: {
                    text: this.$t(`journalArticleCount.${type}Title`)
                },
                // tooltip: {
                //     trigger: 'axis',
                //     axisPointer: {
                //         type: 'cross',
                //         label: {
                //             backgroundColor: '#6a7985'
                //         }
                //     }
                // },

                tooltip: {
                    trigger: 'axis',
                    enterable:true,  //设置鼠标 是否可以进入浮框中
          confine:true,    //设置 浮框 限制在 图表的区域内
          extraCssText:'max-height:98%;overflow:scroll' , //设置最大高度，并添加滚动

                    // formatter函数动态修改tooltip样式
                    formatter: function (params) {
                        var that = this;
                   
                        if (params) {
                            var htmlStr = '';
                            // htmlStr += params[0].name.replace(/\-/g, '/') + '<br/>'; //x轴的名称

                            if (params[0].axisIndex == 0) {
                                htmlStr += '<div>';
                                htmlStr += `${params[0].name} `;
                                //圆点后面显示的文本
                                for (var i = 0; i < params.length; i++) {
                                    var param = params[i]; // 存一份item项
                                    console.log('param at line 404:', param);

                                    var value = param.value; //y轴值
                                    var color = param.color; //图例颜色
                                    var journalStr = ``;
                                    param.data.otherInfo.forEach((e) => {
                                        journalStr +=
                                            '<span style="margin-right:5px;display:inline-block;width:10px;height:10px;border-radius:5px;background-color:' +
                                            color +
                                            ';"></span>' +
                                            `<span>${e.key} : ${e.value}</span><br/>`;
                                    });

                                    htmlStr += `${param.seriesName}: ${value}`; //2023年

                                    htmlStr += `<p style='border-bottom:1px solid #b0b0b0;margin:5px 0;'></p>`;
                                    htmlStr += journalStr;
                                    htmlStr += '</div>';
                                }
                            }

                            return htmlStr;
                        } else {
                            return;
                        }
                    },
                    backgroundColor: '#fff',
                    borderWidth: 1,
                    borderColor: '#ccc',
                    padding: 10,
                    textStyle: {
                        color: '#000',
                        fontSize: 12,
                        align: 'left'
                    }
                },

                //   legend: {
                //     data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
                //   },
                toolbox: {
                    // feature: {
                    // //   dataZoom: {
                    // //     yAxisIndex: 'none'
                    // //   },
                    //   restore: {},
                    // }
                },
                label: {
                    formatter: '',

                    rich: {
                        b: {
                            color: '#4C5058',
                            fontSize: 12,
                            fontWeight: 'bold',
                            lineHeight: 10
                        }
                    }
                },
                dataZoom:
                    type == 'month'
                        ? [
                              {
                                  show: true,
                                  realtime: true,
                                  start: 1,
                                  end: 100,
                                  xAxisIndex: [0, 1]
                              },
                              {
                                  type: 'inside',
                                  realtime: true,
                                  start: 1,
                                  end: 100,
                                  xAxisIndex: [0, 1]
                              }
                          ]
                        : [],
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: type == 'month' ? '20%' : '4%',
                    containLabel: true
                },
                xAxis: [
                    {
                        type: 'category',
                        axisLabel: {},
                        // axisLabel:
                        //     type == 'year'
                        //         ? {}
                        //         : {
                        //               interval: 0,
                        //               rotate: 30
                        //           },
                        boundaryGap: false,
                        data: optionsData.xAxisData
                    }
                ],
                yAxis: [
                    {
                        type: 'value'
                    }
                ],
                series: [
                    {
                        name: this.$t(`journalArticleCount.dataTitle`),
                        type: 'line',
                        stack: 'Total',
                        areaStyle: {
                            opacity: 0.8,
                            color: this.$echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                {
                                    offset: 0,
                                    color: type == 'year' ? 'rgb(0, 221, 255)' : 'rgb(0, 102, 153)'
                                },
                                {
                                    offset: 1,
                                    color: type == 'month' ? 'rgb(77, 119, 255)' : 'rgb(1, 191, 236)'
                                }
                            ])
                        },
                        smooth: true,
                        emphasis: {
                            focus: 'series'
                        },
                        data: optionsData.seriesData
                    }
                ]
            };
            chartBox.clear();
            chartBox.setOption(option, true);
            // 根据页面大小自动响应图表大小
            window.addEventListener('resize', function () {
                chartBox.resize();
            });
            this.$forceUpdate();
        },
        async getData(type) {
            var url = '';
            if (type == 'month') {
                url = this.urlList.month;
            } else if (type == 'year') {
                url = this.urlList.year;
            }
            await this.$api
                .post(url, {
                    // user_id: this.user_id
                })
                .then((res) => {
                    var that = this;
                    if (res.code == 0) {
                        if (type == 'month') {
                            this.monthData = res.data.articles;
                        } else if (type == 'year') {
                            this.yearData = res.data.articles;
                        }
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 获取文章列表数据
        async getdata(type) {
            var data = {};
            var optionJournalData = [];
            var optionData = [];
            console.log('...this.JournalMonthData at line 308:', this.JournalMonthData);
            if (type == 'month') {
                optionJournalData = [...this.JournalMonthData];

                optionData = this.monthData;
            } else if (type == 'year') {
                optionJournalData = [...this.JournalYearData];
                optionData = this.yearData;
            }

            var xAxisData = [];
            var seriesData = [];

            console.log('optionJournalData at line 291:', optionData);
            Object.entries(optionData).forEach(([key, value]) => {
                xAxisData.push(key);
                console.log('key at line 294:', key);
                var otherInfo = optionJournalData.map((e) => {
                    for (let i in e.value) {
                        if (i == key) {
                         
                            return {
                                key: e.key,
                                value: e.value[i].split('/')[0]
                            };
                        }
                    }
                });

                seriesData.push({ value: value, otherInfo: otherInfo });

                data = { type: type, xAxisData: xAxisData, seriesData: seriesData };
            });

            return data;
        },
        async getJournalData(type) {
            var data = {};
            var url = '';
            if (type == 'month') {
                url = this.urlList.Journalmonth;
            } else if (type == 'year') {
                url = this.urlList.Journalyear;
            }

            await this.$api
                .post(url, {
                    // user_id: this.user_id
                })
                .then((res) => {
                    var that = this;
                    if (res.code == 0) {
                        data = res.data.data.map((e) => {
                            return { key: e.journal.abbr, value: e.articles, jabbr: e.journal.jabbr };
                        });
                        if (type == 'month') {
                            this.JournalMonthData = data;
                        } else if (type == 'year') {
                            this.JournalYearData = data;
                        }
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
        },
        // 获取文章列表数据
        async getTableData() {
            this.$nextTick(async () => {
                await this.getTableDataInfo('year');
                await this.getTableDataInfo('month');
            });
        },
        async getTableDataInfo(type) {
            var that = this;
            var data = {};
            var timeData = [];
            var tableData = [];

            var url = '';
            if (type == 'month') {
                for (let i in this.monthData) {
                  
                    timeData.push(i);
                }

                tableData = this.JournalMonthData.map((e) => {
                    console.log('e at line 394:', e);
                    return { ...e.value, abbr: e.key, jabbr: e.jabbr };
                });
            } else if (type == 'year') {
                for (let i in this.yearData) {
                   
                    timeData.push(i);
                }
                tableData = this.JournalYearData.map((e) => {
                    console.log('e at line 394:', e);
                    return { ...e.value, abbr: e.key, jabbr: e.jabbr };
                });
            }
            data = { tableData: tableData, timeData };
            console.log(data, type, '98999');
            if (type == 'year') {
                this.$refs.yearTableData.getTableInfo(type, data);
            } else if (type == 'month') {
                this.$refs.monthTableData.getTableInfo(type, data);
                setTimeout(() => {
                    that.loading = false;
                }, 50);
            }

            return data;
        }
    }
};
</script>

<style scoped>
.container {
    padding: 20px;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    position: relative;
}
.refresh {
    position: absolute;
    top: 20px;
    right: 0px;
    z-index: 10;
}
</style>
