<template>
  <div class="app-container">
    <!-- 顶部操作区域 -->
    <div class="filter-container">
      <div class="filter-control">
        <span>关键词:</span>
        <el-input
          v-model="listQuery.keyword"
          placeholder="关键词"
          clearable
          @keyup.enter.native="getList"
          @clear="getList"
        />
      </div>
      <div class="filter-control">
        <span>搜索统计:</span>
        <el-date-picker
          v-model="time"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          value-format="yyyy-MM-dd"
          @change="getList"
        />
      </div>
      <div class="filter-control">
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button v-permission="'keyword:list:join'" type="primary" :disabled="disabled" @click="handleAddLibrary">
          加入标签库
        </el-button>
        <el-button v-permission="'keyword:list:export'" type="primary" :disabled="disabled" @click="handleExport">
          导出
        </el-button>
      </div>
    </div>

    <!-- 关键词列表 -->
    <el-table
      ref="table"
      v-loading="isLoading"
      :data="list"
      border
      :default-sort="{ prop: 'frequency', order: 'descending' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" :index="indexMethod" type="index" sortable="custom" align="center" width="80" />
      <el-table-column prop="keyword" label="关键词" align="center" />
      <el-table-column
        prop="pv"
        label="搜索次数"
        width="120"
        align="center"
        sortable
        :sort-orders="['ascending', 'descending']"
      />
      <el-table-column label="最近搜索时间" align="center">
        <template slot-scope="{ row }">
          <span v-if="row.searchTime">{{ row.searchTime | parseTime }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="240">
        <template slot-scope="{ row }">
          <div class="labelCenter">
            <el-button type="primary" size="mini" @click="handleSearch(row.keyword)">去搜索</el-button>
            <template v-if="row.labelStatus === 0">
              <el-button v-permission="'keyword:list:join'" type="primary" size="mini" @click="handleAddLibrary(row)">
                加入标签库
              </el-button>
            </template>
            <template v-else>
              <el-button class="labelPoint" type="primary" size="mini"> 加入标签库 </el-button>
            </template>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 页码 -->
    <pagination
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="fetchKeywordList"
    />

    <!-- 去搜索跳转 -->
    <SearchModel v-model="searchDialog" :keyword="visibleKeyword" />
  </div>
</template>

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

export default {
  components: { SearchModel },
  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 * 6)
            picker.$emit('pick', [start, end])
          }
        },
        {
          text: '昨天',
          onClick(picker) {
            const { start, end } = getYestodayTime()
            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)
      let ids = keywords.filter((item) => item.labelStatus === 0).map((item) => item.id)
      if (keywords.length > ids.length) {
        this.$refs.table.clearSelection()
        return this.$message.info('已添加到标签库的标签不可重复添加')
      }
      ids = ids.join(',')
      try {
        await joinKeywordLibrary({ id: ids })
        this.$message.success('添加关键词库成功')
        keywords.forEach((item) => {
          item.labelStatus = 1
        })
        this.$refs.table.clearSelection()
      } 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
    },

    isSelectable(row) {
      return row.labelStatus === 0
    }
  }
}
</script>

<style scoped lang="scss">
.labelCenter {
  display: flex;
  flex-direction: row-reverse;
  justify-content: space-around;
  .labelPoint {
    opacity: 0;
    cursor: default;
  }
}
</style>
