<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-select v-model="listQuery.fromSearch" clearable @change="getList">
          <el-option value="" label="请选择" />
          <el-option :value="1" label="单个添加" />
          <el-option :value="2" label="系统推荐" />
          <el-option :value="3" label="导入" />
          <el-option :value="4" label="协销填写" />
        </el-select>
      </div>
      <div class="filter-control">
        <span>类型:</span>
        <el-select v-model="listQuery.dynamicStatus" clearable @change="getList">
          <el-option value="" label="请选择" />
          <el-option :value="0" label="动态标签" />
          <el-option :value="1" label="静态标签" />
        </el-select>
      </div>
      <div class="filter-control">
        <el-button type="primary" @click="getList"> 查询 </el-button>
        <el-button
          v-permission="'tag:priority-list:add'"
          type="primary"
          :disabled="disabled1"
          @click="labelDialogVisible = true"
        >
          添加标签
        </el-button>
        <el-button v-permission="'tag:priority-list:del'" type="danger" :disabled="disabled" @click="handleDeleteTag">
          删除
        </el-button>
      </div>
    </div>
    <!-- 标签列表 -->
    <el-table v-loading="isLoading" :data="list" border height="600" @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="60" />
      <el-table-column prop="keyword" label="标签词" align="center" />
      <el-table-column label="来源" align="center" width="180">
        <template slot-scope="{ row }">
          <span v-if="row.fromSearch === 1">单个添加</span>
          <span v-else-if="row.fromSearch === 2">系统推荐</span>
          <span v-else-if="row.fromSearch === 3">导入</span>
          <span v-else>协销填写</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" width="180">
        <template slot-scope="{ row }">
          <el-tag v-if="row.dynamicStatus === 0" type="primary" size="small">动态标签</el-tag>
          <el-tag v-if="row.dynamicStatus === 1" type="success" size="small">静态标签</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" width="200">
        <template slot-scope="{ row }">
          <span v-if="row.addTime">{{ row.addTime | parseTime }}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150">
        <template slot-scope="{ row }">
          <el-button v-permission="'tag:priority-list:del'" type="danger" size="mini" @click="handleDeleteTag(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 页码 -->
    <pagination
      :page-sizes="[20]"
      :page-size="20"
      :total="total"
      :page.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getPriorKeywordList"
    />
    <!-- 选择添加标签弹窗 -->
    <LabelDialog
      v-if="labelDialogVisible"
      ref="labelDialog"
      :max-len="total"
      :keyword="visibleKeyword"
      @confirm="handleConfirmLabel"
      @cancel="handleCancel"
    />
  </div>
</template>

<script>
import LabelDialog from './components/label-dialog'
import { getYestodayTime } from '@/utils'
import { delPriorKeyword, getPriorKeywordList, savePriorKeyword } from '@/api/library/keyword'
export default {
  components: { LabelDialog },
  filters: {
    dynamicStatusFilters(value) {
      // 标签类型
      console.log('value', value)
      const map = {
        0: '动态标签',
        1: '静态标签'
      }
      return map[value]
    }
  },
  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,
      pickerOptions,
      time: '',
      listQuery: {
        keyword: '',
        dynamicStatus: '', // 0 为动态标签 1 静态标签
        fromSearch: '',
        pageNum: 1,
        pageSize: 20
      },
      list: [],
      total: 0,
      currentList: [],
      labelDialogVisible: false,
      visibleKeyword: '',
      addTagDialog: false,
      tagForm: {
        keyword: ''
      }
    }
  },
  computed: {
    disabled() {
      return this.currentList.length === 0
    },
    disabled1() {
      return this.total === 50
    }
  },
  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.getPriorKeywordList()
    },

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

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

    // 确认选择标签
    handleConfirmLabel(data) {
      console.log('data', data)
      const maxLeng = this.total + data.length
      console.log('maxLeng', maxLeng)
      if (maxLeng > 50) {
        this.$message.warning('只支持展示50个标签，请删减再添加。')
        return
      }
      const searchIds = []
      data.forEach((ele) => {
        searchIds.push(ele.id)
      })
      this.savePriorKeyword({ searchIds: searchIds.join(',') })
    },
    // 保存添加供应商关键词
    async savePriorKeyword(params) {
      try {
        await savePriorKeyword(params)
        this.$message.success('操作成功')
        this.handleCancel()
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },
    // 取消选择标签
    handleCancel() {
      this.labelDialogVisible = false
      this.$refs.labelDialog.visible = false
    },
    // 删除标签
    async handleDeleteTag(row) {
      try {
        await this.$confirm('确定删除已选标签？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.delPriorKeyword(row)
      } catch (error) {
        this.$message.info('已取消删除操作')
      }
    },
    // 提交删除标签操作
    async delPriorKeyword(row) {
      const keywords = row instanceof Event ? this.currentList : [].concat(row)
      const ids = keywords.map((item) => item.id).join(',')
      try {
        await delPriorKeyword({ ids: ids })
        this.$message.success('标签删除成功')
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },
    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    }
  }
}
</script>

<style></style>
