<template>
  <div class="app-container">
    机构列表
  </div>
</template>

<script>
import { parseTime } from '@/utils'
import { fetchKeywordList, joinKeywordLibrary } from '@/api/library/keyword'
import { export_json_to_excel } from '@/vendor/Export2Excel'

export default {
  data() {
    const pickerOptions = {
      shortcuts: [
        {
          text: '近1年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 365)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '近半年',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 183)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '近1月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '近1周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24)
            picker.$emit('pick', [start, end])
          }
        }
      ]
    }
    return {
      isLoading: true,
      time: '',
      listQuery: {
        keyword: '',
        beginTime: '',
        endTime: '',
        labelStatus: '',
        searchTimeCode: '',
        fromSearch: '',
        pageNum: 1,
        pageSize: 10
      },
      pickerOptions,
      list: [],
      total: 0,
      currentList: [],
      searchDialog: false,
      visibleKeyword: ''
    }
  },
  computed: {
    disabled() {
      return this.currentList.length === 0
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取关键词列表
    getList() {
      this.listQuery.pageNum = 1
      if (this.time && this.time.length > 0) {
        this.listQuery.beginTime = this.time[0]
        this.listQuery.endTime = this.time[1]
      } else {
        this.listQuery.beginTime = ''
        this.listQuery.endTime = ''
      }
      this.fetchKeywordList()
    },

    // 获取关键词列表
    async fetchKeywordList() {
      try {
        this.isLoading = true
        const res = await fetchKeywordList(this.listQuery)
        this.list = res.data.results
        this.total = res.data.totalRecord
        this.isLoading = false
      } catch (error) {
        console.log(error)
      }
    },

    // 添加到标签库
    async handleAddLibrary(row) {
      try {
        await this.$confirm('确定将所选标签加入到标签库？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.addLibrarySubmit(row)
      } catch (error) {
        this.$message.info('已取消操作')
      }
    },

    // 添加到标签库提交
    async addLibrarySubmit(row) {
      const keywords = row instanceof Event ? this.currentList : [].concat(row)
      const ids = keywords.map((item) => item.id).join(',')
      try {
        await joinKeywordLibrary({ id: ids })
        this.$message.success('添加关键词库成功')
        keywords.forEach((item) => {
          item.labelStatus = 1
        })
      } catch (error) {
        console.log(error)
      }
    },

    // 选中列表项
    handleSelectionChange(current) {
      this.currentList = current
    },

    // 去搜索
    handleSearch(keyword) {
      this.visibleKeyword = keyword
      this.searchDialog = true
    },

    // 导出
    async handleExport() {
      try {
        await this.$confirm('确定将所选标签导出为xlsx？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 导出数据格式化
        const filterVal = ['index', 'keyword', 'frequency', 'searchTime', 'labelStatus']
        const data = this.formatJson(filterVal, this.currentList.slice(0))
        export_json_to_excel({
          header: ['序号', '标签', '搜索次数', '最近搜索时间', '标签库状态'],
          data,
          filename: '关键词列表'
        })
      } catch (error) {
        this.$message.info('已取消导出操作')
      }
    },

    formatJson(filterVal, jsonData) {
      return jsonData.map((v, index) =>
        filterVal.map((key) => {
          if (['searchTime'].includes(key)) {
            return parseTime(v[key])
          }
          if (key === 'index') return index + 1
          if (key === 'labelStatus') {
            const t = ['未添加', '已添加', '导入']
            return t[v[key]]
          }
          return v[key]
        })
      )
    },

    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    }
  }
}
</script>

<style></style>
