<script setup>
import axios from 'axios';
import * as echarts from 'echarts';

import { onMounted, reactive, onUnmounted } from 'vue';
const state = reactive({
  loading: false,
  searchValue: '',
  firstChart: null,
  columns: [{
    title: '文章名称',
    dataIndex: 'title',
    fixed: true
  }, {
    title: '链接',
    key: 'url'
  }, {
    title: '浏览量',
    dataIndex: 'viewCount',
    sorter: (a, b) => a.viewCount - b.viewCount,
  }, {
    title: '收藏量',
    dataIndex: 'collectCount',
    sorter: (a, b) => a.collectCount - b.collectCount,
  }, {
    title: '分数',
    dataIndex: 'score',
    sorter: (a, b) => a.score - b.score,
  }, {
    title: '建议',
    dataIndex: 'message',
  }, {
    title: '发文时间',
    dataIndex: 'postTime',
  }],
  dataSource: [],
  pagination: {
    total: 0,
    current: 1,
    pageSize: 10,
    pageSizeOptions: ['10', '20', '30'],
    showTotal: (total, range) => {
      return range[0] + '-' + range[1] + ' 共' + total + '篇博客';
    },
    onShowSizeChange: changePageSize, // 改变每页数量时更新显示
    onChange: changePage,//点击页码事件
  }
})
function changePage(page, pageSize) {
  state.pagination.current = page
  state.pagination.pageSize = pageSize
}
function changePageSize(current, pageSize) {
  state.pagination.current = current
  state.pagination.pageSize = pageSize
}
const getCsdnData = (uId) => {

  const url = 'https://yongma16.xyz/common-api/getCsdnGrade/'
  const data = {
    uId
  }
  state.loading = true
  state.pagination.current = 1
  axios.post(url, data, { timeout: 100000 }).then(res => {
    state.dataSource = res.data.data
    state.pagination.total = state.dataSource.length
    state.loading = false
    initFirstData()
  }).catch((r) => {
    state.pagination.total = 0
    console.log(r)
    state.loading = false
    state.dataSource = []
    initFirstData()
  })
}

const onSearch = () => {
  if (!state.searchValue) {
    return window.alert('请输入用户id')
  }
  window.localStorage.setItem('csdnUid', state.searchValue)
  getCsdnData(state.searchValue)
}

function initFirstData() {
  // 基于准备好的dom，初始化echarts实例
  const myChart = echarts.init(document.getElementById('first'));
  const option = {
    title: {
      text: 'csdn 质量分柱状图 点击跳转到对应的文章'
    },
    toolbox: {
      show: true,
      feature: {
        saveAsImage: {}
      }
    },
    dataZoom: [
      {
        id: 'dataZoomX',
        type: 'slider',
        xAxisIndex: [0],
        filterMode: 'filter'
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {},
    xAxis: {
      type: 'category',
      data: state.dataSource.map(item => item.postTime)
    },
    yAxis: {
      type: 'value'
    },
    tooltip: {
      formatter: function (params) {
        const findItem = state.dataSource.find(item => {
          return item.postTime == params.name
        })
        return `<span style='color:blue'>-<span> 博客标题：${findItem.title}  <br>
                <span style='color:green'>-<span> 博客质量：${params.value} <br>
                <span style='color:red'>-<span> 博客建议：${findItem.message}<br>
                <span style='color:blue'>-<span> 博客地址：${findItem.url}<br>
                <span style='color:blue'>-<span> 发文时间：${params.name}<br>
               `
      },
    },
    series: [
      {
        data: state.dataSource.map(item => item.score),
        type: 'bar',
        showBackground: true,
        backgroundStyle: {
          color: 'rgba(180, 180, 180, 0.2)'
        },
        label: { //柱体上显示数值
          show: true,//开启显示
          position: 'center',//在上方显示
          textStyle: {//数值样式
            fontSize: '2px',
            color: 'blue'
          }
        },
        markPoint: {
          data: [
            { type: 'max', name: '最高分' },
            { type: 'min', name: '最低分' }
          ]
        },
        markLine: {
          data: [{ type: 'average', name: '平均分' }]
        }
      }
    ]
  };
  // 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);
  // 监听
  state.firstChart = myChart;
  window.onresize = myChart.resize
  myChart.on('click', function (params) {
    const findItem = state.dataSource.find(item => {
      return item.postTime == params.name
    })
    if (params.name) {
      window.open(findItem.url, '_blank')
    }
  });

  onMounted(() => {
    const storageUid = window.localStorage.getItem('csdnUid')
    if (storageUid) {
      state.searchValue = storageUid
      onSearch()
    }
  })
  onUnmounted(() => {
    window.onresize = null
    if (state.searchValue) {
      window.localStorage.setItem('csdnUid', state.searchValue)
    }
    else {
      window.localStorage.removeItem('csdnUid')
    }
  })
}
</script>

<template>
  <div class="container">
    <div style="text-align: center;">
      <h3>输入csdn用户id查询文章分数</h3>
    </div>
    <br>
    <div>
      <a-input-search v-model:value="state.searchValue" :disabled="state.loading" placeholder="输入用户id" enter-button
        @search="onSearch" />
    </div>

    <br>
    <div>
      <a-table :scroll="{ x: 800, y: 500 }" :columns="state.columns" :data-source="state.dataSource"
        :loading="state.loading" :pagination="state.pagination" bordered>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'url'">
            <a :href="record.url" target="_blank">
              {{ record.url }}
            </a>
          </template>
        </template>
      </a-table>
    </div>
    <div>
      <div id="first" style="width:100vw;height:900px;margin: 0 auto"></div>
    </div>

  </div>
</template>

<style scoped></style>
