<template>
  <div class="app-container">
    <div style="margin-top:10px">
      <el-input
        v-model="search"
        placeholder="输入分类名称进行搜索"
        style="width: 200px;"
        class="filter-item"
      />
      <el-button type="primary" @click="handleAdd" icon="el-icon-plus">新增</el-button>
    </div>
<el-table
      :data="tableData.filter(data => !search || data.name.toLowerCase().includes(search.toLowerCase()))"
      style="width: 100%;margin-top:10px;"
      border
      fit
      v-loading="listLoading"
      highlight-current-row
      max-height="600"
      row-key="id"
    >
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column align="center" label="名称">
        <template slot-scope="scope">{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column label="创建日期">
        <template slot-scope="scope">
          <span>{{ scope.row.create_time }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope)"
            icon="el-icon-edit"
            :disabled="!checkPermission(['subject_update'])"
          ></el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope)"
            icon="el-icon-delete"
            :disabled="!checkPermission(['subject_delete'])"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑分类':'新增分类'">
      <el-form
        :model="subject"
        label-width="80px"
        label-position="right"
        :rules="rule1"
        ref="commonForm"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="subject.name" placeholder="名称" />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirm('commonForm')">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getSubjectAll,
  createSubject,
  deleteSubject,
  updateSubject
} from "@/api/question";
import { deepClone } from "@/utils";
import checkPermission from "@/utils/permission";

const defaultObj = {
  id: "",
  name: ""
};
export default {
  data() {
    return {
      subject: defaultObj,
      search: "",
      tableData: [],
      listLoading: true,
      dialogVisible: false,
      dialogType: "new",
      rule1: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }]
      }
    };
  },
  computed: {},
  created() {
    this.getList();
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true;
      getSubjectAll().then(response => {
        this.tableData = response.data;
        this.listLoading = false;
      });
    },
    resetFilter() {
      this.search = ""
      this.getList();
    },
    handleAdd() {
      this.subject = Object.assign({}, defaultObj);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["commonForm"].clearValidate();
      });
    },
    handleEdit(scope) {
      this.subject = Object.assign({}, scope.row); // copy obj
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["commonForm"].clearValidate();
      });
    },
    handleDelete(scope) {
      this.$confirm("确认删除该分类吗?将丢失数据!", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error"
      })
        .then(async () => {
          await deleteSubject(scope.row.id);
          this.getList();
          this.$message({
            type: "success",
            message: "成功删除!"
          });
        })
        .catch(err => {
          // console.error(err);
        });
    },
    async confirm(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const isEdit = this.dialogType === "edit";
          if (isEdit) {
            updateSubject(this.subject.id, this.subject).then(
              () => {
                this.getList();
                this.dialogVisible = false;
                this.$message.success('成功')
              }
            );
          } else {
            createSubject(this.subject).then(res => {
              // this.subject = res.data
              // this.tableData.unshift(this.subject)
              this.getList();
              this.dialogVisible = false;
              this.$message.success('成功')
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
