<template>
  <el-dialog
    class="select-analysis-paper page-dialog"
    :visible.sync="modalIsShow"
    title="选择分析试卷"
    top="10px"
    width="80%"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    append-to-body
    @opened="visibleChange"
  >
    <div class="part-box part-box-filter part-box-flex">
      <el-form ref="FilterForm" label-position="left" label-width="55px" inline>
        <!-- <el-form-item label="考试：">
          <exam-select
            v-model="filter.examId"
            :semester-id="filter.semesterId"
            placeholder="考试"
            disabled
            @change="examChange"
          ></exam-select>
        </el-form-item> -->
        <el-form-item label="学院：">
          <!-- <college-select
            v-model="filter.collegeId"
            placeholder="学院"
          ></college-select> -->
          <el-select
            v-model="filter.collegeId"
            class="college-select"
            placeholder="学院"
            filterable
            clearable
          >
            <el-option
              v-for="item in collegeList"
              :key="item.id"
              :value="item.id"
              :label="item.name"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="课程：">
          <course-select
            v-model="filter.courseId"
            placeholder="课程"
            :semester-id="filter.semesterId"
            :exam-id="filter.examId"
          ></course-select>
        </el-form-item>
        <el-form-item>
          <el-input
            v-model.trim="filter.teacherName"
            placeholder="请输入命题老师姓名"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!filter.examId" @click="search"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>

    <div class="mb-4 tab-btns">
      <el-button
        v-for="tab in tabs"
        :key="tab.val"
        size="medium"
        :type="curTab == tab.val ? 'primary' : 'default'"
        @click="selectMenu(tab.val)"
        >{{ tab.name }}
        <span v-if="tab.val === 'selected'">({{ selectedPapers.length }})</span>
      </el-button>
    </div>

    <div v-if="curTab === 'query'" class="part-box part-box-pad">
      <el-table
        ref="TableList"
        :data="dataList"
        key="query"
        @select="handleSelectionChange"
        @select-all="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          fixed="left"
          width="55"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="semesterName"
          label="学期"
          min-width="210"
        ></el-table-column>
        <el-table-column prop="examName" label="考试" min-width="160">
        </el-table-column>
        <el-table-column prop="courseCode" label="课程(代码)" min-width="120">
          <span slot-scope="scope">
            {{ scope.row.courseName }}（{{ scope.row.courseCode }}）
          </span>
        </el-table-column>
        <el-table-column prop="teachCollegeName" label="开课学院">
        </el-table-column>
        <el-table-column prop="teacherName" label="命题老师"> </el-table-column>
        <el-table-column prop="paperNumber" label="试卷编号"> </el-table-column>
        <el-table-column prop="paperType" label="试卷类型" width="80">
        </el-table-column>
      </el-table>
      <div class="part-page">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :pager-count="5"
          :current-page="current"
          :total="total"
          :page-size="size"
          @current-change="toPage"
          @size-change="pageSizeChange"
        >
        </el-pagination>
      </div>
    </div>
    <div v-else class="part-box part-box-pad">
      <el-table ref="SelectedTableList" key="select" :data="selectedPapers">
        <el-table-column
          prop="semesterName"
          label="学期"
          min-width="210"
        ></el-table-column>
        <el-table-column prop="examName" label="考试" min-width="160">
        </el-table-column>
        <el-table-column prop="courseCode" label="课程(代码)" min-width="120">
          <span slot-scope="scope">
            {{ scope.row.courseName }}（{{ scope.row.courseCode }}）
          </span>
        </el-table-column>
        <el-table-column prop="teachCollegeName" label="开课学院">
        </el-table-column>
        <el-table-column prop="teacherName" label="命题老师"> </el-table-column>
        <el-table-column prop="paperNumber" label="试卷编号"> </el-table-column>
        <el-table-column prop="paperType" label="试卷类型" width="80">
        </el-table-column>
        <el-table-column
          class-name="action-column"
          label="操作"
          width="80px"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              class="btn-danger"
              type="text"
              @click="toDelete(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div slot="footer">
      <el-button type="primary" :loading="isSubmit" @click="submit"
        >确认</el-button
      >
      <el-button type="danger" @click="cancel" plain>取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { teachCollegeList } from "../../base/api";
import { analysisPaperList, addAnalysisBatchPaper } from "../api";
const initFilter = {
  batchId: "",
  semesterId: "",
  examId: "",
  collegeId: "",
  courseId: "",
  teacherName: "",
};

export default {
  name: "select-analysis-paper",
  props: {
    batch: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      modalIsShow: false,
      filter: {
        ...initFilter,
      },
      current: 1,
      size: this.GLOBAL.pageSize,
      total: 0,
      curTab: "query",
      tabs: [
        {
          name: "列表",
          val: "query",
        },
        {
          name: "已选",
          val: "selected",
        },
      ],
      collegeList: [],
      searchList: [],
      dataList: [],
      selectedPapers: [],
      selectedPaperIds: [],
      isSubmit: false,
    };
  },
  methods: {
    visibleChange() {
      this.curTab = "query";
      this.selectedPapers = [];
      this.selectedPaperIds = [];
      this.filter = Object.assign({}, initFilter, {
        batchId: this.batch.id,
        semesterId: this.batch.semesterId,
        examId: this.batch.examId,
      });
      this.examChange();
      this.$nextTick(() => this.changeCurListSelect());
    },
    cancel() {
      this.modalIsShow = false;
    },
    open() {
      this.modalIsShow = true;
    },
    examChange() {
      this.filter.collegeId = "";
      this.collegeList = [];
      this.getCollegeList();
    },
    async getCollegeList() {
      const data = await teachCollegeList(this.filter.examId);
      this.collegeList = data || [];
    },
    async search() {
      const datas = {
        ...this.filter,
      };
      const data = await analysisPaperList(datas);
      this.searchList = data.map((item) => {
        item.id = `${item.paperNumber}-${item.paperType}`;
        return item;
      });
      this.total = data.length;
      this.toPage(1);
    },
    changeCurListSelect() {
      this.dataList.forEach((row) => {
        if (this.selectedPaperIds.includes(row.id)) {
          this.$refs.TableList.toggleRowSelection(row, true);
        } else {
          this.$refs.TableList.toggleRowSelection(row, false);
        }
      });
    },
    getList() {
      this.dataList = this.searchList
        .slice((this.current - 1) * this.size, this.current * this.size)
        .map((item) => {
          return { ...item };
        });
      if (this.curTab === "query") {
        this.$nextTick(() => this.changeCurListSelect());
      }
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    selectMenu(tab) {
      this.curTab = tab;
      if (this.curTab === "query") {
        this.$nextTick(() => this.changeCurListSelect());
      }
    },
    toDelete(row) {
      this.selectedPapers = this.selectedPapers.filter(
        (item) => item.id !== row.id
      );
      this.updateSelectedIds();
    },
    updateSelectedIds() {
      this.selectedPaperIds = this.selectedPapers.map((item) => item.id);
    },
    handleSelectionChange(selection) {
      // console.log(selection);
      const seletedIds = selection.map((item) => item.id);
      this.dataList.forEach((item) => {
        const isSelected = seletedIds.includes(item.id);
        if (isSelected) {
          if (this.selectedPaperIds.includes(item.id)) return;
          this.selectedPapers.push({ ...item });
        } else {
          if (!this.selectedPaperIds.includes(item.id)) return;
          const pos = this.selectedPapers.findIndex((p) => p.id === item.id);
          this.selectedPapers.splice(pos, 1);
        }
      });
      this.updateSelectedIds();
    },
    async submit() {
      if (!this.selectedPapers.length) {
        this.$message.error("请选择试卷");
        return;
      }

      if (this.isSubmit) return;
      this.isSubmit = true;

      const ableAnalyzePaperList = this.selectedPapers.map((item) => {
        return {
          teachCollegeName: item.teachCollegeName,
          paperName: item.paperName,
          teachCollegeId: item.teachCollegeId,
          paperType: item.paperType,
          paperNumber: item.paperNumber,
        };
      });

      const res = await addAnalysisBatchPaper({
        batchId: this.batch.id,
        ableAnalyzePaperList,
      }).catch(() => {});
      this.isSubmit = false;
      if (!res) return;

      this.$message.success("添加成功！");
      this.cancel();
      this.$emit("modified");
    },
  },
};
</script>
