<template>
  <div class="testerautosave-wrapper">
    <div class="tools-wrapper">
      <el-button type="primary" @click="addTester">添加试题</el-button>
    </div>
    <div class="table-wrapper">
      <el-table :data="subjectsTableData" border>
        <el-table-column prop="question" label="题干"></el-table-column>
        <el-table-column prop="type" label="题型"></el-table-column>
        <el-table-column prop="difficulty" label="难度"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" @click="remove(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="save-wrapper">
      <el-button type="primary" @click="savePaper">保存试卷</el-button>
    </div>
    <el-dialog title="添加试题" :visible.sync="addDialogVisible" width="80%">
      <div class="dialog-tools-wrapper">
        <el-select v-model="curSubjectType" placeholder="请选择试题类型">
          <el-option
            v-for="item in subjectTypes"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-select
          :style="{ marginLeft: '20px' }"
          v-model="curDifficulty"
          placeholder="请选择困难度"
        >
          <el-option
            v-for="item in difficulties"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-input
          :style="{ marginLeft: '20px' }"
          v-model="searchKeyWord"
          placeholder="关键字"
          >关键字</el-input
        >
        <el-button
          :style="{ marginLeft: '20px' }"
          type="primary"
          @click="searchQuestion"
          >搜索</el-button
        >
      </div>
      <div class="dialog-table-wrapper">
        <div class="dialog-table-header-wrapper">
          <div class="dialog-table-header-selection">
            <el-checkbox
              v-model="chosenRadio"
              @input="inputChosenRadio"
            ></el-checkbox>
          </div>
          <div class="dialog-table-header-question">题干</div>
        </div>
        <div
          v-for="item in searchSubject"
          :key="item.id"
          class="dialog-table-body-wrapper"
        >
          <div class="dialog-table-body-selection">
            <el-checkbox
              v-model="item.isChosen"
              @input="inputItem(item)"
            ></el-checkbox>
          </div>
          <div class="dialog-table-body-question">{{ item.question }}</div>
        </div>
        <el-pagination
          :style="{ marginTop: '30px' }"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="curPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalElements"
        >
        </el-pagination>
      </div>
      <div class="cur-chosen-subject-sum">
        {{ "已选择 " + curChosenSelection.length + " 个试题" }}
      </div>
      <div slot="footer">
        <el-button type="primary" @click="submitSubjects">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOnlineExamSubject,
  findPaperSubject,
  savePaperAfterAutomatically
} from "@/api/test.js";
export default {
  data() {
    return {
      subjectsTableData: [],
      exclusiveIds: [],
      subjectTypes: [
        {
          label: "单选题",
          value: "单选题"
        },
        {
          label: "多选题",
          value: "多选题"
        },
        {
          label: "判断题",
          value: "判断题"
        }
      ],
      curSubjectType: "",
      curDifficulty: "",
      searchKeyWord: "",
      chosenRadio: false,
      addDialogVisible: false,
      difficulties: [
        {
          label: "简单",
          value: "简单"
        },
        {
          label: "一般",
          value: "一般"
        },
        {
          label: "困难",
          value: "困难"
        }
      ],
      searchSubject: [],
      curChosenSelection: [],
      currentPage: 1,
      curPageSize: 10,
      totalElements: 0,
      deleteSubjects: []
    };
  },
  async mounted() {
    console.log(this.$route.params.name, "this.$route.params.name");
    const params = {
      page: 0,
      size: 999,
      paperId: this.$route.params.name,
      type: "单选题"
    };
    let result = [];
    await findPaperSubject(params).then(res => {
      console.log(res, "findPaperSubject findPaperSubject findPaperSubject");
      result = [
        ...result,
        ...res.content.map(item => {
          return {
            ...item,
            type: "单选题"
          };
        })
      ];
    });
    params.type = "多选题";
    await findPaperSubject(params).then(res => {
      console.log(res, "fsda fsda sd fsdf sda f");
      result = [
        ...result,
        ...res.content.map(item => {
          return {
            ...item,
            type: "多选题"
          };
        })
      ];
    });
    params.type = "判断题";
    await findPaperSubject(params).then(res => {
      console.log(res, "sdfahuykfdsyafyweyf");
      result = [
        ...result,
        ...res.content.map(item => {
          return {
            ...item,
            type: "判断题"
          };
        })
      ];
    });
    this.subjectsTableData = [...result];
    this.subjectsTableData.forEach(item => {
      item.id = item.subjectId;
      item.isOrigin = true;
    });
    this.exclusiveIds = [...this.subjectsTableData.map(item => item.subjectId)];
  },
  methods: {
    async getQuestions() {
      const data = {
        page: this.currentPage - 1,
        exclusiveIds: this.exclusiveIds,
        size: this.curPageSize
      };
      if (this.curSubjectType) {
        data.type = this.curSubjectType;
      }
      if (this.curDifficulty) {
        data.difficulty = this.curDifficulty;
      }
      if (this.searchKeyWord) {
        data.question = this.searchKeyWord;
      }
      await getOnlineExamSubject(data).then(res => {
        console.log(res, "getOnlineExamSubject getOnlineExamSubject");
        this.searchSubject = [...res.content];
        this.searchSubject.forEach(item => {
          item.isChosen = false;
          item.isOrigin = false;
        });
        this.searchSubject.forEach(subject => {
          if (
            this.curChosenSelection.filter(item => item.id === subject.id)
              .length > 0
          ) {
            subject.isChosen = true;
          } else {
            subject.isChosen = false;
          }
        });
        this.chosenRadio = false;
        this.totalElements = res.totalElements;
      });
    },
    searchQuestion() {
      this.getQuestions();
    },
    remove(row) {
      console.log(row, "reomove");
      if (row.isOrigin) {
        this.deleteSubjects.push(row);
        console.log(
          this.deleteSubjects,
          "this.deleteSubjects this.deleteSubjects"
        );
      }
      // this.exclusiveIds.push(row.id)
      this.subjectsTableData.splice(this.subjectsTableData.indexOf(row), 1);
    },
    inputChosenRadio($event) {
      console.log($event, "inputChosenRadio inputChosenRadio inputChosenRadio");
      if ($event) {
        this.searchSubject.forEach(item => {
          if (item.isChosen === false) {
            this.curChosenSelection.push(item);
            item.isChosen = true;
          }
        });
      } else {
        this.searchSubject.forEach(item => {
          if (item.isChosen === true) {
            this.curChosenSelection.splice(
              this.curChosenSelection.indexOf(item),
              1
            );
          }
        });
      }
    },
    inputItem(item) {
      console.log(item, "inputItem inputItem inputItem");
      if (item.isChosen) {
        if (this.curChosenSelection.indexOf(item) === -1) {
          this.curChosenSelection.push(item);
        }
      } else {
        if (this.curChosenSelection.indexOf(item) > -1) {
          this.curChosenSelection.splice(
            this.curChosenSelection.indexOf(item),
            1
          );
        }
      }
    },
    handleSizeChange(val) {
      this.curPageSize = val;
      this.getQuestions();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getQuestions();
    },
    addTester() {
      this.addDialogVisible = true;
      this.getQuestions();
    },
    submitSubjects() {
      // this.subjectsTableData = [...this.subjectsTableData, ...this.curChosenSelection]
      this.curChosenSelection.forEach(item => {
        if (
          !this.subjectsTableData.filter(subject => subject.id === item.id)
            .length
        ) {
          this.subjectsTableData.push(item);
        }
      });
      this.addDialogVisible = false;
    },
    savePaper() {
      //this.subjectsTableData
      //this.deleteSubjects
      const data = {
        addJudgementIds: this.subjectsTableData
          .filter(item => item.type === "判断题")
          .map(item => {
            return {
              subjectId: item.id,
              paperId: this.$route.params.name
            };
          }),
        addMultipleChoiceIds: this.subjectsTableData
          .filter(item => item.type === "多选题")
          .map(item => {
            return {
              subjectId: item.id,
              paperId: this.$route.params.name
            };
          }),
        addSingleChoiceIds: this.subjectsTableData
          .filter(item => item.type === "单选题")
          .map(item => {
            return {
              subjectId: item.id,
              paperId: this.$route.params.name
            };
          }),
        deleteJudgementIds: this.deleteSubjects
          .filter(item => item.type === "判断题")
          .map(item => {
            return {
              subjectId: item.id,
              paperId: this.$route.params.name
            };
          }),
        deleteMultipleChoiceIds: this.deleteSubjects
          .filter(item => item.type === "多选题")
          .map(item => {
            return {
              subjectId: item.id,
              paperId: this.$route.params.name
            };
          }),
        deleteSingleChoiceIds: this.deleteSubjects
          .filter(item => item.type === "单选题")
          .map(item => {
            return {
              subjectId: item.id,
              paperId: this.$route.params.name
            };
          }),
        paperId: this.$route.params.name
      };
      savePaperAfterAutomatically(data)
        .then(res => {
          this.$message({
            type: "success",
            message: "保存试卷成功"
          });
        })
        .catch(() => {
          this.$message.error("保存试卷失败");
        });
    }
  }
};
</script>

<style lang="scss" scoped>
.testerautosave-wrapper {
  padding: 10px;
  border-radius: 5px;
  margin: 10px 10px;
  .tools-wrapper {
    padding: 10px;
    border-radius: 5px;
    margin: 10px 10px;
    background: #fff;
  }
  .table-wrapper {
    padding: 10px;
    border-radius: 5px;
    margin: 10px 10px;
    background: #fff;
  }
  .save-wrapper {
    padding: 10px;
    border-radius: 5px;
    margin: 10px 10px;
    display: flex;
    justify-content: flex-end;
    padding-right: 10%;
  }
}
.dialog-tools-wrapper {
  display: flex;
  justify-content: space-around;
  padding: 10px;
  border-radius: 5px;
  margin: 10px 10px;
}
.dialog-table-wrapper {
  padding: 10px;
  border-radius: 5px;
  margin: 10px 10px;
}
.dialog-table-header-wrapper {
  display: flex;
  padding: 10px;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
  .dialog-table-header-selection {
    flex-basis: 10%;
  }
  .dialog-table-header-question {
    flex-basis: 90%;
  }
}
.dialog-table-body-wrapper {
  display: flex;
  padding: 10px;
  border-bottom: 1px solid #eee;
  .dialog-table-body-selection {
    flex-basis: 10%;
  }
  .dialog-table-body-question {
    flex-basis: 90%;
  }
}
.cur-chosen-subject-sum {
  display: flex;
  justify-content: flex-end;
  margin-right: 30px;
}
</style>
