<script setup>
import * as echarts from 'echarts';
import Author from './Author.vue'
import { tableColumns } from './const'
import { getRemoteCsdnGrade } from '../service/csdnApi'
import { onMounted, reactive, onUnmounted } from 'vue';
import { exportExcel } from './writeExcel'
const state = reactive({
  title: 'csdn用户根据id快速查分数改文章',
  loading: false,
  exportLoading: false,
  searchValue: localStorage.getItem('csdnUid') || '',
  firstChart: null,
  columns: tableColumns,
  dataSource: localStorage.getItem('csdnUidData') ? JSON.parse(localStorage.getItem('csdnUidData')) : [],
  pagination: {
    total: 0,
    current: 1,
    pageSize: 10,
    pageSizeOptions: ['10', '50', '100'],
    showTotal: (total, range) => {
      return range[0] + '-' + range[1] + ' 共' + total + '篇博客';
    },
    onShowSizeChange: changePageSize, // 改变每页数量时更新显示
    onChange: changePage,//点击页码事件
  }
})

// storage
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 data = {
    uId
  }
  state.loading = true
  state.pagination.current = 1
  getRemoteCsdnGrade(data).then(res => {
    state.dataSource = res.data.data
    state.pagination.total = state.dataSource.length
    state.loading = false
    initFirstData()
    window.localStorage.setItem('csdnUidData', JSON.stringify(state.dataSource))
  }).catch((r) => {
    state.pagination.total = 0
    console.log(r)
    state.loading = false
    state.dataSource = []
    initFirstData()
  })
}

const onSearch = () => {
  if (!state.searchValue) {
    return window.alert('请输入csdn用户id 如 qq_38870145')
  }
  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'
    },
    grid: {
      x: 60,
      x2: 100
    },
    tooltip: {
      formatter: function (params) {
        let findItem = state.dataSource.find(item => {
          return item.postTime == params.name
        })
        if (!findItem) {

          return ''
        }
        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: {
          itemStyle: {
            normal: {
              lineStyle:
              {
                type: 'dotted',
              },
              label:
              {
                show: true,
                position: 'middle',
                color: 'red',
                lineHeight: 35,
                backgroundColor: 'rgba(255,255,255.7)',
                formatter: (params) => {
                  console.log('params markline', params)
                  return params.name + ":" + params.value
                }
              }
            }
          },
          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')
    }
  });

  const exportTableDataFunc = () => {
    if (!state.dataSource || state.dataSource.length === 0) {
      return window.alert('表格数据为空')
    }
    state.exportLoading = true
    exportExcel(state.dataSource, '用户质量分').then(res => {
      state.exportLoading = false
      console.log('res', res)
    })
  }

  onMounted(() => {
    const storageUid = localStorage.getItem('csdnUid')
    console.log('window.localStorage', localStorage)
    console.log('storageUid', storageUid)
    if (storageUid) {
      state.searchValue = storageUid
      onSearch()
    }
    // storage
    // if (state.dataSource) {
    //   initFirstData();
    // }

  })
  onUnmounted(() => {
    window.onresize = null
    if (state.searchValue) {
      window.localStorage.setItem('csdnUid', state.searchValue)
    }
    if (state.dataSource) {
      window.localStorage.setItem('csdnUidData', JSON.stringify(state.dataSource))
    }
  })

  document.addEventListener('keydown', (e) => {
    console.log(e, 'e')
    if (e.ctrlKey && e.keyCode === 79) {
      console.log('Ctrl+y');
      onSearch()
    }
  })

}
</script>

<template>
  <div class="container">
    <div style="text-align: center;">
      <a style="font-size: 24px;font-weight:bolder;">{{ state.title }}</a>
    </div>
    <div>
      <Author />
    </div>
    <br>
    <div style="display:flex">
      <div style="width:100px;line-height: 32px;">csdn用户id：</div><a-input-search v-model:value="state.searchValue"
        :disabled="state.loading" placeholder="输入用户id(如 qq_38870145)" enter-button @search="onSearch" />
    </div>
    <a-button type="primary" @click="exportTableDataFunc" style="margin: 10px 0;" :loading="state.exportLoading">
      导出 </a-button>
    <div>
      <a-table :scroll="{ x: 800, y: 600 }" :columns="state.columns" :data-source="state.dataSource"
        :loading="state.loading" :pagination="state.pagination" bordered style="border-bottom:1px solid #f0f0f0;">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'url'">
            <a :href="record.url" target="_blank">
              {{ record.url }}
            </a>
          </template>
          <template v-else-if="column.key === 'score'">
            <span>
              <a-tag :color="record.score < 60 ? 'volcano' : record.score > 80 ? 'geekblue' : 'green'">
                {{ record.score }}
              </a-tag>
            </span>
          </template>
          <template v-else-if="column.key === 'option'">
            <a-tooltip placement="topLeft" :title="record.editUrl">
              <a :href="record.editUrl" target="_blank">
                编辑文章
              </a>
            </a-tooltip>
          </template>
        </template>
      </a-table>
    </div>
    <div>
      <a-spin :spinning="state.loading">
        <div id="first" style="width:100vw;height:900px;margin: 0 auto"></div>
      </a-spin>
    </div>
  </div>
</template>
