<template>
  <div class="right-list-toolbar">
    <el-toolbar>
      <el-button @click="addClickHandler" priv="Search.DicManager.Add">
        <i class="fa fa-plus"></i>新建
      </el-button>
      <el-col :span="10" class="search-box-r tool-search-box-r">
        <el-input v-model="search.word" @keyup.enter.native="searchClickHandler" placeholder="请输入关键字" class="search-bar-algin-toolbar"></el-input>
        <span class="search-icon"><i class="fa fa-search" @click="searchClickHandler" title="查询"></i></span>
      </el-col>
    </el-toolbar>
    <div class="scroll general-dictionary">
      <el-table
        :data="searchWord"
        :data-read-url="getData"
        :page-size="10"
        :auto-get-data="false"
        ref="table"
        tooltip-effect="dark"
        @selection-change="onSelectionChange"
        :multi-operates="multiOperates"
        >
        <el-table-column type="selection" width="60" align="center"></el-table-column>
        <el-table-column label="搜索词" align="left">
          <template slot-scope="scope">
            <el-button priv="Search.DicManager.Edit" type="text" class="table-title-button" :title="scope.row.word" @click.stop="editClickHandler(scope.row)">{{scope.row.word}}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="趋势" width="80" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.trend=='-'">{{scope.row.trend}}</span>
            <span v-else :style="{color:'#FA5555'}">
              <i :class="scope.row.trend"></i>
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="dayCount" label="今日搜索" width="80" align="center"></el-table-column>
        <el-table-column prop="weekCount" label="最近七日" width="80" align="center"></el-table-column>
        <el-table-column prop="searchCount" label="历史总搜索" width="100" align="center"></el-table-column>
        <el-table-column label="置顶" width="80" align="center">
          <template slot-scope="scope" v-if="scope.row.topIcon">
            <span :style="{'color':'#67C23A'}"><i :class="scope.row.topIcon"></i></span>
          </template>
        </el-table-column>
        <el-table-column prop="topTime" label="置顶时间" width="180" align="center">
          <template slot-scope="scope">
            {{scope.row.topTime | fixDateTime}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130" align="right">
          <template slot-scope="scope">
            <el-button @click.stop="editClickHandler(scope.row)"  priv="Search.DicManager.Edit" type="text" title="编辑">
              <i class="fa fa-edit f16"></i></el-button>
            <el-button @click.stop="stickClickHandler(scope.row)" priv="Search.DicManager.Top" :disabled="scope.row.topFlag=='Y'" type="text" title="置顶">
              <i class="fa fa-chevron-up f16"></i></el-button>
            <el-button @click.stop="unstickClickHandler(scope.row)" priv="Search.DicManager.NoTop" type="text"  title="取消置顶">
              <i class="fa fa-chevron-down f16"></i></el-button>
            <el-button @click.stop="delClickHandler(scope.row)" priv="Search.DicManager.Delete" type="text" title="删除">
              <i class="fa fa-times f16"></i></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 置顶搜索词 -->
    <word-top-dialog
      :show.sync="stick.isShowModal"
      :ids="stick.selectedIDs"
      @callback="afterStickDlgBack">
    </word-top-dialog>
  </div>
</template>
<script>
import './css/dicManager.css'
import util from '@src/common/util.js'
import Privilege from '@src/common/privilege.js'
import wordDialog from './wordDialog.vue'
import searchWordTopDialog from './searchWordTopDialog.vue'
export default {
  props: { tabName: String },
  filters: {
    fixDateTime: function(val) {
      if (!val) {
        return ''
      }
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      selectedRows: [], //  选中行
      submitLoading: false,
      unstickLoading: false,
      searchWord: [], //   搜索词统计请求数据
      stick: {
        // 置顶弹框变量
        isShowModal: false,
        selectedIDs: []
      },
      search: { word: '' }, //  搜索词查询
      multiOperates: [
        {
          label: '删除',
          value: 'delete',
          fn: rows => {
            this.deleteWords(rows)
          }
        }
      ]
    }
  },
  methods: {
    // 批量删除
    async deleteWords(rows) {
      if (Privilege.hasPriv(`Search.DicManager.Delete`) === false) {
        util.showError('您没有操作权限！')
        return
      }

      this.$confirm(`确认删除选择的<span class='icon-danger'>${rows.length}条</span>内容吗 ？`, {
        title: '提示',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      })
        .then(async r => {
          let IDs = _.map(rows, 'ID').join(',')

          let res = await axios.delete(`/ui/searchword/${IDs}`)
          util.showMessage(res)
          if (res.data.status === 1) {
            this.selectedRows = []
            this.loadSearchWordStatistics()
          }
        })
        .catch(err => { console.error(err) })
    },

    handleCommand(method) {
      if (method && typeof this[method] === 'function') {
        this[method]()
      } else {
        console.warn(`未找到改菜单对应的方法:${method}`)
      }
    },
    // 搜索词搜索点击事件
    searchClickHandler() {
      this.loadSearchWordStatistics()
    },
    // 置顶回调
    afterStickDlgBack() {
      this.selectedRows = []
      this.$refs.table.clearSelection()
      this.loadSearchWordStatistics()
    },
    // 搜索词置顶点击事件
    stickClickHandler(row) {
      let ids = row && row.ID ? [row.ID] : util.getSelectedIDs(this.selectedRows)
      if (!ids || !ids.length) {
        return
      }
      this.stick.isShowModal = true
      this.stick.selectedIDs = ids
    },
    // 搜索词取消置顶点击事件
    async unstickClickHandler(row) {
      let ids = row && row.ID ? [row.ID] : util.getSelectedIDs(this.selectedRows)
      if (!ids || !ids.length) {
        return
      }
      this.unstickLoading = !row.ID
      try {
        let res = await axios.put(`/ui/searchword/unstick/${ids.join()}`)
        this.unstickLoading = false
        util.showMessage(res)
        if (res.data.status === 1) {
          this.selectedRows = []
          this.$refs.table.clearSelection()
          this.loadSearchWordStatistics()
        }
      } catch (e) {
        this.unstickLoading = false
        util.showErrorNotification(e)
      }
    },
    // 删除搜索词点击事件
    async delClickHandler(row) {
      let ids = row && row.ID ? [row.ID] : util.getSelectedIDs(this.selectedRows)
      if (!ids || !ids.length) {
        return
      }
      try {
        await this.$confirm('确认删除？', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.delete(`/ui/searchword/${ids.join()}`)
        util.showMessage(res)
        if (res.data.status === 1) {
          this.selectedRows = []
          this.loadSearchWordStatistics()
        }
      } catch (e) {

      }
    },
    // 编辑搜索词点击事件
    editClickHandler(row) {
      if (!row.ID) {
        util.showErrorMessageBox('数据异常，请重新尝试！')
        return
      }
      let path = `${this.$route.path}/${row.ID}`.replace(/\/\//g, '/')
      this.$router.push({path: path})
    },
    // 新建搜索词点击事件
    addClickHandler() {
      let path = `${this.$route.path}/new`.replace(/\/\//g, '/')
      this.$router.push({path: path})
    },
    // 搜索词table选择多行事件
    onSelectionChange(selection) {
      this.selectedRows = selection
    },
    getData() {
      return [
        '/ui/searchword',
        {
          params: {
            searchName: this.search.word
          }
        }
      ]
    },
    // 加载搜索词统计
    async loadSearchWordStatistics() {
      this.$refs.table.getData()
    }
  },
  components: {
    'word-dialog': wordDialog,
    'word-top-dialog': searchWordTopDialog
  },
  watch: {
    tabName: function(val) {
      if (val === 'wordstat') {
        this.loadSearchWordStatistics()
      }
    }
  }
}
</script>
<style scoped>
.page-wrap {
  margin-top: 5px;
}
</style>
