<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">
        <el-button type="primary" @click="getList">查询</el-button>
        <el-button v-permission="'tag:list:add'" type="primary" @click="handleSelectionTagDialog">选择标签</el-button>
        <el-button v-permission="'tag:list:del'" type="danger" :disabled="disabled" @click="handleDeleteTag">
          删除
        </el-button>
      </div>
    </div>
    <!-- 关键词列表 -->
    <el-table v-loading="isLoading" :data="list" border @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>导入</span>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" align="center" width="200">
        <template slot-scope="{ row }">
          <span v-if="row.pickTime">{{ row.pickTime | 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:list:del'" type="danger" size="mini" @click="handleDeleteTag(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 选择标签 -->
    <el-dialog
      title="选择标签"
      :visible.sync="selectionTagDialog"
      width="1000px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <div class="filter-container">
        <div class="filter-control">
          <span>标签:</span>
          <el-input
            v-model="labelQuery.keyword"
            placeholder="标签"
            clearable
            @keyup.enter.native="fetchLabelList"
            @clear="fetchLabelList"
          />
        </div>
        <div class="filter-control">
          <el-button type="primary" @click="fetchLabelList">查询</el-button>
          <el-button type="primary" @click="handleAddTag">新增标签</el-button>
        </div>
      </div>
      <el-table
        ref="table"
        v-loading="isLoading"
        :data="labelList"
        height="340px"
        border
        @selection-change="handleSelectionTagChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="keyword" label="标签" align="center" />
        <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>
      <div slot="footer">
        <el-button @click="selectionTagDialog = false">取 消</el-button>
        <el-button type="primary" :disabled="labelDisabled" @click="handleSelectionTagConfirm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 添加标签 -->
    <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" maxlength="20" />
        </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 {
  fetchShopLabelList,
  fetchLabelList,
  relevanceInsertLabel,
  delShopLabelList,
  addInsertSearch
} from '@/api/user/supplier/supplier'
export default {
  data() {
    return {
      isLoading: true,
      relevanceId: null,
      listQuery: {
        relevanceId: '',
        keyword: '',
        pageNum: 1,
        pageSize: 10
      },
      list: [],
      total: 0,
      currentList: [],
      searchDialog: false,
      addTagDialog: false,
      selectionTagDialog: false,
      labelQuery: {
        shopId: '', // 供应商Id
        keyword: '', // 标签名
        pageNum: 1, // 页码
        pageSize: 100 // 页面数据数
      },
      tagForm: {
        keyword: ''
      },
      tagFormRules: {
        keyword: [{ required: true, message: '请输入标签名称', trigger: ['blur'] }]
      },
      exportKeywordList: [],
      importDialog: false,
      fileList: [],
      importForm: {
        fileUrl: ''
      },
      importFormRules: {
        fileUrl: [{ required: true, message: '文件不能为空', trigger: ['change'] }]
      },
      labelList: [],
      labelCurrentList: []
    }
  },
  computed: {
    disabled() {
      return this.currentList.length === 0
    },
    labelDisabled() {
      return this.labelCurrentList.length === 0
    }
  },
  created() {
    this.relevanceId = this.$route.query.relevanceId
    this.labelQuery.shopId = this.$route.query.shopId
    this.listQuery = { ...this.listQuery, ...this.$route.query }
    console.log('listQuery', this.listQuery)
    this.getList()
  },
  methods: {
    // 获取关键词列表
    getList() {
      this.listQuery.pageNum = 1
      this.fetchShopLabelList()
    },

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

    // 显示选择标签列表
    handleSelectionTagDialog() {
      this.selectionTagDialog = true
      this.fetchLabelList()
    },

    // 获取标签列表
    async fetchLabelList() {
      try {
        const res = await fetchLabelList(this.labelQuery)
        this.labelList = res.data.results
      } catch (error) {
        console.log(error)
      }
    },
    // 选中标签项
    handleSelectionTagChange(current) {
      this.labelCurrentList = current
    },

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

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

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

    // 选择标签确定
    async handleSelectionTagConfirm() {
      const ids = this.labelCurrentList.map((item) => item.id).join(',')
      try {
        await relevanceInsertLabel({ relevanceId: this.relevanceId, keywordIds: ids })
        this.$message.success('添加成功')
        this.selectionTagDialog = false
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },
    // 添加标签确定
    async handleAddTagConfirm() {
      try {
        await this.$refs.tagForm.validate()
        this.addTagSubmit()
      } catch (error) {
        console.log(error)
      }
    },
    // 提交添加标签信息
    async addTagSubmit() {
      try {
        await addInsertSearch(this.tagForm)
        this.$message.success('添加标签成功')
        this.closeAddTagDialog()
        this.handleSelectionTagDialog()
      } catch (error) {
        console.log(error)
      }
    },

    // 删除标签
    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 delShopLabelList({ labelIds: 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>
