<template>
  <div class="app-container">
    <div style="margin-top:10px">
      <el-select
        v-model="listQuery.pid"
        placeholder="所属学科"
        clearable
        style="width: 200px"
        class="filter-item"
        @change="handleFilter"
      >
        <el-option
          v-for="item in subjectData"
          :key="item.key"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" @click="handleAdd" icon="el-icon-plus">新增</el-button>
    </div>
<el-table
      :data="tableData"
      style="width: 100%;margin-top:10px;"
      border
      fit
      v-loading="listLoading"
      highlight-current-row
      max-height="600"
    >
      <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 align="center" label="所属学科">
        <template slot-scope="scope"><el-tag >{{scope.row.subject_name}}</el-tag></template>
      </el-table-column>
      <el-table-column align="center" label="科目类型">
        <template slot-scope="scope"><el-tag >{{scope.row.type}}</el-tag></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(['questioncat_update'])"
          ></el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope)"
            icon="el-icon-delete"
            :disabled="!checkPermission(['questioncat_delete'])"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑分类':'新增分类'">
      <el-form
        :model="questioncat"
        label-width="80px"
        label-position="right"
        :rules="rule1"
        ref="commonForm"
      >
        <el-form-item label="名称" prop="name">
          <el-input v-model="questioncat.name" placeholder="名称" />
        </el-form-item>
        <el-form-item label="类型" prop="pid">
          <el-select v-model="questioncat.type" placeholder="请选择" style="width:100%">
    <el-option
      v-for="item in typeData"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
        </el-form-item>
        <el-form-item label="学科" prop="pid">
          <el-select v-model="questioncat.pid" placeholder="请选择" style="width:100%">
    <el-option
      v-for="item in subjectData"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
        </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,
  getQuestioncatList,
  createQuestioncat,
  deleteQuestioncat,
  updateQuestioncat
} from "@/api/question";
import { genTree, deepClone } from "@/utils";
import checkPermission from "@/utils/permission";
import Pagination from "@/components/Pagination";

const defaultObj = {
  id: "",
  name: "",
  pid: ""
};
const listQuery = {
  page: 1,
  limit: 20
};
export default {
  components: { Pagination },
  data() {
    return {
      questioncat: defaultObj,
      search: "",
      total: 0,
      listQuery: listQuery,
      tableData: [],
      subjectData: [],
      listLoading: true,
      dialogVisible: false,
      dialogType: "new",
      rule1: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        pid: [{ required: true, message: "请选择分类", trigger: "change" }]
      },
      typeData: [{
          value: '公共',
          label: '公共'
        }, {
          value: '专业',
          label: '专业'
        }],
    };
  },
  computed: {},
  created() {
    this.getList();
    this.getSubjectAll();
  },
  methods: {
    checkPermission,
    getList(query = this.listQuery) {
      this.listLoading = true;
      getQuestioncatList(query).then(response => {
        this.tableData = response.data.results;
        this.total = response.data.count;
        this.listLoading = false;
      });
    },
    getSubjectAll() {
      getSubjectAll().then(response => {
        this.subjectData = genTree(response.data);
      });
    },
    resetFilter() {
      this.search = ""
      this.listQuery = listQuery
      this.getList();
    },
    handleFilter() {
      this.getList();
    },
    // handleSearch() {
    //   this.getList({ search: this.search });
    // },
    handleAdd() {
      this.questioncat = Object.assign({}, defaultObj);
      this.dialogType = "new";
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["commonForm"].clearValidate();
      });
    },
    handleEdit(scope) {
      this.questioncat = 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 deleteQuestioncat(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) {
            updateQuestioncat(this.questioncat.id, this.questioncat).then(
              () => {
                this.getList();
                this.dialogVisible = false;
                this.$message.success('成功')
              }
            );
          } else {
            createQuestioncat(this.questioncat).then(res => {
              // this.questioncat = res.data
              // this.tableData.unshift(this.questioncat)
              this.getList();
              this.dialogVisible = false;
              this.$message.success('成功')
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
