<template>
  <el-dialog
    class="modify-exam-student"
    :visible.sync="modalIsShow"
    title="选择考试对象"
    top="10px"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <div class="mb-4 tab-btns">
      <el-button
        v-for="(val, key) in EXAM_OBJECT_TYPE"
        :key="key"
        size="medium"
        :type="examObjectType === key ? 'primary' : 'default'"
        @click="selectMenu(key)"
        >{{ val }}
      </el-button>
    </div>

    <div v-if="isExportType">
      <el-button type="success" icon="el-icon-download"
        ><a :href="downloadUrl" :download="dfilename">模板下载</a></el-button
      >
      <upload-button
        btn-icon="el-icon-circle-plus-outline"
        btn-content="批量导入"
        btn-type="success"
        :upload-url="uploadUrl"
        :format="['xls', 'xlsx']"
        accept=".xls,.xlsx"
        @valid-error="validError"
        @upload-success="uploadSuccess"
      >
      </upload-button>
    </div>

    <el-row v-else type="flex" :gutter="10">
      <el-col :span="12">
        <h3 class="user-part-title">班级/学生</h3>
        <el-tree
          ref="UserTree"
          :data="userTree"
          node-key="id"
          show-checkbox
          highlight-current
          :props="defaultProps"
          @check-change="checkChange"
        >
        </el-tree>
      </el-col>
      <el-col :span="12">
        <div class="user-part-title">已选范围</div>
        <el-tree
          ref="UserSelectedTree"
          :data="selectedUsers"
          node-key="id"
          show-checkbox
          highlight-current
          :props="defaultProps"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <el-button
              v-if="data.isUser"
              type="text"
              icon="el-icon-remove"
              @click="removeSelectStudent(node, data)"
            >
              {{ data.label }}
            </el-button>
          </span>
        </el-tree>
      </el-col>
    </el-row>
    <p v-show="!selectValid" class="tips-info tips-error"></p>

    <div slot="footer">
      <el-button type="primary" :disabled="!selectValid" @click="submit"
        >确认</el-button
      >
      <el-button @click="cancel">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { uploadOrFindExamTaskStudent } from "../../api";
import UploadButton from "@/components/UploadButton";

const EXAM_OBJECT_TYPE = {
  TEACH_CLAZZ_STUDENT: "我教课程选择",
  BASIC_CLAZZ_STUDENT: "学生库选择",
  IMPORT_STUDENT: "批量导入"
};

export default {
  name: "modify-exam-student",
  props: {
    selectedIds: {
      type: Array,
      default() {
        return [];
      }
    },
    courseId: {
      type: String,
      default: ""
    }
  },
  components: { UploadButton },
  data() {
    return {
      modalIsShow: false,
      examObjectType: "TEACH_CLAZZ_STUDENT",
      EXAM_OBJECT_TYPE,
      dataTree: {
        TEACH_CLAZZ_STUDENT: [],
        BASIC_CLAZZ_STUDENT: []
      },
      userTree: [],
      selectedUsers: [],
      selectedUserIds: [],
      selectValid: true,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // import
      uploadUrl: "/api/admin/exam/task/find_exam_task_student_object",
      downloadUrl: "/temps/studentTemplate.xlsx",
      dfilename: "学生导入模板.xlsx"
    };
  },
  computed: {
    isExportType() {
      return this.examObjectType === "IMPORT_STUDENT";
    }
  },
  methods: {
    async getStudents(examObjectType) {
      let datas = {
        examObjectType: examObjectType || this.examObjectType
      };
      if (this.examObjectType === "TEACH_CLAZZ_STUDENT")
        datas.basicCourseId = this.courseId;
      const data = await uploadOrFindExamTaskStudent(datas);
      this.userTree = this.dataTree[
        this.examObjectType
      ] = this.parseStudentData(data);
    },
    parseStudentData(data) {
      return data.map(item => {
        let nitem = {
          id: item.clazzId,
          label: item.clazzName,
          classId: item.clazzId,
          className: item.clazzName,
          studentClazzType: item.studentClazzType,
          children: []
        };

        nitem.children = item.studentInfoList.map(elem => {
          return {
            ...elem,
            isUser: true,
            id: elem.studentId,
            label: elem.studentName,
            studentClazzType: item.studentClazzType
          };
        });

        return nitem;
      });
    },
    selectMenu(val) {
      this.examObjectType = val;
      if (val === "IMPORT_STUDENT") return;

      this.selectedUserIds = [];
      this.selectedUsers = [];

      if (this.dataTree[val].length) {
        this.userTree = this.dataTree[val];
      } else {
        this.getStudents();
      }
    },
    checkChange() {
      let selectedNode = this.$refs.UserTree.getCheckedNodes(false, true);
      console.log(selectedNode);
    },
    removeSelectStudent(node) {
      console.log(node);

      this.$refs.UserSelectedTree.remove(node);
    },
    async visibleChange() {
      if (this.examObjectType === "TEACH_CLAZZ_STUDENT") {
        await this.getStudents();
      }
      this.$refs.UserTree.setCheckedKeys(this.selectedIds);
      this.$nextTick(() => {
        this.checkChange();
      });
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    // import
    validError(errorData) {
      this.$message.error(errorData.message);
    },
    uploadSuccess(res) {
      console.log(res);
    },
    submit() {
      if (!this.selectedUsers.length) {
        this.$message.error("请选择考试对象");
        return;
      }
      this.$emit("modified", this.selectedUsers);
      this.cancel();
    }
  }
};
</script>
