<template>
  <div id="questionBankManagement">
    <search-box ref="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="infoMessage(props.scope.row)"
          >详情</el-button
        >
        <el-button type="text" @click="modify(props.scope.row)">修改</el-button>
        <el-button type="text" @click="dels(props.scope.row)">删除</el-button>
      </template>
    </table-list>
    <pagination
      :total="total"
      :pageSize="pageSize"
      :currentPage="currentPage"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    />
    <el-dialog
      :visible.sync="dialogBox"
      width="920px"
      :show-close="false"
      :destroy-on-close="true"
      :fullscreen="fullscreen"
      :close-on-click-modal="false"
    >
      <div slot="title" class="hearders">
        <div class="leftTitle">
          {{ statusPop === 1 ? "添加" : statusPop === 0 ? "修改" : "详情" }}
        </div>
        <div class="rightBoxs">
          <img
            src="@/assets/images/Max@2x.png"
            alt=""
            @click="fullscreen = !fullscreen"
          />
          <img src="@/assets/images/Close@2x.png" alt="" @click="closeBefore" />
        </div>
      </div>
      <el-row class="contentBox" :span="24">
        <el-col :span="24" class="juscon">
          <el-steps :active="activeTableStatus">
            <el-step title="填写题库信息"></el-step>
            <el-step title="填写章节信息"></el-step>
          </el-steps>
        </el-col>
        <el-col :span="24" v-show="activeTableStatus === 1">
          <el-col :span="12">
            <el-col :span="24">
              <header>题库分类</header>
              <el-cascader
                style="width: 100%"
                v-model="poppleData.categoryId"
                :options="optionsTion"
                :size="'medium'"
                clearable
                :disabled="statusPop === 2"
                :props="{
                  label: 'categoryName',
                  value: 'categoryId',
                  checkStrictly: true,
                  emitPath: false,
                }"
              ></el-cascader>
            </el-col>
            <el-col :span="24">
              <header>题库名称：</header>
              <el-input
                :disabled="statusPop === 2"
                placeholder="请输入课程名称"
                v-model="poppleData.bankName"
              />
            </el-col>
            <el-col :span="24">
              <header>练习类型：</header>
              <el-radio-group
                v-model="poppleData.typeId"
                :disabled="statusPop === 2 || statusPop === 0"
                @change="changeisZTpaper"
              >
                <el-radio :label="1">普通练习</el-radio>
                <el-radio :label="2">押题试卷</el-radio>
                <el-radio :label="3">真题试卷</el-radio>
              </el-radio-group>
            </el-col>
            <el-col :span="24" v-if="isZTpaper">
              <header>主讲名师</header>
              <el-select
                :disabled="statusPop === 2"
                style="width: 100%"
                multiple
                v-model="poppleData.teacherIds"
                placeholder="请选择主讲名师"
              >
                <el-option
                  v-for="item in optionsTeach"
                  :key="item.teacherId"
                  :label="item.teacherName"
                  :value="item.teacherId"
                >
                </el-option>
              </el-select>
            </el-col>
            <el-col :span="24">
              <header>价格：</header>
              <el-input
                placeholder="请输入价格"
                :disabled="statusPop === 2"
                v-model="poppleData.price"
              >
                <template slot="append">元</template>
              </el-input>
            </el-col>
            <el-col :span="24">
              <header>排序：</header>
              <el-input-number
                :disabled="statusPop === 2"
                v-model="poppleData.sort"
                controls-position="right"
                :min="0"
                placeholder="请输入排序"
              ></el-input-number>
            </el-col>
          </el-col>
          <el-col :span="12">
            <el-col :span="24">
              <header>课程封面：</header>
              <div class="imgBox">
                <label class="imgLabel" for="inputs">
                  <div class="msPhoto" v-if="poppleData.coverUrl">
                    <img
                      :src="$methodsTools.splitImgHost(poppleData.coverUrl)"
                      alt="图片加载失败"
                    />
                  </div>
                  <div class="imgbbx" v-else>
                    <p style="margin-top: 49px">
                      点击添加或将文件拖拽到这里上传
                    </p>
                    <i class="el-icon-plus"></i>
                    <p style="margin-bottom: 37px">
                      图片格式：.jpg/.png/jpeg/bmp
                    </p>
                  </div>
                  <input
                    :disabled="statusPop === 2"
                    id="inputs"
                    type="file"
                    ref="file"
                    style="display: none"
                    @change="getImgFile"
                  />
                </label>
                <p style="color: #999999">请上传比例为16:9且小于2m的图片</p>
              </div>
            </el-col>
            <el-col :span="24">
              <header>是否启用：</header>
              <el-radio-group
                v-model="poppleData.status"
                :disabled="statusPop === 2"
              >
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-col>
          </el-col>
          <el-col :span="24">
            <el-col :span="24">
              <header>课程简介：</header>
              <div
                style="
                  max-height: 300px;
                  overflow-y: auto;
                  border: 1px solid #e2e2e2;
                  border-radius: 8px;
                  padding: 13px;
                "
                v-if="statusPop === 2"
                v-html="poppleData.introduction"
              ></div>
              <editor
                v-else
                v-model="poppleData.introduction"
                :min-height="100"
                :max-height="300"
                :uploadStatus="uploadStatus"
              /> </el-col
          ></el-col>
        </el-col>
        <el-col :span="24" v-show="activeTableStatus === 2">
          <div v-if="showTKtype === 1">
            <div>
              <el-button type="primary" @click="changeList({ level: 0 }, 0)"
                >添加章节</el-button
              >
              <el-button>导入章节</el-button>
            </div>
            <div>
              <el-table
                align="center"
                ref="pager"
                :data="tableDatas"
                style="width: 100%"
                row-key="id"
                :load="load"
                lazy
                @expand-change="expandChange"
                :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren',
                }"
                destroy-on-close
                :key="Math.random()"
              >
                <el-table-column type="index" width="50" label="序号">
                </el-table-column>
                <el-table-column
                  v-for="(item, index) in poppleTableHeader"
                  :key="index"
                  :label="item.label"
                  :width="item.width"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span v-if="item.scope === 'level'">{{
                      scope.row[item.prop] === 0 ? "章" : "节"
                    }}</span>
                    <span v-else>{{ scope.row[item.prop] }}</span>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  align="center"
                  fixed="right"
                  width="180px"
                >
                  <template slot-scope="scope">
                    <div v-if="scope.row.level === 0">
                      <el-button type="text" @click="changeList(scope.row, 0)"
                        >添加下级</el-button
                      >
                      <el-button type="text" @click="changeList(scope.row, 1)"
                        >修改</el-button
                      >
                      <el-button type="text" @click="delF(scope.row)"
                        >删除</el-button
                      >
                    </div>
                    <div v-else>
                      <el-button type="text" @click="xqpaperTopic(scope.row)"
                        >详情题目</el-button
                      >
                      <el-button type="text" @click="changeList(scope.row, 1)"
                        >修改</el-button
                      >
                      <el-button type="text" @click="delFChild(scope.row)"
                        >删除</el-button
                      >
                    </div>
                  </template></el-table-column
                >
              </el-table>
              <el-dialog
                width="520px"
                :visible.sync="innerVisible"
                append-to-body
                :show-close="false"
                :fullscreen="fullscreenChild"
                :close-on-click-modal="false"
              >
                <div slot="title" class="hearders">
                  <div class="leftTitle">
                    {{ int === 0 ? "添加" : "修改" }}
                  </div>
                  <div class="rightBoxs">
                    <img
                      src="@/assets/images/Max@2x.png"
                      alt=""
                      @click="fullscreenChild = !fullscreenChild"
                    />
                    <img
                      src="@/assets/images/Close@2x.png"
                      alt=""
                      @click="closeBeforeChild"
                    />
                  </div>
                </div>
                <el-col :span="24">
                  <el-col :span="18" style="margin: 30px 0px 10px">
                    <el-form label-width="150px">
                      <el-form-item
                        v-for="(items, indexs) in formTables"
                        :key="indexs"
                        :label="items.label"
                      >
                        <el-input
                          v-if="items.scope === 'dis'"
                          v-model="formTableChild[items.prop]"
                          :placeholder="items.placeholder"
                          :disabled="formTableChild.level === 0 ? true : false"
                        ></el-input>
                        <el-radio-group
                          v-else-if="items.scope === 'radio'"
                          v-model="formTableChild.status"
                        >
                          <el-radio :label="1">是</el-radio>
                          <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                        <el-input
                          v-else
                          v-model="formTableChild[items.prop]"
                          :placeholder="items.placeholder"
                        ></el-input>
                      </el-form-item>
                    </el-form>
                  </el-col>
                </el-col>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="closeBeforeChild">取 消</el-button>
                  <el-button type="primary" @click="submitChild"
                    >确 定</el-button
                  >
                </span>
              </el-dialog>
            </div>
            <pagination
              :total="totalChild"
              :pageSize="pageSizeChild"
              :currentPage="currentPageChild"
              @handleSizeChange="handleSizeChangeChild"
              @handleCurrentChange="handleCurrentChangeChild"
            />
          </div>
          <div v-if="showTKtype === 2">
            <div>
              <el-button type="primary" @click="paperAddORChange"
                >添加试卷</el-button
              >
              <el-button>导入试卷</el-button>
            </div>
            <div>
              <el-table
                ref="pager"
                :data="tableDataspaper"
                style="width: 100%"
                destroy-on-close
                :key="Math.random()"
              >
                <el-table-column
                  type="index"
                  width="50"
                  label="序号"
                  align="center"
                >
                </el-table-column>
                <el-table-column
                  v-for="(item, index) in poppleTableHeaderpaper"
                  :key="index"
                  :label="item.label"
                  :width="item.width"
                  align="center"
                >
                  <template slot-scope="scope">
                    <span>{{ scope.row[item.prop] }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" fixed="right">
                  <template slot-scope="scope">
                    <el-button type="text" @click="xqpaperTopic(scope.row)"
                      >详情题目</el-button
                    >
                    <el-button type="text" @click="paperAddORChange(scope.row)"
                      >修改</el-button
                    >
                    <el-button type="text" @click="delPaper(scope.row)"
                      >删除</el-button
                    >
                  </template></el-table-column
                >
              </el-table>
              <el-dialog
                width="520px"
                :visible.sync="innerVisiblePaper"
                append-to-body
                :show-close="false"
                :fullscreen="fullscreenChildPaper"
                :close-on-click-modal="false"
              >
                <div slot="title" class="hearders">
                  <div class="leftTitle">
                    {{ statusPaperDia === 1 ? "添加" : "修改" }}
                  </div>
                  <div class="rightBoxs">
                    <img
                      src="@/assets/images/Max@2x.png"
                      alt=""
                      @click="fullscreenChildPaper = !fullscreenChildPaper"
                    />
                    <img
                      src="@/assets/images/Close@2x.png"
                      alt=""
                      @click="closeBeforeChildPaper"
                    />
                  </div>
                </div>
                <el-col :span="24">
                  <el-col :span="18" style="margin: 30px 0px 10px">
                    <el-form label-width="150px">
                      <el-form-item
                        v-for="(items, indexs) in formTablesPaper"
                        :key="indexs"
                        :label="items.label"
                      >
                        <el-input
                          v-if="items.scope === 'dis'"
                          v-model="formTableChildPaper[items.prop]"
                          :placeholder="items.placeholder"
                          :disabled="
                            formTableChildPaper.level === 0 ? true : false
                          "
                        ></el-input>
                        <el-radio-group
                          v-else-if="items.scope === 'radio'"
                          v-model="formTableChildPaper.status"
                        >
                          <el-radio :label="1">是</el-radio>
                          <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                        <el-input
                          v-else
                          v-model="formTableChildPaper[items.prop]"
                          :placeholder="items.placeholder"
                        ></el-input>
                      </el-form-item>
                    </el-form>
                  </el-col>
                </el-col>
                <span slot="footer" class="dialog-footer">
                  <el-button @click="closeBeforeChildPaper">取 消</el-button>
                  <el-button type="primary" @click="submitnewPaper"
                    >确 定</el-button
                  >
                </span>
              </el-dialog>
            </div>
            <pagination
              :total="totalChildTopic"
              :pageSize="pageSizeChildTopic"
              :currentPage="currentPageChildTopic"
              @handleSizeChange="handleSizeChangeChildTopic"
              @handleCurrentChange="handleCurrentChangeChildTopic"
            />
          </div>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button @click="backTable" v-if="activeTableStatus !== 1"
          >上一步</el-button
        >
        <el-button @click="closeBefore">取 消</el-button>
        <el-button
          v-if="activeTableStatus === 1"
          type="primary"
          @click="submitTabel"
          >下一步</el-button
        ><el-button
          v-if="activeTableStatus === 2"
          type="primary"
          @click="dialogBox = false"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import searchBox from "@/components/searchBox";
import tableList from "@/components/tableList";
import pagination from "@/components/pagination";
import Editor from "@/components/Editor";
export default {
  components: { searchBox, tableList, pagination, Editor },
  data() {
    return {
      uploadStatus: 2, //富文本组件传值
      loading: false, //当前表单加载是否加载动画
      isZTpaper: true, //主讲老师列表是否显示
      navText: {
        title: "题库合计",
        index: 0,
        ch: "个",
        num: true,
        choice: true,
        backFatherBtn: {
          status: false,
          title: "未定义",
        },
      },
      formTableChild: {},
      formTableChildPaper: {},
      formTables: [
        {
          label: "名称",
          prop: "name",
          placeholder: "输入名称",
        },
        {
          label: "排序",
          prop: "sort",
          placeholder: "输入排序",
        },
        {
          label: "是否启用",
          prop: "status",
          scope: "radio",
        },
      ],
      formTablesPaper: [
        {
          label: "名称",
          prop: "name",
          placeholder: "输入名称",
        },
        {
          label: "排序",
          prop: "sort",
          placeholder: "输入排序",
        },
        {
          label: "是否启用",
          prop: "status",
          scope: "radio",
        },
      ], //试卷添加或修改表单
      tableSet: [
        {
          label: "题库名称",
          prop: "bankName",
          hidden: true,
          width: "150px",
        },
        {
          label: "题库类型",
          prop: "categoryName",
          hidden: true,
          width: "150px",
        },
        {
          label: "练习类型",
          prop: "typeId",
          hidden: true,
          scope: "typeId",
        },
        {
          label: "排序",
          prop: "sort",
          hidden: true,
        },
        {
          label: "题目个数",
          prop: "questionNum",
          hidden: true,
        },
        {
          label: "启用状态",
          prop: "status",
          hidden: true,
          scope: "status",
        },
      ], //表头信息
      showTKtype: 0, //1：章节表格 2：试卷表格
      tableData: [], //表单数据

      total: 0, //一共多少条
      pageSize: 10, //每页多少条数据
      currentPage: 1, //当前页码

      totalChild: 0, //一共多少条
      pageSizeChild: 5, //每页多少条数据
      currentPageChild: 1, //当前页码

      totalChildTopic: 0, //一共多少条
      pageSizeChildTopic: 5, //每页多少条数据
      currentPageChildTopic: 1, //当前页码

      formList: [
        {
          label: "题库名称",
          prop: "bankName",
          placeholder: "输入题库名称",
        },
        {
          label: "启用状态",
          prop: "status",
          scope: "select",
          placeholder: "选择启用状态",
          options: [
            {
              label: "启用",
              value: 1,
            },
            {
              label: "关闭",
              value: 0,
            },
          ],
        },
        {
          label: "题库类型",
          prop: "categoryId",
          scope: "cascader",
          placeholder: "选择题库类型",
          options: [],
          props: {
            label: "categoryName",
            value: "categoryId",
          },
        },
        {
          label: "练习类型",
          prop: "typeId",
          scope: "select",
          placeholder: "选择练习类型",
          options: [
            {
              label: "普通练习",
              value: 1,
            },
            {
              label: "押题试卷",
              value: 2,
            },
            {
              label: "真题试卷",
              value: 3,
            },
          ],
        },
      ], //搜索栏
      optionsTion: [],
      optionsTeach: [],
      poppleData: {},
      fullscreen: false,
      fullscreenChild: false,
      fullscreenChildPaperTopic: false,
      dialogBox: false,
      innerVisible: false,
      statusPop: 0,
      beif: "", //备份数据
      activeTableStatus: 1, //步骤条当前状态
      tableDatas: [], //表格数据
      poppleTableHeader: [
        {
          label: "名称",
          prop: "name",
          width: "150px",
        },
        {
          label: "级别",
          prop: "level",
          width: "80px",
          scope: "level",
        },
        {
          label: "题目数量",
          prop: "questionNum",
          width: "150px",
        },
        {
          label: "排序",
          prop: "sort",
        },
      ], //表头数据
      tableDataspaper: [], //试卷数据
      poppleTableHeaderpaper: [
        {
          label: "名称",
          prop: "name",
          width: "150px",
        },
        {
          label: "题目数量",
          prop: "questionNum",
          width: "150px",
        },
        {
          label: "排序",
          prop: "sort",
        },
      ], //试卷表头数据
      innerVisiblePaper: false,
      fullscreenChildPaper: false,
      innerVisiblePaperTopic: false,
      formTablesPaperTopic: [
        {
          label: "类型：",
          prop: "type",
          scope: "radio",
          options: [
            {
              label: "单选题",
              value: 1,
            },
            {
              label: "多选题",
              value: 2,
            },
            {
              label: "判断题",
              value: 3,
            },
            {
              label: "案例题",
              value: 4,
            },
          ],
          optionschild: [
            {
              label: "单选题",
              value: 1,
            },
            {
              label: "多选题",
              value: 2,
            },
            {
              label: "判断题",
              value: 3,
            },
          ],
        },
        {
          label: "题目：",
          prop: "content",
          scope: "textarea",
          placeholder: "请输入题目",
        },
        {
          label: "图片：",
          prop: "imgUrl",
          scope: "photo",
        },
        {
          label: "选项",
          prop: "options",
          scope: "options",
        },
        {
          label: "正确答案",
          prop: "asd",
          scope: "optionsResult",
        },
        {
          label: "答案解析",
          prop: "analysisContent",
          scope: "textarea",
        },
      ],
      formTopic: [],
      int: -1,
      statusPaperDia: 0, //添加试卷窗口 当前状态为添加1还是修改0
      treeObj: {},
      priceTest: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
    };
  },
  mounted() {
    this.search();
    this.initCascader();
    this.initTeacherList();
  },
  methods: {
    changeisZTpaper(v) {
      if (v === 3) {
        this.isZTpaper = false;
      } else {
        this.isZTpaper = true;
      }
    },
    // 初始化教师列表
    initTeacherList() {
      var data = {
        status: "0,1",
      };
      this.$api.inquireCourseTeacher(data).then((res) => {
        console.log(res);
        this.optionsTeach = res.rows;
      });
    },
    //级联选择器数据
    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.formList.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;
      };
    },
    backTable() {
      if (this.statusPop === 1) {
        this.statusPop = 0;
        this.activeTableStatus--;
      } else {
        this.activeTableStatus--;
      }
    },
    nextTable() {
      this.activeTableStatus++;
    },
    getImgFile() {
      var self = this;
      var file = this.$refs.file.files[0];
      if (file === undefined) {
        self.$set(self.poppleData, "coverUrl", "");
        return;
      }
      if (file.size > 2 * 1024 * 1024) {
        this.$message.error("图片不得大于2MB");
        return;
      }
      var type = this.$refs.file.value.toLowerCase().split(".").splice(-1);
      if (
        type[0] != "jpg" &&
        type[0] != "png" &&
        type[0] != "jpeg" &&
        type[0] != "bmp"
      ) {
        this.$message.error("上传格式需为：.jpg/.png/.jpeg/bmp");
        this.$refs.file.value = "";
        return;
      }
      var reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = function (ev) {
        self.$set(self.poppleData, "coverUrl", ev.target.result);
      };
    },
    // 试卷题目图片
    getImgFiletopic(options, childIndex, e) {
      if (childIndex !== null) {
        var self = this;
        var indexNum = -1;
        var indexChildNum = -1;
        this.formTopic.forEach((item, index) => {
          if (item.questionId === options.questionId) {
            indexNum = index;
            item.jsonStr.forEach((i, l) => {
              if (l === childIndex) {
                indexChildNum = l;
              }
            });
          }
        });
        var file = e.target.files[0];
        if (file === undefined) {
          self.$set(
            self.formTopic[indexNum].jsonStr[indexChildNum],
            "imgUrl",
            ""
          );
          return;
        }
        if (file.size > 2 * 1024 * 1024) {
          this.$message.error("图片不得大于2MB");
          return;
        }
        var type = e.target.value.toLowerCase().split(".").splice(-1);
        if (
          type[0] != "jpg" &&
          type[0] != "png" &&
          type[0] != "jpeg" &&
          type[0] != "bmp"
        ) {
          this.$message.error("上传格式需为：.jpg/.png/.jpeg/bmp");
          e.target.value = "";
          return;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (ev) {
          self.$set(
            self.formTopic[indexNum].jsonStr[indexChildNum],
            "imgUrl",
            ev.target.result
          );
        };
      } else {
        var self = this;
        var indexNum = -1;
        this.formTopic.forEach((item, index) => {
          if (item.questionId === options.questionId) {
            indexNum = index;
          }
        });
        var file = e.target.files[0];
        if (file === undefined) {
          self.$set(self.formTopic[indexNum], "imgUrl", "");
          return;
        }
        if (file.size > 2 * 1024 * 1024) {
          this.$message.error("图片不得大于2MB");
          return;
        }
        var type = e.target.value.toLowerCase().split(".").splice(-1);
        if (
          type[0] != "jpg" &&
          type[0] != "png" &&
          type[0] != "jpeg" &&
          type[0] != "bmp"
        ) {
          this.$message.error("上传格式需为：.jpg/.png/.jpeg/bmp");
          e.target.value = "";
          return;
        }
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (ev) {
          self.$set(self.formTopic[indexNum], "imgUrl", ev.target.result);
        };
      }
    },
    // 详情
    infoMessage(options) {
      var data = options.bankId;
      this.$api.obtainbank(data).then((res) => {
        this.poppleData = res.data;
        if (res.data.typeId === 3) {
          this.isZTpaper = false;
        } else {
          this.isZTpaper = true;
          this.poppleData.teacherIds = res.data.teacherIds
            .split(",")
            .map(Number);
        }
        this.beif = res.data.coverUrl;
      });
      this.statusPop = 2;
      this.activeTableStatus = 1;
      this.dialogBox = true;
    },
    //添加
    addClick() {
      this.poppleData = {};
      this.tableDatas = [];
      this.statusPop = 1;
      this.activeTableStatus = 1;
      this.dialogBox = true;
    },
    // 修改
    modify(options) {
      var data = options.bankId;
      this.$api.obtainbank(data).then((res) => {
        console.log(res);
        this.poppleData = res.data;
        if (res.data.typeId === 3) {
          this.isZTpaper = false;
        } else {
          this.isZTpaper = true;
          if (this.poppleData.teacherIds === null) {
          } else {
            this.poppleData.teacherIds = res.data.teacherIds
              .split(",")
              .map(Number);
          }
        }
        this.beif = res.data.coverUrl;
      });
      this.statusPop = 0;
      this.activeTableStatus = 1;
      this.dialogBox = true;
    },
    //确定提交
    async submitTabel() {
      var self = this;
      if (
        this.poppleData.categoryId === undefined ||
        this.poppleData.categoryId === null
      ) {
        this.$message.error("请选择题库分类");
        return;
      }
      if (!this.poppleData.bankName) {
        this.$message.error("请输入题库名称");
        return;
      }
      if (this.poppleData.typeId === undefined) {
        this.$message.error("请选择练习类型");
        return;
      }
      if (this.poppleData.typeId === 3) {
        this.poppleData.teacherIds = "";
      } else {
        if (
          !this.poppleData.teacherIds ||
          this.poppleData.teacherIds.length === 0
        ) {
          this.$message.error("请选择主讲名师");
          return;
        }
      }
      if (this.poppleData.price === undefined) {
        this.$message.error("请输入价格");
        return;
      }
      if (this.poppleData.sort === undefined) {
        this.$message.error("请输入排序");
        return;
      }
      if (!this.priceTest.test(this.poppleData.price)) {
        this.$message.error("请输入正确价格");
        this.poppleData.price = "";
        return;
      }
      if (!this.poppleData.introduction) {
        this.$message.error("请输入课程简介");
        return;
      }
      if (this.poppleData.status === undefined) {
        this.$message.error("请选择是否启用该课程");
        return;
      }
      if (!this.poppleData.coverUrl || this.poppleData.coverUrl.length === 0) {
        this.$message.error("请上传课程封面");
        return;
      }
      var data = {
        categoryId: this.poppleData.categoryId,
        bankName: this.poppleData.bankName,
        typeId: this.poppleData.typeId,
        introduction: this.poppleData.introduction,
        price: this.poppleData.price,
        status: this.poppleData.status,
        sort: this.poppleData.sort,
        teacherIds:
          this.poppleData.typeId !== 3
            ? this.poppleData.teacherIds.join(",")
            : "",
      };
      if (this.statusPop === 1) {
        const awtimg = await this.imgUpload(2);
        data.coverUrl = this.poppleData.coverUrl;
        this.submitFun(data);
      } else if (this.statusPop === 0) {
        data.bankId = this.poppleData.bankId;
        if (
          this.poppleData.coverUrl === this.beif &&
          this.poppleData.coverUrl.length !== 0
        ) {
          this.submitFun(data);
        } else {
          const awtimg = await this.imgUpload(2);
          data.coverUrl = this.poppleData.coverUrl;
          this.submitFun(data);
        }
      } else if (this.statusPop === 2) {
        if (this.poppleData.typeId === 1) {
          this.showTKtype = 1;
          this.getZJList(this.poppleData.bankId).then(() => {
            this.nextTable();
          });
        } else {
          this.showTKtype = 2;
          this.getPAPERList(this.poppleData.bankId).then(() => {
            this.nextTable();
          });
        }
      }
    },
    submitFun(data) {
      if (data.bankId) {
        this.$api
          .editbank(data)
          .then((res) => {
            console.log(res);
            this.$message.success("修改成功!");
            this.search();
            if (this.poppleData.typeId === 1) {
              this.showTKtype = 1;
              this.getZJList(data.bankId).then(() => {
                this.nextTable();
              });
            } else {
              this.showTKtype = 2;
              this.getPAPERList(this.poppleData.bankId).then(() => {
                this.nextTable();
              });
            }
          })
          .catch((err) => {
            this.$message.error(err);
          });
      } else {
        this.$api
          .addbank(data)
          .then((res) => {
            this.$message.success("添加成功!");
            this.search();
            this.poppleData.bankId = res.log.primary_key_id;
            if (this.poppleData.typeId === 1) {
              this.showTKtype = 1;
              this.getZJList(res.log.primary_key_id).then(() => {
                this.nextTable();
              });
            } else {
              this.showTKtype = 2;
              this.getPAPERList(this.poppleData.bankId).then(() => {
                this.nextTable();
              });
            }
          })
          .catch((err) => {
            this.$message.error(err);
          });
      }
    },
    //获取大章
    getZJList(index) {
      var self = this;
      return new Promise((resolve, reject) => {
        var data = {
          bankId: index,
          status: "0,1",
          pageSize: this.pageSizeChild,
          pageNum: this.currentPageChild,
        };
        var nullBox = [];
        this.$api.inquirebankchapterList(data).then((res) => {
          res.rows.forEach((item) => {
            item.id = item.bankChapterId + "";
            item.level = 0;
            item.hasChildren = true;
            nullBox.push(item);
          });
          nullBox.sort(self.sortBy("sort", true));
          self.tableDatas = nullBox;
          self.totalChild = res.total;
          resolve();
        });
      });
    },
    //获取试卷
    getPAPERList(index) {
      var self = this;
      return new Promise((resolve, reject) => {
        var data = {
          bankId: index,
          status: "0,1",
          pageSize: this.pageSizeChildTopic,
          pageNum: this.currentPageChildTopic,
        };
        var nullBox = [];
        this.$api.inquirebankexamList(data).then((res) => {
          res.rows.forEach((item) => {
            // item.id = item.bankChapterId + "";
            // item.level = 0;
            item.hasChildren = true;
            nullBox.push(item);
          });
          nullBox.sort(self.sortBy("sort", true));
          self.tableDataspaper = nullBox;
          self.totalChildTopic = res.total;
          resolve();
        });
      });
    },
    imgUpload(int) {
      var self = this;
      return new Promise((resolve, reject) => {
        this.$upload
          .upload(this.$refs.file.files[0], int)
          .then((res) => {
            self.poppleData.coverUrl = res;
            resolve();
          })
          .catch((err) => {
            self.$message.error("图片上传错误");
          });
      });
    },

    //删除
    dels(options) {
      console.log(options);
      var self = this;
      this.$confirm("此操作将删除该课程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var data = {
            bankId: options.bankId,
            categoryId: options.categoryId,
            bankName: options.bankName,
            teacherIds: "",
            price: options.price,
            status: -1,
            typeId: options.typeId,
          };
          this.$api
            .editbank(data)
            .then((res) => {
              this.$message.success("删除成功!");
              this.search();
            })
            .catch((err) => {
              this.$message.error("删除失败：" + err);
            });
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    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;
      };
    },
    search(v,os) {
      if (os) {
        this.currentPage = 1;
      }
      if (v === undefined) {
        v = {};
      }
      var data = {
        bankName: v.bankName || "",
        categoryId: v.categoryId || "",
        status: v.status === undefined ? "0,1" : v.status,
        typeId: v.typeId,
        pageSize: this.pageSize,
        pageNum: this.currentPage,
      };
      this.loading = true;
      this.$api
        .inquirebankList(data)
        .then((res) => {
          this.tableData = res.rows;
          this.total = res.total;
          this.navText.index = res.total;
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    init() {
      this.search();
    },
    //窗口关闭
    closeBefore() {
      this.dialogBox = false;
      this.fullscreen = false;
      this.poppleData = {};
    },
    closeBeforeChild() {
      this.innerVisible = false;
      this.fullscreenChild = false;
      // this.poppleData = {};
    },
    closeBeforeChildPaper() {
      this.innerVisiblePaper = false;
          this.fullscreenChildPaper = false;
    },
    closeBeforeChildPaperTopic() {
      this.innerVisiblePaperTopic = false;
          this.innerVisiblePaperTopic = false;
    },
    handleSizeChange(v) {
      this.pageSize = v;
      this.currentPage = 1;
      this.search(this.$refs.search_box.formData);
    },
    handleCurrentChange(v) {
      this.currentPage = v;
      this.search(this.$refs.search_box.formData);
    },

    handleSizeChangeChild(v) {
      this.pageSizeChild = v;
      this.currentPageChild = 1;
      this.getZJList(this.poppleData.bankId);
    },
    handleCurrentChangeChild(v) {
      this.currentPageChild = v;
      this.getZJList(this.poppleData.bankId);
    },

    handleSizeChangeChildTopic(v) {
      this.pageSizeChildTopic = v;
      this.currentPageChildTopic = 1;
      this.getPAPERList(this.poppleData.bankId);
    },
    handleCurrentChangeChildTopic(v) {
      this.currentPageChildTopic = v;
      this.getPAPERList(this.poppleData.bankId);
    },

    //点击多级触发异步
    async load(tree, treeNode, resolve) {
      this.treeObj[tree.bankChapterId] = { tree, treeNode, resolve };
      var data = {
        status: "0,1",
        bankChapterId: tree.bankChapterId,
      };
      const loadChildren = await this.$api.inquirebanksectionList(data);
      if (Array.isArray(loadChildren.rows) && loadChildren.rows.length > 0) {
        loadChildren.rows.forEach((item) => {
          item.id = tree.bankChapterId + "." + item.bankSectionId;
          item.level = 1;
        });
        loadChildren.rows.sort(this.sortBy("sort", true));
        if (loadChildren.rows === 0) {
          this.$message.warning("暂无下级");
        }
        resolve(loadChildren.rows); // 返回最终数据对象
      } else {
        tree.children = [];
        resolve([]);
      }
    },
    //添加or修改章节or子节
    changeList(row, int) {
      console.log(row);
      this.int = int;
      var kelone = JSON.stringify(row);
      this.formTableChild = JSON.parse(kelone);
      if (int === 0 && row.bankId !== undefined) {
        this.formTableChild = {
          level: 1,
          bankId: row.bankId,
          bankChapterId: row.bankChapterId,
        };
      }
      this.innerVisible = true;
    },
    expandChange() {
      console.log(111);
    },
    // 修改子节点
    changeTableList() {
      var data = {
        bankChapterId: this.formTableChild.bankChapterId,
        bankSectionId: this.formTableChild.bankSectionId,
        name: this.formTableChild.name,
        sort: this.formTableChild.sort,
        status: this.formTableChild.status,
      };
      this.$api.editbanksection(data).then((res) => {
        this.$message.success("修改成功");
        this.getZJList(this.poppleData.bankId);

        // 处理懒加载节点，先清空再渲染。
        // 利用refs得到表格的数据结构，拿到 lazyTreeNodeMap 这个懒加载对象。
        // 这里面存储的就是你之前加载的所有节点数据对象了。然后清空操作节点的父节点对象。
        this.$refs.pager.store.states.lazyTreeNodeMap[
          this.formTableChild.bankChapterId
        ] = [];
        // 根据我们声明的maps对象，拿到父节点。然后手动进行接口请求，重新进行数据渲染。
        const { tree, treeNode, resolve } =
          this.treeObj[this.formTableChild.bankChapterId];
        this.load(tree, treeNode, resolve);
        this.innerVisible = false;
      });
    },

    //章节操作
    submitChild() {
      if (this.formTableChild.name === undefined) {
        this.$message.error("请输入名字");
        return;
      }
      if (this.formTableChild.sort === undefined) {
        this.$message.error("请输入排序");
        return;
      }
      if (this.formTableChild.status === undefined) {
        this.$message.error("请选择是否启用");
        return;
      }
      // int = 0 添加
      if (this.int === 0) {
        if (this.formTableChild.bankChapterId) {
          //添加下级
          var data = {
            bankChapterId: this.formTableChild.bankChapterId,
            name: this.formTableChild.name,
            sort: this.formTableChild.sort,
            status: this.formTableChild.status,
          };
          this.$api.addbanksection(data).then((res) => {
            this.$message.success("添加下级成功");
            this.getZJList(this.poppleData.bankId);
            if (
              this.$refs.pager.store.states.lazyTreeNodeMap[
                this.formTableChild.bankChapterId
              ] === undefined
            ) {
            } else {
              this.$refs.pager.store.states.lazyTreeNodeMap[
                this.formTableChild.bankChapterId
              ] = [];
              // 根据我们声明的maps对象，拿到父节点。然后手动进行接口请求，重新进行数据渲染。
              const { tree, treeNode, resolve } =
                this.treeObj[this.formTableChild.bankChapterId];
              this.load(tree, treeNode, resolve);
            }
            this.innerVisible = false;
          });
        } else {
          // 添加章节
          var data = {
            bankId: this.poppleData.bankId,
            name: this.formTableChild.name,
            sort: this.formTableChild.sort,
            status: this.formTableChild.status,
          };
          this.$api.addbankchapter(data).then((res) => {
            this.$message.success("添加成功");
            this.getZJList(this.poppleData.bankId);
            this.innerVisible = false;
          });
        }
      }
      //int = 1 修改
      if (this.int === 1) {
        // 章修改
        if (this.formTableChild.bankSectionId === undefined) {
          var data = {
            bankId: this.poppleData.bankId,
            bankChapterId: this.formTableChild.bankChapterId,
            name: this.formTableChild.name,
            sort: this.formTableChild.sort,
            status: this.formTableChild.status,
          };
          this.$api.editbankchapter(data).then((res) => {
            this.$message.success("修改成功");
            this.getZJList(this.poppleData.bankId);
            this.innerVisible = false;
          });
        } else {
          // 节点修改
          this.changeTableList();
        }
      }
    },
    delF(row) {
      this.$confirm("是否确认删除该章？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var data = {
            bankId: this.poppleData.bankId,
            bankChapterId: row.bankChapterId,
            name: row.name,
            sort: row.sort,
            status: -1,
          };
          this.$api.editbankchapter(data).then((res) => {
            this.$message.success("删除成功");
            this.getZJList(this.poppleData.bankId);
            this.innerVisible = false;
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    delFChild(rowsz) {
      this.$confirm("是否确认删除该节？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var data = {
            bankChapterId: rowsz.bankChapterId,
            bankSectionId: rowsz.bankSectionId,
            name: rowsz.name,
            sort: rowsz.sort,
            status: -1,
          };
          this.$api.editbanksection(data).then((res) => {
            this.$message.success("删除成功");
            this.getZJList(this.poppleData.bankId);

            // 处理懒加载节点，先清空再渲染。
            // 利用refs得到表格的数据结构，拿到 lazyTreeNodeMap 这个懒加载对象。
            // 这里面存储的就是你之前加载的所有节点数据对象了。然后清空操作节点的父节点对象。
            this.$refs.pager.store.states.lazyTreeNodeMap[rowsz.bankChapterId] =
              [];
            // 根据我们声明的maps对象，拿到父节点。然后手动进行接口请求，重新进行数据渲染。
            const { tree, treeNode, resolve } =
              this.treeObj[rowsz.bankChapterId];
            this.load(tree, treeNode, resolve);
            this.innerVisible = false;
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //添加试卷或修改试卷窗口
    paperAddORChange(options) {
      if (options.examId) {
        // 执行修改操作
        this.statusPaperDia = 0;
        this.formTableChildPaper = options;
      } else {
        // 执行添加操作
        this.statusPaperDia = 1;
        this.formTableChildPaper = {
          bankId: this.poppleData.bankId,
        };
      }
      this.innerVisiblePaper = true;
    },
    //提交试卷修改或添加操作
    submitnewPaper() {
      if (!this.formTableChildPaper.name) {
        this.$message.error("请输入试卷名称");
        return;
      }
      if (this.formTableChildPaper.sort === undefined) {
        this.$message.error("请输入试卷排序");
        return;
      }
      if (this.formTableChildPaper.status === undefined) {
        this.$message.error("请选择该试卷是否启用");
        return;
      }
      var data = {
        bankId: this.formTableChildPaper.bankId,
        name: this.formTableChildPaper.name,
        sort: this.formTableChildPaper.sort,
        status: this.formTableChildPaper.status,
      };
      if (this.statusPaperDia === 0) {
        (data.examId = this.formTableChildPaper.examId),
          this.$api.editbankexam(data).then(() => {
            this.$message.success("试卷修改成功!");
            this.getPAPERList(data.bankId).then((res) => {
              this.innerVisiblePaper = false;
            });
          });
      }
      if (this.statusPaperDia === 1) {
        this.$api.addbankexam(data).then(() => {
          this.$message.success("试卷添加成功!");
          this.getPAPERList(data.bankId).then((res) => {
            this.innerVisiblePaper = false;
          });
        });
      }
    },
    delPaper(options) {
      this.$confirm("此操作将删除该试卷, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var data = {
            bankId: options.bankId,
            examId: options.examId,
            name: options.name,
            sort: options.sort,
            status: -1,
          };
          this.$api.editbankexam(data).then(() => {
            this.$message.success("删除成功!");
            this.getPAPERList(data.bankId).then((res) => {
              this.innerVisiblePaper = false;
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //查看详情题目
    xqpaperTopic(v) {
      console.log(this.poppleData);
      if (v.bankSectionId) {
        var data = {
          bankSectionId: v.bankSectionId,
        };
      } else {
        var data = {
          examId: v.examId,
        };
      }
      data.typeId = this.poppleData.typeId;
      this.$router.push({
        path: "/questionBank",
        query: data,
      });
    },
    //新增题目
    addItem(v) {
      this.formTopic = [{}];
      this.innerVisiblePaperTopic = true;
    },
    resultFormTable(faindex, chilindex) {
      if (chilindex === null) {
      } else {
      }
    },
    //新增案例
    addAnli(options) {
      console.log(options);
    },
    // 删除选项
    closeThislist(options, index) {
      this.formTopic.forEach((items, indexs) => {
        if (items.questionId === options.questionId) {
          if (items.type === "1") {
            items.jsonStr.splice(index, 1);
          } else if (items.type === "2") {
            items.jsonStr.splice(index, 1);
          }
          // this.$set(this.formTopic[indexs],'jsonStr',options.jsonStr)
        }
      });
      console.log(this.formTopic);
    },
    // 新增选项
    addList(options) {
      var sut = {
        questionId: options.questionId,
        imgUrl: null,
        optionAnswer: 0,
        status: 1,
        content: "",
      };
      this.formTopic.forEach((item, index) => {
        if (item.questionId === options.questionId) {
          item.jsonStr.push(sut);
        }
      });
    },
    // 单选框选中
    actionListRadio(fatherNum, childNum) {
      this.formTopic.forEach((item, index) => {
        if (item.questionId === fatherNum) {
          item.jsonStr.forEach((items, indexs) => {
            if (indexs === childNum) {
              items.optionAnswer = 1;
            } else {
              items.optionAnswer = 0;
            }
          });
        }
      });
    },
    // 复选框改变
    actionListCheck(fatherNum, childNum, e) {
      this.formTopic.forEach((item, index) => {
        if (item.questionId === fatherNum) {
          item.jsonStr.forEach((items, indexs) => {
            if (indexs === childNum) {
              if (items.optionAnswer === 1) {
                items.optionAnswer = 0;
              } else {
                items.optionAnswer = 1;
              }
            }
          });
        }
      });
      console.log(this.formTopic);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.el-dropdown {
  color: #409eff;
}
/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__body {
    padding: 0;
    .contentBox {
      padding: 20px 20px 5px;
      .el-col {
        padding: 0px 20px;
        margin-bottom: 30px;
        header {
          margin-bottom: 6px;
          color: #2f4378;
          font-size: 14px;
        }
      }
      .juscon {
        float: none;
        width: 50%;
        margin: 0 auto;
      }
    }
  }
  .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;
  }
}
.imgBoxTopic {
  width: 150px;
  height: 150px;
  border: 1px solid #e2e2e2;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  .imgLabel {
    flex: 1;
    width: 100%;
    background-color: #f9f9f9;
    color: #999;
    font-size: 14px;
    cursor: pointer;
    border-radius: 8px;
    .msPhoto {
      display: flex;
      justify-content: center;
      align-items: center;
      max-width: 100%;
      max-height: 150px;
      img {
        max-width: 100%;
        max-height: 150px;
      }
    }
    .imgbbx {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 100%;
      height: 100%;
      i {
        font-weight: bold;
        margin: 8px 0;
        font-size: 20px;
      }
    }
  }
}
.listChildoptions {
  margin-bottom: 8px;
  display: flex;
  align-items: center;
}
</style>
