<template>
  <div>
    <section class="content">
      <div>
        <!-- 头信息 -->
        <div><h3 class="box-title">精确结构创建-->创建大题</h3></div>
        <!-- 正文信息 -->
        <div class="box-body">
          <el-form
            :inline="true"
            :model="paperStruct"
            ref="paperStruct"
            :rules="rules2"
          >
            <el-row>
              <el-form-item label="精确结构名称" prop="name">
                <el-input
                  v-model="paperStruct.name"
                  auto-complete="off"
                  placeholder="试卷结构名称"
                ></el-input>
              </el-form-item>
              <el-form-item label="总分" prop="score">
                <el-input
                  v-model.number="paperStruct.totalScore"
                  auto-complete="off"
                  placeholder="请输入总分"
                ></el-input>
              </el-form-item>
              <el-form-item label="制定课程">
                <el-select
                  v-model="paperStruct.courseNo"
                  filterable
                  :remote-method="getCourses"
                  remote
                  clearable
                  placeholder="请选择"
                >
                  <el-option label="请选择" value="ALL" key="ALL"></el-option>
                  <el-option label="公用" value="" key=""></el-option>
                  <el-option
                    v-for="item in courseInfoSelect"
                    :label="item.courseInfo"
                    :value="item.courseNo"
                    :key="item.courseNo"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button
                  size="small"
                  type="success"
                  :disabled="button_disabled"
                  @click="savePaperStruct();"
                >
                  <i class="fa fa-floppy-o"></i>保 存</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  icon="plus"
                  :disabled="button_disabled"
                  @click="insert();"
                  >添加大题</el-button
                >
                <el-button
                  size="small"
                  type="primary"
                  icon="caret-left"
                  @click="back"
                  >返 回</el-button
                >
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="考试说明">
                <div style="width:550px;">
                  <ckeditor v-model="paperStruct.examRemark"></ckeditor>
                </div>
              </el-form-item>
            </el-row>
          </el-form>

          <!-- 添加大题弹出框 -->
          <el-dialog
            title="大题信息"
            :visible.sync="paperDetailStructDialog"
            size="tiny"
          >
            <el-form
              :inline="true"
              :model="paperDetailStructForm"
              ref="paperDetailStructForm"
              :rules="rules"
              label-position="right"
              label-width="90px"
            >
              <el-row>
                <el-form-item label="大题名称" label-width="120px" prop="name">
                  <el-input
                    v-model="paperDetailStructForm.name"
                    auto-complete="off"
                    placeholder="请输入题型名称"
                  ></el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <el-form-item
                  label="题型描述"
                  label-width="120px"
                  prop="remark"
                >
                  <el-input
                    type="textarea"
                    :rows="2"
                    v-model="paperDetailStructForm.remark"
                    auto-complete="off"
                    placeholder="请输入题型描述"
                  ></el-input>
                </el-form-item>
              </el-row>
              <el-row>
                <span v-if="dialogType == 'ADD'">
                  <el-button
                    type="primary"
                    @click="submitForm('paperDetailStructForm');"
                    >保 存</el-button
                  >
                </span>
                <span v-else>
                  <el-button
                    type="primary"
                    @click="submitEditForm('paperDetailStructForm');"
                    >保 存</el-button
                  >
                </span>
                <el-button type="danger" @click="resetForm();">重 置</el-button>
              </el-row>
            </el-form>
          </el-dialog>

          <!-- 页面列表 -->
          <el-table :data="paperDetailStructs" border>
            <el-table-column label="大题名称">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.name }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="小题数">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.detailCount }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="大题分数">
              <template slot-scope="scope">
                <div>
                  <span>{{ scope.row.totalScore }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column :context="_self" label="操作">
              <template slot-scope="scope">
                <div>
                  <el-button
                    size="mini"
                    type="primary"
                    @click="insertTopicStruct(scope.row);"
                    >添加小题</el-button
                  >
                  <el-button
                    size="mini"
                    type="info"
                    @click="editPaperDetail(scope.row.id);"
                  >
                    编辑
                  </el-button>
                  <el-button
                    size="mini"
                    type="danger"
                    @click="deletePaperDetail(scope.row.id);"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </section>
  </div>
</template>

<script>
import { CORE_API, Q_API } from "../constants/constants";
import ckeditor from "../component/ckeditor.vue";
export default {
  components: { ckeditor },
  data() {
    return {
      loading: false,
      courseList: [],
      paperDetailStructForm: {
        id: "",
        number: "",
        name: "",
        remark: "",
        totalScore: "",
        detailCount: "",
        unitStructs: []
      },
      paperStruct: {
        name: "",
        totalScore: "",
        paperDetailStructs: [],
        courseNo: "ALL",
        type: "EXACT", //试卷结构类型
        genPaperType: "COMMON", //组卷类型
        examRemark: ""
      },
      paperDetailStructs: [],
      paperDeatilId: "",
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
        remark: [{ required: true, message: "请输入题型描述", trigger: "blur" }]
      },
      rules2: {
        name: [
          { required: true, message: "请输入试卷结构名称", trigger: "blur" }
        ]
      },
      paperStructId: "",
      paperDetailStructDialog: false,
      dialogType: ""
    };
  },

  methods: {
    //查询列表集合
    searchForm() {
      this.loading = true;
      var paperStructStorge = sessionStorage.getItem("paperStruct");
      if (typeof paperStructStorge == "string") {
        var paperStruct = JSON.parse(paperStructStorge);
        console.log(paperStruct);
        this.paperStruct = paperStruct;
        this.paperDetailStructs = paperStruct.paperDetailStructs;
      }
      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.courseNo == "ALL") {
        this.$notify({
          message: "请选择课程",
          type: "error"
        });
        return false;
      }
      this.loading = true;
      var url = Q_API + "/paperStruct";
      console.log(this.paperStructId);
      if (this.paperStructId != "add") {
        //假如没ID就是新增
        this.$http
          .put(url, this.paperStruct)
          .then(() => {
            this.$notify({
              message: "保存成功",
              type: "success"
            });
            this.loading = false;
            this.removeItem();
            this.back();
          })
          .catch(() => {
            this.$notify({
              type: "error",
              message: "试卷结构名称重复，请重新命名"
            });

            this.loading = false;
          });
      } else {
        this.$http
          .post(url, this.paperStruct)
          .then(() => {
            this.$notify({
              message: "保存成功",
              type: "success"
            });
            this.loading = false;
            this.removeItem();
            this.back();
          })
          .catch(() => {
            this.loading = false;
            this.$notify({
              type: "error",
              message: "试卷结构名称重复，请重新命名"
            });
          });
      }
    },
    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) {
      //校验大题名称
      if (
        !this.paperDetailStructForm.name ||
        this.paperDetailStructForm.name.trim().length == 0
      ) {
        this.$notify({
          message: "大题名称不能为空",
          type: "error"
        });
        return;
      }
      this.loading = true;
      this.$refs[formData].validate(valid => {
        if (valid) {
          var ids = [];
          for (let paperDetailStruct of this.paperDetailStructs) {
            ids.push(paperDetailStruct.id);
          }
          ids.sort();
          var maxId;
          if (ids.length == 0) {
            maxId = 1;
          } else {
            maxId = ids[ids.length - 1];
          }

          var paperDetailStruct = Object.assign({}, this.paperDetailStructForm);
          paperDetailStruct.id = maxId + 1;
          paperDetailStruct.number = this.paperDetailStructs.length + 1;
          this.paperDetailStructs.push(paperDetailStruct);
          this.paperDetailStructDialog = false;
          this.paperDetailStructForm = { name: "", remark: "" };
          this.paperStruct.paperDetailStructs = this.paperDetailStructs;
          sessionStorage.setItem(
            "paperStruct",
            JSON.stringify(this.paperStruct)
          );
        } else {
          return false;
        }
      });
      this.loading = false;
    },
    submitEditForm(formData) {
      //校验大题名称
      if (
        !this.paperDetailStructForm.name ||
        this.paperDetailStructForm.name.trim().length == 0
      ) {
        this.$notify({
          message: "大题名称不能为空",
          type: "error"
        });
        return;
      }
      this.loading = true;
      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 = { name: "", remark: "" };
          this.paperStruct.paperDetailStructs = paperDetailStructs;
          sessionStorage.setItem(
            "paperStruct",
            JSON.stringify(this.paperStruct)
          );
        } else {
          return false;
        }
      });
      this.loading = 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() {
      this.paperDetailStructForm = {
        name: "",
        remark: ""
      };
    },

    //添加大题型
    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;
    },
    //添加小题
    insertTopicStruct(row) {
      let courseNo =
        this.paperStruct.courseNo === "" ? "all" : this.paperStruct.courseNo;
      sessionStorage.setItem("paperStruct", JSON.stringify(this.paperStruct));
      this.$router.push({
        path:
          "/questions/insert_paper_structure_info/" +
          this.paperStructId +
          "/" +
          row.name +
          "/" +
          row.id +
          "/" +
          courseNo
      });
    },
    //返回
    back() {
      this.$router.push({
        path: "/questions/paper_structure/1"
      });
    },
    //查询所有课程
    getCourses(query) {
      query = query.trim();
      if (query) {
        if (!(query.indexOf("(") > -1 && query.indexOf(")") > -1)) {
          this.courseLoading = true;
          this.$http
            .get(CORE_API + "/course/query?name=" + query + "&enable=true")
            .then(response => {
              this.courseList = response.data;
              this.courseLoading = false;
            });
        }
      } else {
        this.courseList = [];
      }
    }
  },
  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 += paperDetailStruct.totalScore;
      }
      return sum;
    },
    courseInfoSelect() {
      var courseList = [];
      for (let course of this.courseList) {
        var courseInfo = course.name + "(" + course.code + ")";
        var courseNo = course.code;
        courseList.push({ courseNo: courseNo, courseInfo: courseInfo });
      }
      return courseList;
    }
  },
  created() {
    this.paperStructId = this.$route.params.id;
    this.searchForm();
  }
};
</script>
