<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="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.parentLabel" clearable @change="getList">
          <el-option value="" label="请选择" />
          <el-option :value="1" label="是" />
          <el-option :value="0" label="否" />
        </el-select>
      </div>
      <div class="filter-control">
        <el-button type="primary" @click="getList"> 查询 </el-button>
        <el-button v-permission="'tag:list:add'" type="primary" @click="handleOerate('add')"> 添加标签 </el-button>
        <el-button v-permission="'tag:list:del'" type="danger" :disabled="disabled" @click="handleDeleteTag">
          批量删除
        </el-button>
        <el-button v-permission="'tag:list:improt'" type="primary" @click="importDialog = true"> 导入 </el-button>
        <el-button v-permission="'tag:list:export'" type="primary" :disabled="disabled" @click="handleExport">
          导出
        </el-button>
        <el-button v-permission="'tag:list:improt'" type="primary" @click="handleDownloadTemp">
          下载导入模板
        </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 prop="keyword" label="下拉搜索框联动" width="180" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.linkageStatus" @change="handleStatusChange(scope.row)" />
        </template>
      </el-table-column>
      <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 width="100" label="是否为父标签" align="center">
        <template slot-scope="{ row }">
          <el-tag v-if="row.parentLabel === 1" type="success" size="small">是</el-tag>
          <el-tag v-else type="warning" 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="240">
        <template slot-scope="{ row }">
          <el-button type="primary" size="mini" @click="handleOerate('edit', row)"> 编辑 </el-button>
          <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.sync="listQuery.pageNum"
      :limit.sync="listQuery.pageSize"
      @pagination="getStatekeywordList"
    />

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

    <!-- 导入标签 -->
    <el-dialog
      title="导入标签"
      :visible.sync="importDialog"
      width="460px"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <el-form ref="importForm" :model="importForm" :rules="importFormRules">
        <el-form-item label="上传文件：" prop="fileUrl">
          <el-upload
            ref="upload"
            accept=".xlsx, .xls"
            action="https://jsonplaceholder.typicode.com/posts/"
            :limit="1"
            :file-list="fileList"
            :on-success="handleUploadSuccess"
            :on-remove="handleUploadRemove"
            :on-change="handleUploadChange"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary"> 选取文件 </el-button>
            <div slot="tip" class="el-upload__tip">只能上传.xlsx, .xls文件</div>
          </el-upload>
          <input v-show="false" v-model="importForm.fileUrl" type="text" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="closeImportDialog"> 取 消 </el-button>
        <el-button v-debounce="handleImportConfirm" type="primary"> 导 入 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import SearchModel from '@/components/SearchModel'
import { downloadWithUrl, parseTime } from '@/utils'
import {
  deleteTrendsLabel,
  getStatekeywordList,
  importKeywordLabelXlsx,
  findLinkageStatus
} from '@/api/library/keyword'
import { export_json_to_excel } from '@/vendor/Export2Excel'
import pickerOptions from '@/utils/time-picker.js'
export default {
  components: { SearchModel },
  data() {
    return {
      isLoading: true,
      pickerOptions,
      time: '',
      listQuery: {
        keyword: '',
        beginTime: '',
        dynamicStatus: 0,
        parentLabel: '',
        endTime: '',
        serviceProviderId: '',
        pageNum: 1,
        pageSize: 20
      },
      list: [],
      total: 0,
      currentList: [],
      searchDialog: false,
      visibleKeyword: '',
      exportKeywordList: [],
      importDialog: false,
      fileList: [],
      importForm: {
        fileUrl: ''
      },
      importFormRules: {
        fileUrl: [{ required: true, message: '文件不能为空', trigger: ['change'] }]
      }
    }
  },
  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.getStatekeywordList()
          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.getStatekeywordList()
      }
    },

    // 获取标签列表
    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.getStatekeywordList()
    },

    // 获取标签列表
    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,
          parentLabel: i.parentLabel
        }))
        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
    },
    // 添加标签
    handleOerate(type, row) {
      if (type === 'add') {
        this.$router.push({
          path: '/library/tag/tag-form',
          query: { type: type }
        })
      } else {
        this.$router.push({
          path: '/library/tag/tag-form',
          query: { id: row.id, type: type }
        })
      }
    },
    // 删除标签
    async handleDeleteTag(row) {
      try {
        let confirmText = ''
        if (row && row.parentLabel === 1) {
          confirmText = '该标签为父标签删除后将失去和子标签的联系,确定删除吗?'
        } else {
          const parentLabel = []
          this.currentList.forEach((el) => {
            if (el.parentLabel === 1) {
              parentLabel.push(`【${el.keyword}】`)
              console.log('parentLabel', parentLabel)
            }
          })
          if (parentLabel.length > 0) {
            confirmText = `所选标签中含有父标签,删除后将失去和子标签的联系,确定删除吗?`
          } else {
            confirmText = '确定删除已选标签？'
          }
        }
        await this.$confirm(confirmText, {
          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)
      }
    },

    // 导入标签
    async handleImport() {},

    // 导入标签取消
    closeImportDialog() {
      this.$refs.importForm.resetFields()
      this.importDialog = false
    },

    // 导入标签确定
    async handleImportConfirm() {
      console.log(1)
      try {
        await this.$refs.importForm.validate()
        this.importSumbit()
      } catch (error) {
        console.log(error)
      }
    },

    async importSumbit() {
      const file = this.fileList.length > 0 && this.fileList[0]
      if (!file) return
      try {
        const formData = new FormData()
        this.fileList = []
        this.importDialog = false
        formData.append('keywordFile', file.raw)
        await importKeywordLabelXlsx(formData)
        this.$message.success('导入标签成功')
        this.getList()
      } catch (error) {
        console.log(error)
      }
    },

    // 导出
    async handleExport() {
      try {
        await this.$confirm('确定将所选标签导出为xlsx？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        // 导出数据格式化
        const filterVal = ['index', 'keyword', 'frequency', 'fromSearch', 'searchTime', 'addTime']
        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', 'addTime'].includes(key)) {
            return parseTime(v[key])
          }
          if (key === 'index') return index + 1
          if (key === 'fromSearch') {
            const t = ['单个添加', '系统推荐', '导入']
            return t[v[key] - 1]
          }
          return v[key]
        })
      )
    },

    // 文件上传成功
    handleUploadSuccess(response, file, fileList) {
      this.importForm.fileUrl = response.url
      this.fileList = fileList
    },

    // 上传文件删除
    handleUploadRemove(file, fileList) {
      this.fileList = fileList
    },

    handleUploadChange(file, fileList) {
      this.fileList = fileList
      this.importForm.fileUrl = file.name
    },

    indexMethod(index) {
      return index + this.listQuery.pageSize * (this.listQuery.pageNum - 1) + 1
    },

    // 导入模板
    handleDownloadTemp() {
      downloadWithUrl('/temp/tag-import.xlsx', '标签库.xlsx')
    }
  }
}
</script>

<style></style>
