<template>
  <div class="app-container">
    <div class="left">
      <el-input
        v-model="input"
        class="list"
        placeholder="批量添加, 换行分隔"
        :autosize="{ minRows: 13, maxRows: 13 }"
        type="textarea"
        clearable
      >
      </el-input>
      <div class="footer">
        <el-upload
          class="uploadBox"
          :show-file-list="false"
          :headers="headers"
          :on-success="upSuccess"
          :on-error="upError"
          action="/admin/common/sensitiveWord/upload"
          :before-upload="beforeAvatarUpload"
        >
          <el-button type="success" size="mini" plain>上传txt</el-button>
        </el-upload>
        <el-button
          type="success"
          size="mini"
          class="addBtn"
          :disabled="input ? false : true"
          @click="addBtn"
          >添加</el-button
        >
      </div>
    </div>
    <div class="right">
      <div class="tool">
        <el-input
          v-model="table.keyword"
          placeholder="请输入搜索内容"
          :clearable="true"
          class="keywords"
          size="mini"
          @keyup.enter.native="queryTable"
        />
        <el-button type="primary" size="mini" @click="queryTable"
          >查询</el-button
        >
        <el-button type="success" size="mini" plain @click="download"
          >下载txt</el-button
        >
      </div>
      <div class="table">
        <el-table v-loading="loading" :data="table.data" border>
          <el-table-column label="序号" width="60" type="index" />
          <el-table-column label="敏感词" prop="word" />
          <el-table-column label="添加时间" prop="createTime">
            <template slot-scope="scope">
              <span>{{ formatCreateTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="del(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          :total="table.total"
          :current-page="table.current"
          :page-size="this.table.size"
          style="margin-top: 8px;"
          layout="total, prev, pager, next, sizes"
          @size-change="sizeChange"
          @current-change="pageChange"
        />
      </div>
    </div>
  </div>
</template>
<script>
// import _ from 'lodash'
import moment from "moment";
import "./sensitive.scss";
import { mapGetters } from "vuex";
import { getToken } from "@/utils/auth";
import {
  addSensitive,
  getSensitiveList,
  delSensitive,
  download
} from "@/api/sensitive";

export default {
  name: "敏感词",
  data() {
    return {
      loading: true,
      input: "",
      list: {
        data: [],
        selected: []
      },
      inputValue: null,
      table: {
        //  表格数据
        data: [],
        // 分页
        current: 1,
        size: 10,
        total: 0,
        // 关键字
        keyword: ""
      },
      headers: {
        Authorization: "Bearer " + getToken()
      }
    };
  },
  computed: {
    ...mapGetters(["universalUpApi", "universalDownApi"])
  },
  created() {
    this.getList();
  },
  methods: {
    queryTable() {
      this.table.current = 1;
      this.getList();
    },
    async getList() {
      const params = {};
      // 关键字
      params.keyword = this.table.keyword;
      // 偏移量
      params.current = this.table.current;
      // 分页数量
      params.size = this.table.size;
      const data = await getSensitiveList(params);
      this.table.data = data.data.list;
      this.table.total = data.data.total;
      this.loading = false;
    },
    async download() {
      const data = await download();
      const fileBlob = data;
      const fileUrl = URL.createObjectURL(fileBlob);
      const a = document.createElement("a");
      a.setAttribute("download", "敏感词.txt");
      a.href = fileUrl;
      document.body.appendChild(a);
      const e = document.createEvent("MouseEvent");
      e.initEvent("click", false, false);
      a.dispatchEvent(e);
      a.remove();
      window.URL.revokeObjectURL(fileUrl);
    },
    // async inputCancel() {
    //   this.dialogFormVisible = false
    //   this.inputValue = null
    // },
    // async inputPost() {
    //   this.dialogFormVisible = false
    //   this.list.data = this.inputValue.split('\n')
    //   this.inputValue = null
    // },
    async addBtn() {
      const params = { words: this.input.split("\n") };
      const isEmpty = params.words.some(item => item.trim() === "");
      const isLimit = params.words.some(item => item.trim().length > 30);
      if (isEmpty) {
        this.$message({
          type: "error",
          message: "敏感词不能为空",
          center: true
        });
      } else if (isLimit) {
        this.$message({
          type: "error",
          message: "敏感词不能超过30字符",
          center: true
        });
      } else {
        const data = await addSensitive(params);
        if (data.code === 0) {
          this.$message({
            type: "success",
            message: "添加成功",
            center: true
          });
          this.input = "";
          this.getList();
        } else {
          this.$message({
            type: "error",
            message: data.message,
            center: true
          });
        }
      }
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "text/plain";
      const isLt2M = file.size / 1024 / 1024 < 1;

      if (!isJPG) {
        this.$message.error("上传敏感词列表只能以txt格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传敏感词列表不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },
    upSuccess(res, file, fileList) {
      console.log(res);
      if (res.code === 0) {
        this.$message({
          type: "success",
          message: `成功解析出${res.data.length}条!`
        });
        this.input = res.data.join("\n");
      } else {
        this.$message.error(res.message);
      }
    },
    upError(err, file, fileList) {
      console.log("失败~！");
      this.$message.error(err.message);
    },
    delChange(size) {
      if (size === undefined) {
        size = 1;
      }
      if (this.table.data.length === size && this.table.current !== 1) {
        this.table.current -= 1;
      }
    },
    del(row) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const res = await delSensitive({ id: row.id });
          if (res.code === 0) {
            this.$message({
              type: "success",
              message: `删除成功!`,
              center: true
            });
            this.delChange();
            this.getList();
          } else {
            this.$message.error(res.message);
          }
        })
        .catch(err => console.log(err));
    },
    /*
     * 更改分页数量
     */
    sizeChange(e) {
      this.table.current = 1;
      this.table.size = e;
      this.getList();
    },
    // 更改页码
    pageChange(e) {
      this.table.current = e;
      this.getList();
    },
    formatCreateTime(time) {
      return moment(time).format("YYYY-MM-DD HH:mm:ss");
    }
  }
};
</script>
