<template>
  <div class="insert-paper-structure">
    <div class="part-box">
      <div class="part-box-header">
        <h1 class="part-box-title">
          {{ paperStructId ? "精确结构编辑" : "精确结构创建" }}
        </h1>
        <div>
          <el-button
            type="primary"
            icon="icon icon-save-white"
            :disabled="button_disabled"
            @click="savePaperStruct()"
            >保存试卷结构</el-button
          >
          <el-button
            type="primary"
            icon="icon icon-plus-white"
            :disabled="button_disabled"
            @click="insert()"
            >新增大题</el-button
          >
          <el-button type="danger" plain icon="icon icon-back" @click="back"
            >返回</el-button
          >
        </div>
      </div>
      <el-form
        ref="paperStruct"
        class="part-filter-form"
        :inline="true"
        :model="paperStruct"
        :rules="rules2"
      >
        <el-form-item prop="name" label="结构名称">
          <el-input
            v-model="paperStruct.name"
            placeholder="试卷结构名称"
          ></el-input>
        </el-form-item>
        <el-form-item prop="score" label="总分">
          <el-input-number
            v-model.number="paperStruct.totalScore"
            placeholder="总分"
            :precision="1"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="制定课程">
          <el-select
            v-model="paperStruct.courseId"
            filterable
            :remote-method="getCourses"
            remote
            clearable
            placeholder="请选择"
            @clear="getCourses('')"
          >
            <el-option label="公用" :value="-1"></el-option>
            <el-option
              v-for="item in courseInfoSelect"
              :key="item.courseId"
              :label="item.courseInfo"
              :value="item.courseId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label-width="0px"> </el-form-item>
      </el-form>
      <v-editor
        v-model="paperStruct.examRemark"
        :height="hValue"
        placeholder="请输入考试说明"
        :enable-formula="false"
      ></v-editor>
    </div>
    <div class="part-box">
      <!-- 页面列表 -->
      <el-table :data="paperDetailStructs">
        <el-table-column label="大题名称">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="小题数">
          <template slot-scope="scope">
            <span>{{ scope.row.detailCount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="大题分数">
          <template slot-scope="scope">
            <span>{{ scope.row.totalScore }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="245">
          <template slot-scope="scope">
            <div class="operate_left">
              <el-button
                size="mini"
                type="primary"
                plain
                @click="insertTopicStruct(scope.row)"
                >添加小题</el-button
              >
              <el-button
                size="mini"
                type="primary"
                plain
                @click="editPaperDetail(scope.row.id)"
                >编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                plain
                @click="deletePaperDetail(scope.row.id)"
                >删除</el-button
              >
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加大题弹出框 -->
    <el-dialog
      title="大题信息"
      :visible.sync="paperDetailStructDialog"
      width="520px"
      :modal="false"
      append-to-body
      custom-class="side-dialog"
    >
      <el-form
        ref="paperDetailStructForm"
        :model="paperDetailStructForm"
        :rules="rules"
        label-position="right"
        label-width="100px"
        inline-message
        class="form-tight"
      >
        <el-form-item label="大题名称" prop="name">
          <el-input
            v-model="paperDetailStructForm.name"
            class="dialog-input-width"
            placeholder="请输入题型名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="大题描述" prop="remark">
          <v-editor
            v-model="paperDetailStructForm.remark"
            placeholder="请输入大题描述"
            :enable-formula="false"
          ></v-editor>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button
          v-if="dialogType == 'ADD'"
          type="primary"
          @click="submitForm('paperDetailStructForm')"
          >保存</el-button
        >
        <el-button
          v-else
          type="primary"
          @click="submitEditForm('paperDetailStructForm')"
          >保存</el-button
        >
        <el-button
          type="danger"
          plain
          @click="resetForm('paperDetailStructForm')"
          >重置</el-button
        >
        <el-button type="danger" plain @click="back2('paperDetailStructForm')"
          >返回</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { QUESTION_API } from "@/constants/constants";

export default {
  name: "InsertPaperStructure",
  data() {
    return {
      hValue: "100px",
      wValue: "800px",
      display: "block",
      loading: false,
      courseList: [],
      paperDetailStructForm: {
        id: "",
        number: "",
        name: "",
        remark: "",
        totalScore: "",
        detailCount: "",
        unitStructs: [],
      },
      paperStruct: {
        name: "",
        totalScore: "",
        paperDetailStructs: [],
        courseId: null,
        courseName: "",
        type: "EXACT", //试卷结构类型
        genPaperType: "COMMON", //组卷类型
        examRemark: { sections: [] },
      },
      paperDetailStructs: [],
      paperDeatilId: "",
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
      rules2: {
        name: [
          { required: true, message: "请输入试卷结构名称", trigger: "blur" },
        ],
      },
      paperStructId: "",
      paperDetailStructDialog: false,
      dialogType: "",
    };
  },
  computed: {
    button_disabled: function () {
      //var reg = /^[-\+]?\d+(\.\d+)?$/; //正小数
      var reg = /^\d+(?=\.{0,1}\d+$|$)/;
      if (
        reg.test(this.paperStruct.totalScore) &&
        this.paperStruct.totalScore > 0 &&
        this.paperStruct.name
      ) {
        return false;
      } else {
        return true;
      }
    },
    totalScore() {
      var sum = 0.0;
      for (let paperDetailStruct of this.paperDetailStructs) {
        sum = this.accAdd(sum, paperDetailStruct.totalScore);
      }
      return sum;
    },
    courseInfoSelect() {
      var courseList = [];
      for (let course of this.courseList) {
        var courseInfo = course.name + "(" + course.code + ")";
        var courseId = course.id;
        courseList.push({ courseId: courseId, courseInfo: courseInfo });
      }
      return courseList;
    },
  },
  created() {
    this.paperStructId = this.$route.params.id;
    this.searchForm();
  },
  mounted() {
    setTimeout(() => {
      this.$store.commit("UPDATE_CURRENT_PATHS", [
        "组卷结构预设",
        "精确结构预设",
        this.paperStructId ? "精确结构编辑" : "精确结构创建",
      ]);
    }, 200);
  },
  methods: {
    accAdd(num1, num2) {
      let sq1, sq2, m;
      try {
        sq1 = num1.toString().split(".")[1].length;
      } catch (e) {
        sq1 = 0;
      }
      try {
        sq2 = num2.toString().split(".")[1].length;
      } catch (e) {
        sq2 = 0;
      }
      m = Math.pow(10, Math.max(sq1, sq2));
      return (num1 * m + num2 * m) / m;
    },
    //查询列表集合
    searchForm() {
      this.loading = true;
      var paperStructStorge = sessionStorage.getItem("paperStruct");
      if (typeof paperStructStorge == "string") {
        var paperStruct = JSON.parse(paperStructStorge);
        this.getCourses(paperStruct.courseName);
        this.paperStruct = paperStruct;
        this.paperDetailStructs = paperStruct.paperDetailStructs;
      } else {
        this.getCourses("");
      }
      this.loading = false;
    },
    //保存
    savePaperStruct() {
      if (this.paperStruct.name.trim().length == 0) {
        this.$notify({
          message: "结构名称不能为空格",
          type: "error",
        });
        return false;
      }
      if (!this.checkPaperStruct()) {
        return false;
      }
      if (!this.paperStruct.courseId) {
        this.$notify({
          message: "请选择课程",
          type: "error",
        });
        return false;
      }
      this.loading = true;
      var url = QUESTION_API + "/paperStruct";
      console.log(this.paperStructId);
      if (this.paperStructId != "add") {
        //假如没ID就是新增
        this.$httpWithMsg
          .put(url, this.paperStruct)
          .then(() => {
            this.$notify({
              message: "保存成功",
              type: "success",
            });
            this.loading = false;
            this.removeItem();
            this.back();
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        this.$httpWithMsg
          .post(url, this.paperStruct)
          .then(() => {
            this.$notify({
              message: "保存成功",
              type: "success",
            });
            this.loading = false;
            this.removeItem();
            this.back();
          })
          .finally(() => {
            this.loading = false;
          });
      }
    },
    checkPaperStruct() {
      if (
        !(
          this.paperStruct.paperDetailStructs &&
          this.paperStruct.paperDetailStructs.length > 0
        )
      ) {
        this.$notify({
          message: "请添加大题",
          type: "error",
        });
        return false;
      }
      for (let paperDetailStruct of this.paperStruct.paperDetailStructs) {
        if (
          !(
            paperDetailStruct.unitStructs &&
            paperDetailStruct.unitStructs.length > 0
          )
        ) {
          this.$notify({
            message: "请添加大题下的题型",
            type: "error",
          });
          return false;
        }
      }
      if (this.paperStruct.totalScore !== this.totalScore) {
        this.$notify({
          message: "大题总分与结构满分不一致",
          type: "error",
        });
        return false;
      }
      return true;
    },
    //保存大题
    submitForm(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          var nextId;
          if (!this.paperDetailStructs || this.paperDetailStructs.length == 0) {
            nextId = 1;
          } else {
            nextId =
              this.paperDetailStructs[this.paperDetailStructs.length - 1].id +
              1;
          }
          var paperDetailStruct = Object.assign({}, this.paperDetailStructForm);
          paperDetailStruct.id = nextId;
          paperDetailStruct.number = paperDetailStruct.id;
          if (!paperDetailStruct.remark)
            paperDetailStruct.remark = { sections: [] };
          this.paperDetailStructs.push(paperDetailStruct);
          this.paperDetailStructDialog = false;
          this.paperDetailStructForm.id = "";
          this.paperDetailStructForm.name = "";
          this.paperDetailStructForm.remark = "";
          this.paperStruct.paperDetailStructs = this.paperDetailStructs;
          sessionStorage.setItem(
            "paperStruct",
            JSON.stringify(this.paperStruct)
          );
        } else {
          return false;
        }
      });
    },
    submitEditForm(formData) {
      this.$refs[formData].validate((valid) => {
        if (valid) {
          var paperDetailStructs = this.paperDetailStructs;
          for (let i = paperDetailStructs.length - 1; i >= 0; i--) {
            if (paperDetailStructs[i].id == this.paperDeatilId) {
              paperDetailStructs[i].remark = this.paperDetailStructForm.remark;
              paperDetailStructs[i].name = this.paperDetailStructForm.name;
            }
          }
          this.paperDetailStructDialog = false;
          this.paperDetailStructForm.id = "";
          this.paperDetailStructForm.name = "";
          this.paperDetailStructForm.remark = "";
          this.paperStruct.paperDetailStructs = paperDetailStructs;
          sessionStorage.setItem(
            "paperStruct",
            JSON.stringify(this.paperStruct)
          );
        } else {
          return false;
        }
      });
    },
    deletePaperDetail(id) {
      var paperDetailStructs = this.paperDetailStructs;
      for (let i = paperDetailStructs.length - 1; i >= 0; i--) {
        if (paperDetailStructs[i].id == id) {
          paperDetailStructs.splice(i, 1);
        }
      }
      this.paperStruct.paperDetailStructs = paperDetailStructs;
      sessionStorage.setItem("paperStruct", JSON.stringify(this.paperStruct));
      console.log(sessionStorage.getItem("paperStruct"));
    },
    setPaperStruct() {
      var paperStruct = sessionStorage.getItem("paperStruct");
      this.paperStruct = JSON.parse(paperStruct);
    },
    removeItem() {
      sessionStorage.removeItem("paperStruct");
    },
    //重置
    resetForm(formData) {
      this.paperDetailStructForm.remark = "";
      this.paperDetailStructForm.name = "";
      this.$refs[formData].clearValidate();
    },

    //添加大题型
    insert() {
      this.dialogType = "ADD";
      this.paperDetailStructForm.remark = "";
      this.paperDetailStructForm.name = "";
      this.paperDetailStructDialog = true;
    },
    editPaperDetail(paperDeatilId) {
      this.dialogType = "EDIT";
      this.paperDeatilId = paperDeatilId;
      var paperDetailStructs = this.paperDetailStructs;
      for (let i = paperDetailStructs.length - 1; i >= 0; i--) {
        if (paperDetailStructs[i].id == this.paperDeatilId) {
          this.paperDetailStructForm.remark = paperDetailStructs[i].remark;
          this.paperDetailStructForm.name = paperDetailStructs[i].name;
        }
      }
      this.paperDetailStructDialog = true;
    },
    getCourseName(courseId) {
      for (let course of this.courseList) {
        if (course.courseId == courseId) {
          this.paperStruct.courseName = course.name;
        }
      }
    },
    //添加小题
    insertTopicStruct(row) {
      let courseId = this.paperStruct.courseId;
      this.getCourseName(this.paperStruct.courseId);
      sessionStorage.setItem("paperStruct", JSON.stringify(this.paperStruct));
      this.$router.push({
        path:
          "/questions/insert_paper_structure_info/" +
          this.paperStructId +
          "/" +
          row.name +
          "/" +
          row.id +
          "/" +
          courseId,
      });
    },
    //返回
    back() {
      this.$router.push({
        path: "/questions/paper_structure/1",
      });
    },
    back2(formData) {
      this.resetForm(formData);
      this.paperDetailStructDialog = false;
    },
    //查询所有课程
    getCourses(query) {
      this.courseLoading = true;
      this.$http
        .get(QUESTION_API + "/course/query?name=" + query + "&enable=true")
        .then((response) => {
          this.courseList = response.data;
          this.courseLoading = false;
        });
    },
  },
};
</script>
