<template>
  <div
    v-loading="fullscreenLoading"
    class="synthesis-paper gen-paper-detail"
    element-loading-text="正在组卷中..."
  >
    <div class="part-box">
      <div class="part-box-header">
        <h1 class="part-box-title">综合组卷</h1>
        <div>
          <el-button
            type="primary"
            icon="icon icon-save-white"
            :loading="fullscreenLoading"
            @click="confirmGenPaper"
            >确定</el-button
          >
          <el-button type="danger" plain icon="icon icon-back" @click="goback"
            >返回</el-button
          >
        </div>
      </div>
      <el-form
        ref="modalFormComp"
        class="part-filter-form"
        :model="modalForm"
        :rules="rules"
        inline
      >
        <el-form-item prop="courseName" label="业务课名称" style="width: 300px">
          <el-input
            v-model="modalForm.courseName"
            placeholder="业务课名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="courseCode" label="业务课代码" style="width: 300px">
          <el-input
            v-model="modalForm.courseCode"
            placeholder="业务课代码"
          ></el-input>
        </el-form-item>
        <el-form-item prop="name" label="试卷标题" style="width: 300px">
          <el-input v-model="modalForm.name" placeholder="试卷名称"></el-input>
        </el-form-item>
        <span class="tips-info margin-left-10"
          >会作为试卷标题展示在试卷卷头部分</span
        >
      </el-form>
    </div>

    <!-- 试题来源 -->
    <div class="part-box">
      <div class="gen-step-title">
        <h3>题源选择</h3>
      </div>
      <div class="gen-step-body">
        <el-form class="part-filter-form" :inline="true">
          <el-form-item label="课程" style="width: 280px">
            <el-select
              v-model="filter.courseId"
              :remote-method="getCoursesList"
              :loading="courseLoading"
              remote
              filterable
              clearable
              multiple
              placeholder="请选择"
              @clear="getCoursesList('')"
            >
              <el-option
                v-for="item in courseList"
                :key="item.id"
                :label="item.name + ' - ' + item.code"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" style="width: 460px">
            <el-date-picker
              v-model="createTime"
              type="datetimerange"
              :picker-options="pickerOptions"
              range-separator="-"
              start-placeholder="创建开始时间"
              end-placeholder="创建结束时间"
              value-format="timestamp"
              align="right"
              unlink-panels
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :loading="loading" @click="toPage(1)"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
        <el-table v-loading="loading" class="part-box-border" :data="paperList">
          <el-table-column width="50" align="center">
            <template slot-scope="scope">
              <el-checkbox
                v-model="scope.row.selected"
                @change="paperSelectChange(scope.row)"
              ></el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="courseName" label="课程名称">
          </el-table-column>
          <el-table-column prop="courseCode" label="课程代码">
          </el-table-column>
          <el-table-column prop="paperName" label="试卷名称"> </el-table-column>
          <el-table-column prop="totalScore" label="总分" width="100">
          </el-table-column>
          <el-table-column prop="unitCount" label="小题数量" width="200">
          </el-table-column>
        </el-table>
        <div class="part-page">
          <el-pagination
            :current-page="current"
            :page-size="size"
            :page-sizes="[10, 20, 50, 100, 200, 300]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @current-change="toPage"
            @size-change="pageSizeChange"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 已选试卷 -->
    <div class="part-box">
      <div class="gen-step-title">
        <h3>选中试卷列表</h3>
      </div>
      <div class="gen-step-body">
        <el-table class="part-box-border" :data="selectPapers">
          <el-table-column prop="courseName" label="课程名称">
          </el-table-column>
          <el-table-column prop="courseCode" label="课程代码">
          </el-table-column>
          <el-table-column prop="aliasName" label="试卷名称">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.aliasName"
                placeholder="请输入试卷名称"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="220">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="danger"
                plain
                @click="toRemovePaper(scope.row)"
                >移除</el-button
              >
              <el-button
                v-if="scope.$index"
                size="mini"
                type="primary"
                plain
                @click="toMoveupPaper(scope.row)"
                >上移</el-button
              >
              <el-button
                v-if="scope.$index !== dataListLastInd"
                size="mini"
                type="primary"
                plain
                @click="toMovedownPaper(scope.row)"
                >下移</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<script>
import {
  paperPageListApi,
  courseQueryApi,
  synthesisBuildPaperApi,
} from "../api";
import pickerOptions from "@/constants/datePickerOptions";

export default {
  data() {
    return {
      modalForm: {
        courseName: "",
        courseCode: "",
        name: "",
      },
      rules: {
        courseName: [
          {
            required: true,
            message: "请输入业务课名称",
            trigger: "change",
          },
          {
            max: 100,
            message: "业务课名称不可超过100字符",
          },
        ],
        courseCode: [
          {
            required: true,
            message: "请输入业务课代码",
            trigger: "change",
          },
          {
            max: 100,
            message: "业务课代码不可超过100字符",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入试卷名称",
            trigger: "change",
          },
          {
            max: 100,
            message: "试卷名称不可超过100字符",
          },
        ],
      },
      filter: {
        courseId: [],
        createStartTime: "",
        createEndTime: "",
      },
      current: 1,
      size: 10,
      total: 0,
      loading: false,
      paperList: [],
      selectPapers: [],
      courseList: [],
      courseLoading: false,
      fullscreenLoading: false,
      // date-picker
      createTime: [],
      pickerOptions,
    };
  },
  computed: {
    dataListLastInd() {
      return this.selectPapers.length - 1;
    },
  },
  mounted() {
    this.getCoursesList();
  },
  methods: {
    async getCoursesList(query) {
      this.courseLoading = true;
      query = query && query.trim();
      const res = await courseQueryApi(query, "true");
      this.courseList = res.data || [];
      this.courseLoading = false;
    },
    async getList() {
      const datas = {
        ...this.filter,
        pageNumber: this.current,
        pageSize: this.size,
      };
      datas.courseId = datas.courseId.join();
      if (this.createTime && this.createTime.length) {
        datas.createStartTime = this.createTime[0];
        datas.createEndTime = this.createTime[1];
      }
      const selectedPaperIds = this.selectPapers.map((item) => item.id);
      datas.selectedPaperIds = selectedPaperIds;
      const res = await paperPageListApi(datas);
      this.paperList = res.data.content.map((item) => {
        let nitem = {
          ...item,
          id: item.paperId,
          selected: selectedPaperIds.includes(item.id),
        };
        return nitem;
      });
      this.total = res.data.totalElements;
    },
    toPage(page) {
      this.current = page;
      this.getList();
    },
    pageSizeChange(size) {
      this.size = size;
      this.toPage(1);
    },
    paperSelectChange(row) {
      if (row.selected) {
        const paper = this.paperList.find((item) => item.id === row.id);
        this.selectPapers.push({ ...paper, aliasName: paper.paperName });
      } else {
        this.toRemovePaper(row);
      }
    },
    toRemovePaper(row) {
      this.selectPapers = this.selectPapers.filter(
        (item) => item.id !== row.id
      );
    },
    toMoveupPaper(row) {
      const pos = this.selectPapers.findIndex((item) => item.id === row.id);
      if (!pos) return;
      const curPaper = this.selectPapers.splice(pos, 1)[0];
      this.selectPapers.splice(pos - 1, 0, curPaper);
    },
    toMovedownPaper(row) {
      const pos = this.selectPapers.findIndex((item) => item.id === row.id);
      if (pos === this.selectPapers.length - 1) return;
      const curPaper = this.selectPapers.splice(pos, 1)[0];
      this.selectPapers.splice(pos + 1, 0, curPaper);
    },
    async confirmGenPaper() {
      const valid = await this.$refs.modalFormComp.validate().catch(() => {});
      if (!valid) return;

      if (!this.selectPapers.length) {
        this.$message.error("请选择试卷");
        return;
      }

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

      let datas = { ...this.modalForm };
      datas.papers = this.selectPapers.map((item) => {
        return {
          paperId: item.id,
          paperName: item.aliasName,
        };
      });
      const res = await synthesisBuildPaperApi(datas).catch(() => {});
      this.fullscreenLoading = false;
      if (!res) return;

      this.$message.success("组卷成功！");
      this.goback();
    },
  },
};
</script>
