<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="1" label="单个添加" />
          <el-option :value="4" label="协销填写" />
        </el-select>
      </div>
      <div class="filter-control">
        <span>协销:</span>
        <el-select v-model="listQuery.serviceProviderId" filterable @change="getList">
          <el-option value="" label="请选择" />
          <el-option
            v-for="item in sellerList"
            :key="item.serviceProviderId"
            :label="item.linkMan"
            :value="item.serviceProviderId"
          />
        </el-select>
      </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="'tag:static-list:add'" type="primary" @click="handleAddTag"> 添加标签 </el-button>
        <el-button v-permission="'tag:static-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="80" />
      <el-table-column prop="keyword" label="标签词" align="center" />
      <el-table-column width="180" label="来源" align="center">
        <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="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="240">
        <template slot-scope="{ row }">
          <el-button v-permission="'tag:static-list:del'" type="danger" size="mini" @click="handleDeleteTag(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

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

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

    <!-- 添加标签 -->
    <el-dialog
      title="添加标签"
      :visible.sync="addTagDialog"
      width="460px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form ref="tagForm" :model="tagForm" :rules="tagFormRules">
        <el-form-item label="标签名：" prop="keyword">
          <el-input v-model="tagForm.keyword" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="closeAddTagDialog"> 取 消 </el-button>
        <el-button type="primary" @click="handleAddTagConfirm"> 确 定 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SearchModel from '@/components/SearchModel'
import pickerOptions from '@/utils/time-picker.js'
import {
  getServiceList,
  saveLabelByState,
  deleteTrendsLabel,
  getStatekeywordList,
  findLinkageStatus
} from '@/api/library/keyword'
export default {
  components: { SearchModel },
  data() {
    return {
      isLoading: true,
      pickerOptions,
      time: '',
      listQuery: {
        keyword: '',
        beginTime: '',
        dynamicStatus: 1,
        parentLabel: '',
        endTime: '',
        serviceProviderId: '',
        pageNum: 1,
        pageSize: 20
      },
      list: [],
      total: 0,
      currentList: [],
      searchDialog: false,
      visibleKeyword: '',
      addTagDialog: false,
      tagForm: {
        id: '',
        keyword: '',
        dynamicStatus: 1,
        parentLabel: 0
      },
      tagFormRules: {
        keyword: [{ required: true, message: '请输入标签名称', trigger: ['blur'] }]
      },
      exportKeywordList: [],
      fileList: [],
      importForm: {
        fileUrl: ''
      },
      importFormRules: {
        fileUrl: [{ required: true, message: '文件不能为空', trigger: ['change'] }]
      },
      sellerList: []
    }
  },
  computed: {
    disabled() {
      return this.currentList.length === 0
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 标签下拉关联
    async handleStatusChange($event) {
      const res = await findLinkageStatus({ id: $event.id, linkageStatus: $event.linkageStatus ? 1 : 0 })
      if (res.code === 0) {
        if (res.data === 0) {
          await this.fetchKeywordList()
          return this.$message({
            type: 'success',
            message: `${res.msg}`
          })
        }
        if (res.msg.length < 5) {
          this.$message({
            type: 'success',
            message: '开启成功!'
          })
        } else {
          this.$confirm(`${res.msg}`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              $event.linkageStatus = !$event.linkageStatus
            })
            .catch(() => {
              $event.linkageStatus = !$event.linkageStatus
            })
        }
        await this.fetchKeywordList()
      }
    },

    // 获取标签列表
    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.getServiceList()
      this.getStatekeywordList()
    },
    // 获取协销列表选项
    async getServiceList() {
      try {
        const res = await getServiceList()
        this.sellerList = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 获取标签列表
    async getStatekeywordList() {
      try {
        this.isLoading = true
        const res = await getStatekeywordList(this.listQuery)
        this.list = res.data.results.map((i) => ({
          addTime: i.addTime,
          frequency: i.frequency,
          fromSearch: i.fromSearch,
          id: i.id,
          keyword: i.keyword,
          labelStatus: i.labelStatus,
          linkageStatus: i.linkageStatus === 1, // 0 关闭，1 打开
          recommendTime: i.recommendTime,
          searchTime: i.searchTime
        }))
        this.total = res.data.totalRecord
        this.isLoading = false
      } catch (error) {
        console.log(error)
      }
    },

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

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

    // 添加标签
    handleAddTag() {
      this.addTagDialog = true
    },

    // 添加标签取消
    closeAddTagDialog() {
      this.$refs.tagForm.resetFields()
      this.addTagDialog = false
    },

    // 添加标签确定
    async handleAddTagConfirm() {
      try {
        await this.$refs.tagForm.validate()
        this.addTagSubmit()
      } catch (error) {
        console.log(error)
      }
    },

    // 提交添加标签信息
    async addTagSubmit() {
      try {
        await saveLabelByState(this.tagForm)
        this.$message.success('添加标签成功')
        this.getList()
      } catch (error) {
        console.log(error)
      }
      this.closeAddTagDialog()
    },

    // 删除标签
    async handleDeleteTag(row) {
      try {
        await this.$confirm('确定删除已选标签？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        this.deleteTagSubmit(row)
      } catch (error) {
        this.$message.info('已取消删除操作')
      }
    },

    // 提交删除标签操作
    async deleteTagSubmit(row) {
      const keywords = row instanceof Event ? this.currentList : [].concat(row)
      const ids = keywords.map((item) => item.id).join(',')
      try {
        await deleteTrendsLabel({ id: 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>
