<template>
  <div class="right-list-toolbar">
    <el-toolbar>
      <el-button @click="addClickHandler" priv="Search.DicManager.AddStopWord">
        <i class="fa fa-plus"></i>添加停用词
      </el-button>
      <el-button @click="recompilationClickHandler" priv="Search.DicManager.RecompilationStopWordDic">
        <i class="fa fa-refresh" ></i>重新编译停用词典
      </el-button>
      <el-col :span="10" class="search-box-r tool-search-box-r">
        <el-input v-model="search.rootWord" @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="stopWord"
        ref="table"
        :data-read-url="getData"
        :page-size="20"
        :auto-get-data="false"
        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="停用词">
          <template slot-scope="scope">
            <el-button priv="Search.DicManager.EditStopWord" type="text" class="table-title-button" :title="scope.row.rootWord" @click.stop="editClickHandler(scope.row)">{{scope.row.rootWord}}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="statusName" label="状态" width="100" align="center"></el-table-column>
        <el-table-column prop="addUser" label="添加人" width="120"></el-table-column>
        <el-table-column prop="addTime" label="添加时间" width="180" align="center">
          <template slot-scope="scope">
            {{scope.row.addTime | 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.EditStopWord" type="text" title="编辑">
              <i class="fa fa-edit f16"></i></el-button>
            <el-button @click.stop="publishClickHandler(scope.row)" priv="Search.DicManager.PublishStopWord" :disabled="scope.row.status=='3'" type="text" title="发布">
              <i class="fa fa-cloud-upload f16"></i></el-button>
            <el-button @click.stop="offlineClickHandler(scope.row)" priv="Search.DicManager.OfflineStopWord" :disabled="scope.row.status=='4'" type="text" title="下线">
              <i class="fa fa-cloud-download f16"></i></el-button>
            <el-button @click.stop="delClickHandler(scope.row)" priv="Search.DicManager.DeleteStopWord" type="text" title="删除">
              <i class="fa fa-times f16"></i></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>
<script>

import './css/dicManager.css'
import util from '@src/common/util.js'
import Privilege from '@src/common/privilege.js'
export default {
  props: { tabName: String },
  filters: {
    fixDateTime: function(val) {
      return util.formatDate(val, 'yyyy-MM-dd HH:mm')
    }
  },
  data() {
    return {
      selectedRows: [], //  选中行
      submitLoading: false,
      publishLoading: false,
      offlineLoading: false,
      stopWord: [], //  停用词请求数据
      search: { rootWord: '' }, //  查询条件
      multiOperates: [
        {
          label: '删除',
          value: 'delete',
          fn: rows => {
            this.deleteStopWords(rows)
          }
        },
        {
          label: '下线',
          value: 'offLine',
          fn: rows => {
            this.offLineStopWords(rows)
          }
        },
        {
          label: '发布',
          value: 'publish',
          fn: rows => {
            self.publishStopWords(rows)
          }
        }
      ]
    }
  },
  methods: {
    // 批量删除
    async deleteStopWords(rows) {
      if (Privilege.hasPriv(`Search.DicManager.DeleteStopWord`) === 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/stopword/${IDs}`)
          util.showMessage(res)
          if (res.data.status === 1) {
            this.selectedRows = []
            this.loadStopWord()
          }
        })
        .catch(err => { console.error(err) })
    },

    // 批量下线
    async offLineStopWords(rows) {
      if (Privilege.hasPriv(`Search.DicManager.OfflineStopWord`) === 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.put(`/ui/stopword/offline/${IDs}`)
          this.offlineLoading = false
          util.showMessage(res)
          if (res.data.status === 1) {
            this.selectedRows = []
            this.$refs.table.clearSelection()
            this.loadStopWord()
          }
        })
        .catch(err => { console.error(err) })
    },

    // 批量发布
    async publishStopWords(rows) {
      if (Privilege.hasPriv(`Search.DicManager.PublishStopWord`) === 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.put(`/ui/stopword/publish/${IDs}`)
          this.publishLoading = false
          util.showMessage(res)
          if (res.data.status === 1) {
            this.selectedRows = []
            this.$refs.table.clearSelection()
            this.loadStopWord()
          }
        })
        .catch(err => { console.error(err) })
    },

    handleCommand(method) {
      if (method && typeof this[method] === 'function') {
        this[method]()
      } else {
        console.warn(`未找到改菜单对应的方法:${method}`)
      }
    },
    searchClickHandler() {
      this.loadStopWord()
    },
    // 重新编译词典点击事件
    async recompilationClickHandler() {
      try {
        await this.$confirm('确认要重新编译吗?', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.get('/ui/stopword/recompilation')
        if (res.data.status === 1) {
          await util.showProgress(res.data.data.taskID, '正在重新编译词典...')
          this.loadStopWord()
        } else {
          util.showMessage(res)
        }
      } catch (e) {

      }
    },

    // 添加停用词点击事件
    addClickHandler() {
      let path = `${this.$route.path}/new`.replace(/\/\//g, '/')
      this.$router.push({path: path})
    },
    // 编辑停用词点击事件
    editClickHandler(row) {
      if (!row.ID) {
        util.showErrorMessageBox('数据异常，请重新尝试！')
        return
      }
      let path = `${this.$route.path}/${row.ID}`.replace(/\/\//g, '/')
      this.$router.push({path: path})
    },
    // 下线停用词点击事件
    async offlineClickHandler(row) {
      let ids = row && row.ID ? [row.ID] : util.getSelectedIDs(this.selectedRows)
      if (!ids || !ids.length) {
        return
      }
      this.offlineLoading = !row.ID
      try {
        let res = await axios.put(`/ui/stopword/offline/${ids.join()}`)
        this.offlineLoading = false
        util.showMessage(res)
        if (res.data.status === 1) {
          this.selectedRows = []
          this.$refs.table.clearSelection()
          this.loadStopWord()
        }
      } catch (e) {
        this.offlineLoading = false
        // util.showErrorNotification(e)
      }
    },
    // 发布停用词点击事件
    async publishClickHandler(row) {
      let ids = row && row.ID ? [row.ID] : util.getSelectedIDs(this.selectedRows)
      if (!ids || !ids.length) {
        return
      }
      this.publishLoading = !row.ID
      try {
        let res = await axios.put(`/ui/stopword/publish/${ids.join()}`)
        this.publishLoading = false
        util.showMessage(res)
        if (res.data.status === 1) {
          this.selectedRows = []
          this.$refs.table.clearSelection()
          this.loadStopWord()
        }
      } catch (e) {
        this.publishLoading = 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/stopword/${ids.join()}`)
        util.showMessage(res)
        if (res.data.status === 1) {
          this.selectedRows = []
          this.loadStopWord()
        }
      } catch (e) {

      }
    },
    // 停用词table多行选中事件
    onSelectionChange(selection) {
      this.selectedRows = selection
    },
    getData() {
      return [
        '/ui/stopword',
        {
          params: {
            rootWord: this.search.rootWord
          }
        }
      ]
    },
    //  加载停用词
    async loadStopWord() {
      this.$refs.table.getData()
    },
    // 校验停用词库数据库是否为空
    async validateGeneralWordDB() {
      let res = await axios.get('/ui/generalword/validatedb', {
        params: { type: 4 }
      })
      if (res.data.status === 1) {
        this.initGeneralWordDB()
      } else {
        this.loadStopWord()
      }
    },
    // 初始化停用词库
    async initGeneralWordDB() {
      try {
        await this.$confirm('您的停用词库为空需要初始化，点击确定开始。', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.get('/ui/dictionary/initdb', {
          params: { type: 4 }
        })
        if (res.data.status === 1) {
          await util.showProgress(res.data.data.taskID, '停用词库初始化')
          this.loadStopWord()
        } else {
          util.showResponseMessage(res.data)
        }
      } catch (e) {

      }
    }
  },
  watch: {
    tabName: function(val) {
      if (val === 'stopword') {
        this.validateGeneralWordDB()
      }
    }
  }
}
</script>
