<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单词" prop="word">
        <el-input
          v-model="queryParams.word"
          placeholder="请输入单词"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" clearable size="small">
          <el-option
              v-for="dict in sensitiveTypeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['sensitive:word:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['sensitive:word:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['sensitive:word:export']"
        >导出</el-button>
      </el-col>-->
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="el-icon-s-operation"
            size="mini"
            @click="handleWordConfig"
        >敏感词配置</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="success"
            plain
            icon="el-icon-refresh"
            size="mini"
            @click="handleRefresh"
        >手动刷新词库</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="info"
            plain
            icon="el-icon-coffee-cup"
            size="mini"
            @click="handleTest"
        >测试文字</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-tag type="info">最近刷新词库时间: {{lastRefresh}}</el-tag>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="wordList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="敏感词" align="center" prop="word" />
      <el-table-column label="类型" align="center" prop="type">
        <template v-slot="scope">
          <cai-dict-tag :options="sensitiveTypeList" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="enableStatus" >
        <template v-slot="scope">
          <el-switch
              v-model="scope.row.enableStatus"
              :active-value="1"
              :inactive-value="0"
              @change="handleEnableStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="配置描述" align="center" prop="remark" show-overflow-tooltip/>
      <el-table-column label="更新时间" align="center" prop="updateTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['sensitive:word:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['sensitive:word:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改敏感词对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" clearable size="small">
            <el-option
                v-for="dict in sensitiveTypeList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="敏感词" prop="word">
          <el-input v-model="form.word" placeholder="请输入敏感词" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input type="textarea" :rows="2" v-model="form.remark" placeholder="请输入描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <word-test-dialog v-if="wordTestVisible" ref="wordTest"/>
    <word-config-dialog v-if="wordConfigVisible" ref="wordConfig"/>
  </div>
</template>

<script>
import { addWord, delWord, getWord, lastRefresh, listWord, refreshWord, updateWord } from '@/api/sensitive/word'
import { sensitiveTypeList } from '@/constant/statusMap'
import WordTestDialog from '@/views/sensitive/word/word-test-dialog.vue'
import WordConfigDialog from '@/views/sensitive/word/word-config-dialog.vue'

export default {
  name: "Word",
  components: {
    WordTestDialog,WordConfigDialog
  },
  data() {
    return {
      sensitiveTypeList,
      wordTestVisible: false,
      wordConfigVisible: false,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 敏感词表格数据
      wordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        word: undefined,
        type: undefined,
        enableStatus: undefined,
        operatorId: undefined,
      },
      lastRefresh: "",
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        word: [
          { required: true, message: "单词不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询敏感词列表 */
    getList() {
      this.loading = true;
      listWord(this.queryParams).then(response => {
        this.wordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      this.updateRefreshTime()
    },
    updateRefreshTime(){
      lastRefresh().then(response => {
        this.lastRefresh = response.data
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        word: undefined,
        type: 2,
        enableStatus: undefined,
        remark: undefined,
        operatorId: undefined,
        createTime: undefined,
        updateTime: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加敏感词";
    },
    handleTest() {
      this.wordTestVisible = true
      this.$nextTick(() => {
        this.$refs.wordTest.init()
      })
    },
    handleWordConfig() {
      this.wordConfigVisible = true
      this.$nextTick(() => {
        this.$refs.wordConfig.init()
      })
    },
    handleRefresh() {
      this.$modal.confirm('是否刷新敏感词库缓存？').then(() => {
        this.loading = true;
        return refreshWord();
      }).then(() => {
        this.loading = false;
        this.updateRefreshTime()
        this.$modal.msgSuccess("刷新成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getWord(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改敏感词";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateWord(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          } else {
            addWord(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).finally(() => {
              this.buttonLoading = false;
            });
          }
        }
      });
    },
    handleEnableStatusChange(row){
      let text = row.enableStatus === 0 ? '封禁' : '恢复'
      this.$confirm('确认要' + text + '[' + row.word + ']敏感词吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return updateWord({ id: row.id, enableStatus: row.enableStatus })
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function() {
        row.enableStatus = row.enableStatus === 1 ? 0 : 1
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除敏感词编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delWord(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('sensitive/word/export', {
        ...this.queryParams
      }, `word_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
