<template>
  <div id="examQuestionConfiguration">
    <search-box :formList="formList" @search="search" @init="init" />
    <table-list
      :tableSets="tableSet"
      :tableData="tableData"
      :navText="navText"
      @addClick="addClick"
      :loading="loading"
    >
      <template slot="btn" slot-scope="props">
        <el-button type="text" @click="addClick(props.scope.row, 2)"
          >详情</el-button
        >
        <el-button type="text" @click="addClick(props.scope.row, 0)"
          >修改</el-button
        >
        <el-button type="text" @click="del(props.scope.row)">删除</el-button>
      </template>
    </table-list>
    <pagination
      :total="total"
      :pageSize="pageSize"
      :currentPage="currentPage"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <el-dialog
      :visible.sync="dialogVisible"
      width="560px"
      :show-close="false"
      :before-close="close"
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">
          {{ statusPop === 1 ? "添加" : statusPop === 0 ? "修改" : "详情" }}
        </div>
        <div class="rightBoxs">
          <img src="@/assets/images/Close@2x.png" alt="" @click="close" />
        </div>
      </div>
      <div>
        <el-form>
          <el-form-item
            v-for="(items, indexs) in listitem"
            :key="indexs"
            :label="items.label"
          >
            <div
              v-if="items.scope === 'more'"
              style="display: flex; align-item: center"
            >
              <div>分值：</div>
              <el-input
                :disabled="statusPop === 2"
                style="width: 140px"
                v-model="formtrop[items.prop]"
                ><template slot="append">分</template></el-input
              >
              <div style="margin: 0px 10px">抽取题目数量</div>
              <el-input
                :disabled="statusPop === 2"
                style="flex: 1"
                v-model="formtrop[items.prop2]"
                ><template slot="append">题</template></el-input
              >
            </div>
            <div v-else-if="items.scope === 'totalScores'">
              {{ formtrop[items.prop] }}
              <el-button
                size="small"
                style="margin-left: 20px"
                @click="computedTotal"
                >重新计算</el-button
              >
            </div>
            <el-select
              :disabled="statusPop === 2"
              v-else-if="items.scope === 'select'"
              v-model="formtrop[items.prop]"
              placeholder="请选择状态"
            >
              <el-option
                v-for="it in items.options"
                :key="it.value"
                :label="it.label"
                :value="it.value"
              >
              </el-option>
            </el-select>
            <el-cascader
              v-else-if="items.scope === 'cascader'"
              style="width: 150px"
              v-model="formtrop[items.prop]"
              :options="optionsTion"
              :disabled="statusPop !== 1"
              clearable
              :props="{
                label: 'categoryName',
                value: 'categoryId',
                checkStrictly: true,
                emitPath: false,
              }"
            ></el-cascader>
            <el-input
              v-else
              :disabled="statusPop === 2"
              style="width: 150px"
              v-model="formtrop[items.prop]"
              ><template slot="append">{{ items.ch }}</template></el-input
            >
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import searchBox from "@/components/searchBox";
import tableList from "@/components/tableList";
import pagination from "@/components/pagination";
export default {
  components: { searchBox, tableList, pagination },
  data() {
    return {
      zzs: /^[0-9]+$/, //非负整数
      zs: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/, //非负数
      loading: false, //当前表单加载是否加载动画
      navText: {
        title: "考题配置",
        index: 0,
        ch: "项",
        num: true,
        choice: true,
        backFatherBtn: {
          status: false,
          title: "未定义",
        },
      },
      tableSet: [
        {
          label: "考试类型",
          prop: "categoryName",
          hidden: true,
        },
        {
          label: "及格分数",
          prop: "passingScore",
          hidden: true,
        },
        {
          label: "考试时长(分钟)",
          prop: "examTime",
          hidden: true,
          scope: "minute",
        },
        {
          label: "试卷分数",
          prop: "totalScore",
          hidden: true,
        },
        {
          label: "启用状态",
          prop: "status",
          hidden: true,
          scope: "status",
        },
      ], //表头信息
      tableData: [], //表单数据
      total: 0, //一共多少条
      pageSize: 10, //每页多少条数据
      currentPage: 1, //当前页码
      formList: [
        {
          label: "考试类型名称",
          prop: "categoryId",
          placeholder: "请输入考试类型名称",
        },
        {
          label: "启用状态",
          prop: "status",
          scope: "select",
          placeholder: "选择启用状态",
          options: [
            {
              label: "启用",
              value: 1,
            },
            {
              label: "关闭",
              value: 0,
            },
          ],
        },
      ], //搜索栏
      dialogVisible: false,
      formtrop: {},
      statusPop: -1, // 1添加 0修改 2详情
      listitem: [
        {
          label: "考试类型",
          prop: "categoryId",
          scope: "cascader",
          options: [],
        },
        {
          label: "及格分数",
          prop: "passingScore",
          ch: "分",
        },
        {
          label: "考试时长",
          prop: "examTime",
          ch: "分钟",
        },
        {
          label: "单选题",
          prop: "singleChoiceScore",
          prop2: "singleChoiceNum",
          scope: "more",
        },
        {
          label: "多选题",
          prop: "multipleChoiceScore",
          prop2: "multipleChoiceNum",
          scope: "more",
        },
        {
          label: "判断题",
          prop: "judgmentScore",
          prop2: "judgmentNum",
          scope: "more",
        },
        {
          label: "案例题",
          prop: "caseScore",
          prop2: "caseNum",
          scope: "more",
        },
        {
          label: "一套试卷合计分数：",
          prop: "totalScore",
          scope: "totalScores",
        },
        {
          label: "是否状态",
          prop: "status",
          scope: "select",
          options: [
            { label: "启用", value: 1 },
            {
              label: "关闭",
              value: 0,
            },
          ],
        },
      ],
      optionsTion: [],
    };
  },
  mounted() {
    this.search();
    this.initCascader();
  },
  methods: {
    totalScores() {},
    search(v) {
      if (v === undefined) {
        v = {
          status: "0,1",
          pageSize: this.pageSize,
          pageNum: this.currentPage,
        };
      }
      var data = {
        categoryId: v.categoryId,
        status: v.status === undefined ? "0,1" : v.status,
        pageSize: this.pageSize,
        pageNum: this.currentPage,
      };
      this.loading = true;
      this.$api
        .inquireexamconfigList(data)
        .then((res) => {
          this.tableData = res.rows;
          this.total = res.total;
          this.navText.index = res.total;
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    computedTotal() {
      var judgmen = this.formtrop.judgmentNum * this.formtrop.judgmentScore;
      var multipleChoice =
        this.formtrop.multipleChoiceNum * this.formtrop.multipleChoiceScore;
      var singleChoice =
        this.formtrop.singleChoiceNum * this.formtrop.singleChoiceScore;
      var casest = this.formtrop.caseNum * this.formtrop.caseScore;
      var allnum = judgmen + multipleChoice + singleChoice + casest;
      this.$set(this.formtrop, "totalScore", allnum);
    },
    init() {
      this.search();
    },
    del(row) {
      var data = row;
      data.status = -1;
      delete data.categoryId;
      this.$api.editexamconfig(data).then((res) => {
        this.$message.success("删除成功！");
        this.search();
      });
    },
    addClick(v, int) {
      if (v === undefined) {
        this.statusPop = 1;
        this.formtrop = {};
      } else {
        var data = v.id;
        this.$api.obtainconfigexam(data).then((res) => {
          console.log(res);
          res.data.examTime = res.data.examTime / 60;
          this.formtrop = res.data;
          console.log(int);
          if (int === 2) {
            this.statusPop = 2;
          } else {
            this.statusPop = 0;
          }
        });
      }
      this.dialogVisible = true;
    },
    submit() {
      if (!this.zs.test(this.formtrop.categoryId)) {
        this.$message.error("请选择考试类型");
        return;
      }
      if (!this.zs.test(this.formtrop.passingScore)) {
        this.$message.error("请重新输入及格分数，需输入非负数");
        return;
      }
      if (!this.zs.test(this.formtrop.examTime)) {
        this.$message.error("请重新输入考试时长，需输入非负数");
        return;
      }
      if (!this.zs.test(this.formtrop.singleChoiceScore)) {
        this.$message.error("请重新输入单选题分值，需输入非负数");
        return;
      }
      if (!this.zzs.test(this.formtrop.singleChoiceNum)) {
        this.$message.error("请重新输入抽取题目单选题数量，需输入非负整数");
        return;
      }
      if (!this.zs.test(this.formtrop.singleChoiceScore)) {
        this.$message.error("请重新输入多选题分值，需输入非负数");
        return;
      }
      if (!this.zzs.test(this.formtrop.multipleChoiceNum)) {
        this.$message.error("请重新输入抽取题目多选题数量，需输入非负整数");
        return;
      }
      if (!this.zs.test(this.formtrop.judgmentScore)) {
        this.$message.error("请重新输入判断题分值，需输入非负数");
        return;
      }
      if (!this.zzs.test(this.formtrop.judgmentNum)) {
        this.$message.error("请重新输入抽取题目判断题数量，需输入非负整数");
        return;
      }
      if (!this.zs.test(this.formtrop.caseScore)) {
        this.$message.error("请重新输入案例题分值，需输入非负数");
        return;
      }
      if (!this.zzs.test(this.formtrop.caseNum)) {
        this.$message.error("请重新输入抽取题目案例题数量，需输入非负整数");
        return;
      }
      if (this.formtrop.status === undefined) {
        this.$message.error("请选择状态");
        return;
      }
      if (this.statusPop === 1) {
        var bf = JSON.stringify(this.formtrop);
        var data = JSON.parse(bf);
        data.examTime = data.examTime * 60;
        this.$api.examconfig(data).then((res) => {
          this.$message.success("添加配置成功！");
          this.search();
          this.dialogVisible = false;
        });
      } else if (this.statusPop === 0) {
        var bf = JSON.stringify(this.formtrop);
        var data = JSON.parse(bf);
        data.examTime = data.examTime * 60;
        delete data.categoryId;
        this.$api.editexamconfig(data).then((res) => {
          this.$message.success("修改配置成功！");
          this.search();
          this.dialogVisible = false;
        });
      } else {
        this.dialogVisible = false;
      }
    },
    close() {
      this.$confirm("是否关闭该窗口", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.dialogVisible = false;
        })
        .catch(() => {});
    },
    handleSizeChange(v) {
      this.pageSize = v;
      this.currentPage = 1;
      this.search();
    },
    handleCurrentChange(v) {
      this.currentPage = v;
      this.search();
    },
    //级联选择器数据
    initCascader() {
      this.$api
        .inquireProfessionClassification()
        .then((res) => {
          this.arrayChangeType(res.rows);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 接口数据转换级联类型
    arrayChangeType(options) {
      let result = [];
      if (!Array.isArray(options)) {
        return result;
      }
      options.forEach((item) => {
        delete item.children;
      });
      let map = {};
      options.forEach((item) => {
        map[item.categoryId] = item;
      });
      options.forEach((item) => {
        let parent = map[item.pid];
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          result.push(item);
        }
      });
      result = result.sort(this.sortBy("sort", true));
      result.forEach((item, index) => {
        if (item.children) {
          item.children.sort(this.sortBy("sort", true));
        }
      });
      this.listitem.forEach((item, index) => {
        if (item.prop === "categoryId") {
          item.options = result;
          this.optionsTion = result;
        }
      });
      return result;
    },
    sortBy(attr, rev) {
      //第二个参数没有传递 默认升序排列
      if (rev == undefined) {
        rev = 1;
      } else {
        rev = rev ? 1 : -1;
      }

      return function (a, b) {
        a = a[attr];
        b = b[attr];
        if (a < b) {
          return rev * -1;
        }
        if (a > b) {
          return rev * 1;
        }
        return 0;
      };
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.el-button {
  border-radius: 8px;
}
/deep/.el-dialog {
  border-radius: 8px;
  .el-dialog__header {
    padding: 0;
    .hearders {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0px 18px 0px 20px;
      border-bottom: 1px solid #e2e2e2;
      .leftTitle {
        font-size: 14px;
        font-weight: bold;
        color: #2f4378;
      }
      .rightBoxs {
        display: flex;
        align-items: center;
        img {
          width: 14px;
          height: 14px;
          margin-left: 13px;
          cursor: pointer;
        }
      }
    }
  }
  .el-dialog__footer {
    padding: 0;
    .dialog-footer {
      padding: 0px 40px;
      height: 70px;
      border-top: 1px solid #e2e2e2;
      display: flex;
      align-items: center;
      justify-content: flex-end;
    }
  }
}
.imgBox {
  width: 100%;
  // height: 210px;
  border: 1px solid #e2e2e2;
  border-radius: 8px;
  padding: 8px 8px 3px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .imgLabel {
    flex: 1;
    width: 100%;
    border: 1px dotted #e2e2e2;
    color: #999;
    font-size: 14px;
    cursor: pointer;
    border-radius: 8px;
    .msPhoto {
      display: flex;
      justify-content: center;
      align-items: center;
      max-width: 100%;
      max-height: 270px;
      img {
        max-width: 100%;
        max-height: 270px;
      }
    }
    .imgbbx {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      i {
        font-weight: bold;
        margin: 14px 0;
        font-size: 24px;
      }
    }
  }
  p {
    margin: 5px 0px;
  }
}
</style>
