<template>
  <div class="right-list-toolbar">
    <el-toolbar>
      <el-button @click="addGeneralWordClickHandler" priv="Search.DicManager.AddGeneralWord">
        <i class="fa fa-plus"></i>新建
      </el-button>
      <el-dropdown @command="handleCommand">
        <el-button>
          <i class="fa fa-ellipsis-h" aria-hidden="true"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown" class="button-dropdown">
          <el-dropdown-item>
            <el-button @click="importGeneralWordClickHandler" type="text" priv="Search.DicManager.AddGeneralWord">
            <i class="fa fa-plus" aria-hidden="true"></i>通用词导入</el-button>
          </el-dropdown-item>
          <el-dropdown-item>
            <el-button @click="exportGeneralWordClickHandler" type="text" priv="Search.DicManager.ExportGeneralWord">
            <i class="fa fa-arrow-right" aria-hidden="true"></i>通用词导出</el-button>
          </el-dropdown-item>
          <el-dropdown-item>
            <el-button @click="clearGeneralWordClickHandler" type="text" priv="Search.DicManager.EmptyDB">
            <i class="fa fa-bolt fa-fw" aria-hidden="true"></i>清空词库</el-button>
          </el-dropdown-item>
          <el-dropdown-item>
            <el-button @click="recompilationClickHandler" type="text" priv="Search.DicManager.Recompilation">
            <i class="fa fa-refresh" aria-hidden="true"></i>重新编译词库</el-button>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </el-toolbar>
    <div class="scroll general-dictionary">
      <div class="bar">
        <div class="layout-data-search layout-data-search-3 layout-data-search-con">
          <el-input v-model="search.rootWord" @keyup.enter.native="searchClickHandler" placeholder="请输入根词"></el-input>
          <el-input v-model="search.synWord" @keyup.enter.native="searchClickHandler" placeholder="请输入同义词"></el-input>
          <el-checkbox v-model="search.accurate" style="margin-left: 5px;">
            <span class="layout-label">整词匹配</span>
          </el-checkbox>
          <el-button @click="searchClickHandler" title="搜索">
            <i class="fa fa-search"></i>搜索
          </el-button>
        </div>
      </div>
      <el-table :data="generalWordLib" :data-read-url="getData" :page-size="20" 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="根词">
          <template slot-scope="scope">
            <span priv="Search.DicManager.EditGeneralWord" type="text" class="table-title-button" :title="scope.row.rootWord" @click.stop="editGeneralWordClickHandler(scope.row)">{{scope.row.rootWord}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="同义词">
          <template slot-scope="scope">
            <span :title="scope.row.synWords">{{scope.row.synWords}}</span>
          </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" align="center"></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="120" align="right">
          <template slot-scope="scope">
            <el-button @click.stop="editGeneralWordClickHandler(scope.row)" type="text" title="编辑" priv="Search.DicManager.EditGeneralWord">
              <i class="fa fa-edit f16"></i>
            </el-button>
            <el-button @click.stop="publishGeneralWordClickHandler(scope.row)" type="text" title="发布" priv="Search.DicManager.PublishGeneralWord">
              <i class="fa fa-cloud-upload f16"></i>
            </el-button>
            <el-button @click.stop="delGeneralWordClickHandler(scope.row)" type="text" title="删除" priv="Search.DicManager.DeleteGeneralWord">
              <i class="fa fa-times f16"></i>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 导入词典弹框 -->
    <import-dic :show.sync="isShowModal" @dialog="dialog" @callback="afterImport">
    </import-dic>
  </div>
</template>
<script>
import './css/dicManager.css'
import util from '@src/common/util.js'
import Privilege from '@src/common/privilege.js'
import txtImport from './txtImport.vue'
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, //  发布加载
      clearLoading: false, //  清空加载
      generalWordLib: [], //   通用词库请求数据
      search: { rootWord: '', synWord: '', accurate: false }, //  查询参数
      isShowModal: false, //  导入弹框变量
      multiOperates: [
        {
          label: '删除',
          value: 'delete',
          fn: rows => {
            this.deleteGeneralWords(rows)
          }
        },
        {
          label: '发布',
          value: 'publish',
          fn: rows => {
            this.publishGeneralWords(rows)
          }
        }
      ]
    }
  },
  methods: {
    // 批量删除
    async deleteGeneralWords(rows) {
      if (Privilege.hasPriv(`Search.DicManager.DeleteGeneralWord`) === false) {
        util.showError('您没有操作权限！')
        return
      }

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

          let resp = await axios.delete(`/ui/generalword/${IDs}`)
          util.showMessage(resp)
          if (resp.data.status === 1) {
            this.selectedRows = []
            this.$refs.table.clearSelection()
            this.loadGeneralWordLib()
          }
        })
        .catch(err => { console.error(err) })
    },

    // 批量发布
    async publishGeneralWords(rows) {
      if (Privilege.hasPriv(`Search.DicManager.PublishGeneralWord`) === false) {
        util.showError('您没有操作权限！')
        return
      }

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

          let resp = await axios.put(`/ui/generalword/publish/${IDs}`)
          this.publishLoading = false
          util.showMessage(resp)
          if (resp.data.status === 1) {
            this.selectedRows = []
            this.$refs.table.clearSelection()
            this.loadGeneralWordLib()
          }
        })
        .catch(err => { console.error(err) })
    },

    handleCommand(method) {
      if (method && typeof this[method] === 'function') {
        this[method]()
      } else {
        console.warn(`未找到改菜单对应的方法:${method}`)
      }
    },
    // 导入成功后回调
    async afterImport(taskID) {
      await util.showProgress(taskID, '词典导入')
      this.loadGeneralWordLib()
    },
    // 导出词库点击事件
    async exportGeneralWordClickHandler() {
      try {
        let res = await axios.get('/ui/dictionary/export')
        if (res.data.status === 1) {
          await util.showProgress(res.data.data.taskid, '通用词典导出')
          window.location.href = `ui/dictionary/download?fileName=${res.data.data.fileName}`
        } else {
          util.showMessage(res)
        }
      } catch (e) {
        // util.showErrorNotification(e)

      }
    },
    // 导入通用词库点击事件
    importGeneralWordClickHandler() {
      this.isShowModal = true
    },
    // 重新编译词典点击事件
    async recompilationClickHandler() {
      try {
        await this.$confirm('确认要重新编译吗?', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.get('/ui/generalword/recompilation')
        if (res.data.status === 1) {
          await util.showProgress(res.data.data.taskID, '重新编译词典')
          this.loadGeneralWordLib()
        } else {
          util.showMessage(res)
        }
      } catch (e) {

      }
    },
    // 清空词库点击事件
    async clearGeneralWordClickHandler() {
      this.clearLoading = true
      try {
        await this.$confirm('确定清空通用词库?', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.put('/ui/generalword/clear')
        this.clearLoading = false
        util.showMessage(res)
        if (res.data.status === 1) {
          this.loadGeneralWordLib()
        }
      } catch (e) {
        this.clearLoading = false
      }
    },
    // 发布通用词点击事件
    async publishGeneralWordClickHandler(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/generalword/publish/${ids.join()}`)
        this.publishLoading = false
        util.showMessage(res)
        if (res.data.status === 1) {
          this.selectedRows = []
          this.$refs.table.clearSelection()
          this.loadGeneralWordLib()
        }
      } catch (e) {
        this.publishLoading = false
        // util.showErrorNotification(e)
      }
    },
    // 删除通用词点击事件
    async delGeneralWordClickHandler(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/generalword/${ids.join()}`)
        util.showMessage(res)
        if (res.data.status === 1) {
          this.selectedRows = []
          this.$refs.table.clearSelection()
          this.loadGeneralWordLib()
        }
      } catch (e) {

      }
    },
    // 添加通用词事件
    addGeneralWordClickHandler() {
      let path = `${this.$route.path}/new`.replace(/\/\//g, '/')
      this.$router.push({path: path})
    },
    // 编辑通用词事件
    editGeneralWordClickHandler(row) {
      if (!row.ID) {
        util.showErrorMessageBox('数据异常，请重新尝试！')
        return
      }
      let path = `${this.$route.path}/${row.ID}`.replace(/\/\//g, '/')
      this.$router.push({path: path})
    },
    getData() {
      let params = {
        rootWord: this.search.rootWord,
        synWords: this.search.synWord,
        accurate: this.search.accurate
      }
      return ['/ui/generalword', { params: params }]
    },
    // 加载通用词库
    async loadGeneralWordLib() {
      this.$refs.table.getData()
    },
    // 校验通用词库数据库是否为空
    async validateGeneralWordDB() {
      let res = await axios.get('/ui/generalword/validatedb', {
        params: { type: 1 }
      })
      if (res.data.status === 1) {
        this.initGeneralWordDB()
      } else {
        this.loadGeneralWordLib()
      }
    },
    // 初始化通用词库
    async initGeneralWordDB() {
      try {
        await this.$confirm('您的通用词库为空需要初始化，点击确定开始。', '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        let res = await axios.get('/ui/dictionary/initdb', {
          params: { type: 1 }
        })
        if (res.data.status === 1) {
          await util.showProgress(res.data.data.taskID, '通用词库初始化')
          this.loadGeneralWordLib()
        } else {
          util.showMessage(res)
        }
      } catch (e) {

      }
    },
    // 通用词库查询点击事件
    searchClickHandler() {
      this.loadGeneralWordLib()
    },
    // 通用词多行选中事件
    onSelectionChange(selection) {
      this.selectedRows = selection
    },
    // 消息Dialog封装
    dialog(msg) {
      this.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      })
    }
  },
  components: {
    'import-dic': txtImport
  },
  watch: {
    tabName(val) {
      if (val === 'dic') {
        this.validateGeneralWordDB()
      }
    }
  },
  created() {
    this.validateGeneralWordDB()
  }
}
</script>
<style>
.general-dictionary .el-table .cell {
  font-size: 13px;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}
</style>
