<script setup>
import Author from './Author.vue';
import ExportBtn from './ExportBtn.vue';
import EchartBar from './EchartBar.vue';
import { tableColumns } from './const';
import { getRemoteCsdnGrade } from '../service/csdnApi';
import { onMounted, reactive, onUnmounted, computed } from 'vue';

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,//点击页码事件
  },
  selectedRows: []
})

// 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
    saveStorege(state.dataSource)

  }).catch((r) => {
    state.pagination.total = 0
    console.log(r)
    state.loading = false
    state.dataSource = []
    initFirstData()
  })
}

async function saveStorege(val) {
  return new Promise(resolve => {
    window.localStorage.setItem('csdnUidData', JSON.stringify(val))
    resolve(true)
  })
}

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

const rowSelection = {
  onChange: (selectedRowKeys, selectedRows) => {
    console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    state.selectedRows = selectedRows
  },
  getCheckboxProps: (record) => ({
    disabled: record.name === 'Disabled User', // Column configuration not to be checked
    name: record.name,
  })
}


const exportTableData = computed(() => {
  if (state.selectedRows?.length) {
    return state.selectedRows
  }
  return state.dataSource
})



onMounted(() => {
  // const storageUid = localStorage.getItem('csdnUid')
  console.log('window.localStorage', localStorage)
  // console.log('storageUid', storageUid)
  // if (storageUid) {
  //   state.searchValue = storageUid
  //   onSearch()
  // }
  document.addEventListener('keydown', (e) => {
    console.log(e, 'e')
    if (e.ctrlKey && e.keyCode === 89) {
      console.log('Ctrl+y');
      onSearch()
    }
  })

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

<template>
  <div class="container">
    <Author />
    <div style="text-align: center;">
      <a style="font-size: 24px;font-weight:bolder;">{{ state.title }}</a>
    </div>
    <div>

    </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>

    <div>
      <ExportBtn :table-data="exportTableData" :user-id="state.searchValue" />
      <a-table :scroll="{ x: 800, y: 600 }" :columns="state.columns" :row-selection="rowSelection"
        :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">
        <EchartBar :table-data="state.dataSource" />
      </a-spin>
    </div>
  </div>
</template>
