<template>
    <div class="container" style="padding-bottom: 50px; width: 100%; height: 100%">
        <div class="block">
            <el-select
                v-model="journal_id"
                filterable
                placeholder="Please select a Journal"
                value-key="groupID"
                style="width: 300px; margin-right: 10px"
                @change="chan_id"
            >
                <el-option v-for="item in evaList" :label="item.title" :key="item.journal_id" :value="item.journal_id"></el-option>
            </el-select>
            <el-date-picker
                @change="selectYear"
                :picker-options="pickerOption"
                style="width: 200px"
                :clearable="false"
                v-model="currentYear"
                type="year"
                format="yyyy"
                placeholder="选择年"
            >
            </el-date-picker>
        </div>
        <div style="margin-top: 20px" v-loading="loading">
            <el-table
                :data="tableData"
                class="msg-table"
                empty-text="New Data (0)"
                :tree-props="{ children: 'articles', hasChildren: 'hasChildren' }"
           
                >
                <el-table-column type="expand" width="15" align="center">
                    <template slot-scope="props">
                        <!-- {{ props.row.articles.length }} -->
                        <div class="articleTable">
                            <el-table
                                row-key="article_id"
                                style="width: calc(100% - 20px); float: right; margin-top: 15px; margin-bottom: 20px"
                                border
                                :data="props.row.articles"
                                class=""
                                empty-text="New Data (0)"
                            >
                                <!-- <el-table-column type="index" label="No." width="45" align="center"></el-table-column> -->
                                <el-table-column :label="`${$t('paperArticleCount.articleTitle')}`" width="" prop="title">
                                    <template slot-scope="scope">
                                        <span style="font-size: 700">{{ scope.$index + 1 }}. &nbsp;&nbsp;</span> {{ scope.row.title }}
                                    </template>
                                </el-table-column>
                                <el-table-column :label="$t('paperArticleCount.cite')" prop="title" width="80">
                                    <template slot-scope="scope">
                                        <el-popover
                                            ref="popover"
                                            placement="right"
                                            trigger="click"
                                            width="700"
                                            v-if="scope.row.cites && scope.row.cites > 0"
                                        >
                                            <ul style="padding: 10px; box-sizing: border-box; max-height: 500px; overflow-y: auto">
                                                <li v-for="(v, i) in citeList" style="overflow: hidden; margin-bottom: 10px">
                                                    <div style="color: #7a2702; margin-right: 10px; float: left">{{ i + 1 }} .</div>
                                                    <div style="float: left">
                                                        <div style="margin-bottom: 2px">
                                                            <a
                                                                target="_blank"
                                                                :href="`https://doi.org/${v.doi}`"
                                                                style="color: #205493 !important"
                                                                >{{ v.article_name }}</a
                                                            >
                                                        </div>
                                                        <div style="color: #a2b1b6">
                                                            <span>{{ v.author }}</span>
                                                            <span style="margin-left: 5px">{{ v.journal_name }}</span>
                                                        </div>
                                                    </div>
                                                </li>
                                            </ul>

                                            <div
                                                :style="`text-align: center; color:${
                                                    scope.row.cites && scope.row.cites > 0 ? '#006699' : '#b0b0b0'
                                                }; cursor: pointer;font-weight:${scope.row.cites && scope.row.cites > 0 ? '700' : '500'};`"
                                                slot="reference"
                                                @click="getCite(scope.row.article_id)"
                                            >
                                                {{ scope.row.cites ? scope.row.cites : 0 }}
                                            </div>
                                        </el-popover>
                                        <div style="text-align: center; color: #b0b0b0; cursor: pointer" v-else>
                                            {{ scope.row.cites ? scope.row.cites : 0 }}
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column :label="$t('paperArticleCount.relation')" prop="title" width="80">
                                    <template slot-scope="scope">
                                        <el-popover
                                            ref="popover1"
                                            placement="right"
                                            trigger="click"
                                            width="700"
                                            v-if="scope.row.relations && scope.row.relations > 0"
                                        >
                                            <ul
                                                style="padding: 10px; box-sizing: border-box; max-height: 500px; overflow-y: auto"
                                                v-loading="citeLoading"
                                            >
                                                <li v-for="(v, i) in relationsList" style="overflow: hidden; margin-bottom: 10px">
                                                    <div style="color: #7a2702; margin-right: 10px; float: left">{{ i + 1 }} .</div>
                                                    <div style="float: left; width: calc(100% - 100px)">
                                                        <div style="margin-bottom: 2px">
                                                            <a
                                                                target="_blank"
                                                                :href="`https://doi.org/${v.doi}`"
                                                                style="color: #205493 !important"
                                                                >{{ v.title }}</a
                                                            >
                                                        </div>
                                                        <div style="color: #a2b1b6">
                                                            <span>{{ v.abbr }}</span>
                                                            <span style="margin-left: 5px">{{ v.journal_name }}</span>
                                                        </div>
                                                    </div>
                                                </li>
                                            </ul>

                                            <div
                                                :style="`text-align: center; color:${
                                                    scope.row.relations && scope.row.relations > 0 ? '#006699' : '#b0b0b0'
                                                }; cursor: pointer;font-weight:${
                                                    scope.row.relations && scope.row.relations > 0 ? '700' : '500'
                                                };`"
                                                slot="reference"
                                                @click="getArticleCountRelatedForEditor(scope.row.article_id)"
                                            >
                                                {{ scope.row.relations ? scope.row.relations : 0 }}
                                            </div>
                                        </el-popover>
                                        <div style="text-align: center; color: #b0b0b0; cursor: pointer" v-else>
                                            {{ scope.row.relations ? scope.row.relations : 0 }}
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </template>
                </el-table-column>

                <el-table-column :label="$t('paperArticleCount.Periodroll')" width="" prop="title">
                    <template slot-scope="scope">
                        <div style="display: flex; align-items: center; justify-content: space-between">
                            <div>
                                <span style="display: inline-block; width: 140px; font-weight: 700; color: #333"
                                    >Issue.{{ scope.$index + 1 }} No.{{ scope.row.stage_page }}</span
                                >
                                <span style="color: #006699"
                                    >(&nbsp;{{ $t('paperArticleCount.articleLen1') }} : {{ scope.row.articles.length }}&nbsp;)</span
                                >
                            </div>

                            <span style="color: #b0b0b0; display: inline-block; width: 120px"> {{ scope.row.issue_date }} </span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            activeNames: [],
      expands: [],
            citeLoading: false,
            expandedRows: [],
            lang: !localStorage.getItem('langs') || localStorage.getItem('langs') == 'en' ? 'en' : 'zh',
            pickerOption: {
                disabledDate(time) {
                    return time.getFullYear() < 2020 || time.getFullYear() > new Date().getFullYear();
                }
            },
            currentYear: '',
            loading: false,
            journal_id: '',
            citeList: [],
            relationsList: [],
            evaList: [],
            tableData: [],
            journal_data: {},
            user_id: localStorage.getItem('U_id')
        };
    },
    components: {},
    async created() {
        this.maxYear = new Date();
        this.currentYear = new Date();

        this.getData();
    },
    methods: {
        expndChange(row, expandedRows) {
      if (expandedRows.length) {
        this.expands = []
        if (row) {
          this.expands.push(row.journal_id) // 每次push进去的是每行的ID
        }
      } else {
        this.expands = [] // 默认不展开
      }
    },
    getRowKeys(row) {
      return row.journal_id
    },
        toggleRow(row) {
            const index = this.expandedRows.indexOf(row.journal_stage_id);
            if (index === -1) {
                this.expandedRows.push(row.journal_stage_id);
            } else {
                this.expandedRows.splice(index, 1);
            }
        },
        async chan_id(value) {
            this.loading = true;
            console.log('value at line 138:', value);
            // this.$echarts.init(document.getElementById('myChart')).clear();
            // this.$echarts.init(document.getElementById('myChartgjhp')).clear();
            this.journal_id = value;
            console.log('this.evaList at line 169:', this.evaList);
            this.journal_data = this.evaList.find((e) => e.journal_id == this.journal_id);
            this.currentYear = new Date();
            this.getInfo();
            // await this.initEcharts();
            // await this.initEchartsgjh();
        },
        // 获取数据
        async getData() {
            this.loading = true;

            this.$api
                .post('api/Super/editorJournal', {
                    editor_id: this.user_id
                })
                .then(async (res) => {
                    if (res.code == 0) {
                        this.loading = false;
                        this.evaList = res.data.list;
                        this.journal_id = res.data.list[0].journal_id;
                        console.log('this.evaList at line 169:', this.evaList);
                        this.journal_data = this.evaList.find((e) => e.journal_id == this.journal_id);

                        await this.getInfo();
                    } else {
                        this.$message.error(res.msg);
                    }
                })
                .catch((err) => {
                    this.loading = false;
                    this.$message.error(err);
                });
        },
        selectYear() {
            this.loading = true;
            this.getInfo();
        },
        async getInfo() {
            var that = this;
            await this.$api
                .post('api/Monitor/getPublicStagesForEditor', {
                    journal_id: this.journal_id,
                    year: this.currentYear.getFullYear()
                })
                .then(async (res) => {
                    if (res.code == 0) {
                        var data = res.data.list;
                        console.log('data at line 177:', data);

                        that.tableData = [...data];
                        console.log('this.tableData at line 177:', this.tableData);
                        this.$forceUpdate();
                        this.loading = false;
                    } else {
                        this.loading = false;
                        this.$message.error(res.msg);
                    }
                })
                .catch((err) => {
                    this.loading = false;
                    this.$message.error(err);
                });
        },
        async getCite(id) {
            var that = this;
            this.citeList = [];
            this.citeLoading = true;
            await this.$api
                .post('api/Monitor/getArticleCountCiteForEditor', {
                    article_id: id
                })
                .then(async (res) => {
                    if (res.code == 0) {
                        this.citeList = res.data.list;
                        this.citeLoading = false;
                        setTimeout(() => {
                            that.$nextTick(() => {
                                that.$refs.popover.updatePopper();
                            });
                        }, 100);
                    } else {
                        this.$message.error(res.msg);
                        this.citeLoading = false;
                    }
                })
                .catch((err) => {
                    this.$message.error(err);
                    this.citeLoading = false;
                });
        },
        async getArticleCountRelatedForEditor(id) {
            var that = this;
            this.citeLoading = true;
            this.relationsList = [];
            await this.$api
                .post('api/Monitor/getArticleCountRelatedForEditor', {
                    article_id: id
                })
                .then(async (res) => {
                    if (res.code == 0) {
                        this.relationsList = res.data.list;
                        this.citeLoading = false;
                        setTimeout(() => {
                            that.$nextTick(() => {
                                that.$refs.popover1.updatePopper();
                            });
                        }, 100);
                    } else {
                        this.$message.error(res.msg);
                        this.citeLoading = false;
                    }
                })
                .catch((err) => {
                    this.$message.error(err);
                    this.citeLoading = false;
                });
        },
        handleRefresh() {},
        async getEchartsData() {
            await this.getCharts('year');
            await this.getCharts('month');
            this.$forceUpdate();
        },
        async getCharts(type) {
            var optionsData = await this.getdata(type);
            console.log('🚀 ~ getCharts ~ optionsData:', optionsData);

            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'
                        }
                    }
                },
                //   legend: {
                //     data: ['Email', 'Union Ads', 'Video Ads', 'Direct', 'Search Engine']
                //   },
                toolbox: {
                    // feature: {
                    // //   dataZoom: {
                    // //     yAxisIndex: 'none'
                    // //   },
                    //   restore: {},
                    // }
                },
                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 data = {};
            var url = '';
            if (type == 'month') {
                url = '/api/Monitor/getArticleNumByMonth';
            } else if (type == 'year') {
                url = '/api/Monitor/getArticleNumByYear';
            }
            await this.$api
                .post(url)
                .then((res) => {
                    var that = this;
                    if (res.code == 0) {
                        console.log('🚀 ~ .then ~ res1998:' + type, res.data.articles);
                        var xAxisData = [];
                        var seriesData = [];
                        Object.entries(res.data.articles).forEach(([key, value]) => {
                            xAxisData.push(key);
                            seriesData.push(value);

                            data = { type: type, xAxisData: xAxisData, seriesData: seriesData };
                        });
                    }
                })
                .catch((err) => {
                    console.log(err);
                });
            return data;
        },
        // 获取文章列表数据
        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') {
                url = '/api/Monitor/getArticleNumByMonthForJournal';
            } else if (type == 'year') {
                url = '/api/Monitor/getArticleNumByYearForJournal';
            }
            await this.$api
                .post(url)
                .then(async (res) => {
                    var that = this;
                    if (res.code == 0) {
                        for (let i in res.data.data) {
                            tableData.push({ ...res.data.data[i].journal, ...res.data.data[i].articles });
                        }

                        for (let i in res.data.data[0].articles) {
                            timeData.push(i);
                        }

                        data = { tableData: tableData, timeData: timeData };
                    }
                })
                .catch((err) => {
                    console.log(err, '989898');
                    this.loading = false;
                });
            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>
/deep/.articleTable .el-table th {
    background-color: #f0f0f0 !important;
    color: #006699 !important;
    padding: 3px !important;
}
.container {
    padding: 20px;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    position: relative;
}
.refresh {
    position: absolute;
    top: 20px;
    right: 0px;
    z-index: 10;
}
.demo-table-expand {
    font-size: 0;
}
.demo-table-expand label {
    width: 90px;
    color: #99a9bf;
}
.demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 50%;
}

li {
    list-style: none;
}

li a:hover {
    text-decoration: underline; /* 鼠标移入时显示下划线 */
}
</style>
