<template>
  <div id="courseManagement">
    <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="del(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"
      :before-close="closeBefore"
      :fullscreen="fullscreen"
    >
      <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.courseName"
              />
            </el-col>
            <el-col :span="24">
              <header>主讲名师</header>
              <el-select
                :disabled="statusPop === 2"
                style="width: 100%"
                multiple
                v-model="poppleData.teacherIds"
                placeholder="请选择主讲名师："
                @change="changeTeacherlist"
              >
                <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>
            <el-button type="primary" @click="changeList({ level: 0 }, 0)"
              >添加章节</el-button
            >
            <el-button>导入章节</el-button>
          </div>
          <div>
            <el-table
              ref="pager"
              :data="tableDatas"
              row-key="id"
              :load="load"
              lazy
              :show-overflow-tooltip="true"
              @expand-change="expandChange"
              :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
            >
              <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 === 'time'">{{
                    scope.row["level"] === 0
                      ? ""
                      : numTime(scope.row[item.prop])
                  }}</span>
                  <span v-else-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="innerVisibleVideoFun(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="innerVisibleVideo"
              append-to-body
              :show-close="false"
              :destroy-on-close="true"
            >
              <div slot="title" class="hearders">
                <div class="leftTitle">视频播放器</div>
                <div class="rightBoxs">
                  <img
                    src="@/assets/images/Close@2x.png"
                    alt=""
                    @click="closeVideoPop"
                  />
                </div>
              </div>
              <player-video :videoDatas="videoDatas"></player-video>
              <span slot="footer" class="dialog-footer">
                <el-button @click="closeVideoPop">取 消</el-button>
              </span>
            </el-dialog>
            <el-dialog
              width="520px"
              :visible.sync="innerVisible"
              append-to-body
              :show-close="false"
              :fullscreen="fullscreenChild"
            >
              <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"
          />
        </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="statusPop === 1" @click="submitAddTable" type="primary"
          >提交</el-button
        >
        <el-button
          v-else
          type="primary"
          @click="activeTableStatus === 1 ? nextTable() : submitTabel()"
          >{{ activeTableStatus === 1 ? "下一步" : "确定" }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import playerVideo from "@/components/player";
import searchBox from "@/components/searchBox";
import tableList from "@/components/tableList";
import pagination from "@/components/pagination";
import Editor from "@/components/Editor";
export default {
  components: { playerVideo, searchBox, tableList, pagination, Editor },
  data() {
    return {
      uploadStatus: 2, //富文本组件传值
      loading: false, //当前表单加载是否加载动画
      navText: {
        title: "课程合计",
        index: 0,
        ch: "个",
        num: true,
        choice: true,
        backFatherBtn: {
          status: false,
          title: "未定义",
        },
      },
      formTableChild: {},
      formTables: [
        {
          label: "名称",
          prop: "name",
          placeholder: "输入名称",
        },
        // {
        //   label: "视频地址",
        //   prop: "videoUrl",
        //   placeholder: "输入视频地址",
        //   scope: "dis",
        // },
        // {
        //   label: "时长",
        //   prop: "videoTime",
        //   placeholder: "输入时长",
        //   scope: "dis",
        // },
        {
          label: "视频ID",
          prop: "vid",
          placeholder: "输入视频ID",
          scope: "dis",
        },
        {
          label: "排序",
          prop: "sort",
          placeholder: "输入排序",
        },
        {
          label: "是否启用",
          prop: "status",
          scope: "radio",
        },
      ],
      tableSet: [
        {
          label: "课程名称",
          prop: "courseName",
          hidden: true,
          width: "180px",
        },
        {
          label: "课程类型",
          prop: "categoryName",
          hidden: true,
          width: "180px",
        },
        {
          label: "章节数",
          prop1: "chapterNum",
          prop2: "sectionNum",
          hidden: true,
          scope: "numberAll",
        },
        {
          label: "视频时长(小时)",
          prop: "duration",
          hidden: true,
          scope: "time",
          width: "200px",
        },
        {
          label: "排序",
          prop: "sort",
          hidden: true,
        },
        {
          label: "启用状态",
          prop: "status",
          hidden: true,
          scope: "status",
        },
      ], //表头信息
      tableData: [], //表单数据
      total: 0, //一共多少条
      pageSize: 10, //每页多少条数据
      currentPage: 1, //当前页码
      totalChild: 0, //一共多少条
      pageSizeChild: 5, //每页多少条数据
      currentPageChild: 1, //当前页码
      formList: [
        {
          label: "课程名称",
          prop: "courseName",
          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",
          },
        },
      ], //搜索栏
      optionsTion: [],
      optionsTeach: [],
      poppleData: {},
      fullscreen: false,
      fullscreenChild: false,
      dialogBox: false,
      innerVisible: false,
      innerVisibleVideo: false, //视频播放器窗口
      videoDatas: {}, //视频数据
      statusPop: 0,
      beif: "", //备份数据
      activeTableStatus: 1, //步骤条当前状态
      tableDatas: [], //表格数据
      poppleTableHeader: [
        {
          label: "名称",
          prop: "name",
          width: "150px",
        },
        {
          label: "级别",
          prop: "level",
          width: "80px",
          scope: "level",
        },
        {
          label: "视频地址",
          prop: "mp4",
          width: "300px",
        },
        {
          label: "时长(小时)",
          prop: "duration",
          // scope: "time",
          width: "120px",
        },
        {
          label: "排序",
          prop: "sort",
        },
      ], //表头数据
      int: -1,
      treeObj: {},
      priceTest: /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/,
    };
  },
  computed: {
    numTime: function () {
      return function (res) {
        return Number(res / 3600).toFixed(2);
      };
    },
  },
  mounted() {
    this.search();
    this.initCascader();
    this.initTeacherList();
  },
  methods: {
    //视频播放器窗口
    innerVisibleVideoFun(options) {
      this.videoDatas = options;
      this.innerVisibleVideo = true;
    },
    //视频窗口关闭
    closeVideoPop() {
      this.innerVisibleVideo = false;
    },
    changeTeacherlist(options) {
      console.log(this.poppleData);
    },
    // 初始化教师列表
    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);
      };
    },
    // 详情
    infoMessage(options) {
      var data = options.courseId;
      this.$api.obtainCourse(data).then((res) => {
        this.poppleData = res.data;
        this.beif = res.data.coverUrl;
        this.poppleData.teacherIds = res.data.teacherIds.split(",").map(Number);
        this.getTables(data);
      });
      this.statusPop = 2;
      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.courseName) {
        this.$message.error("请输入课程名称");
        return;
      }
      if (
        this.poppleData.teacherIds === undefined ||
        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,
        courseName: this.poppleData.courseName,
        duration: 0,
        introduction: this.poppleData.introduction,
        price: this.poppleData.price,
        sort:this.poppleData.sort,
        status: this.poppleData.status,
        teacherIds: this.poppleData.teacherIds.join(","),
      };
      if (this.statusPop === 1) {
        this.search();
        this.dialogBox = false;
      } else if (this.statusPop === 0) {
        data.courseId = this.poppleData.courseId;
        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) {
        this.dialogBox = false;
      }
    },
    submitFun(data) {
      this.$api
        .editCourse(data)
        .then((res) => {
          console.log(data)
          this.$message.success("修改成功!");
          this.dialogBox = false;
          this.search();
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    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("图片上传错误");
          });
      });
    },
    //添加
    addClick() {
      this.poppleData = {};
      this.tableDatas = [];
      this.statusPop = 1;
      this.activeTableStatus = 1;
      this.dialogBox = true;
    },
    // 添加表单执行提交
    async submitAddTable() {
      var self = this;
      if (this.poppleData.categoryId === undefined) {
        this.$message.error("请选择课程分类");
        return;
      }
      if (this.poppleData.courseName === undefined) {
        this.$message.error("请输入课程名称");
        return;
      }
      if (this.poppleData.teacherIds === undefined) {
        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 === undefined) {
        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,
        courseName: this.poppleData.courseName,
        duration: 0,
        sort: this.poppleData.sort,
        introduction: this.poppleData.introduction,
        price: this.poppleData.price,
        status: this.poppleData.status,
        teacherIds: this.poppleData.teacherIds.join(","),
      };
      const awtimg = await this.imgUpload(2);
      data.coverUrl = this.poppleData.coverUrl;
      this.$api
        .addCourse(data)
        .then((res) => {
          this.poppleData.courseId = res.log.primary_key_id;
          this.$message.success("新增成功!");
          this.search();
          this.getTables(res.log.primary_key_id);
          this.nextTable();
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    // 修改
    modify(options) {
      var data = options.courseId;
      this.$api.obtainCourse(data).then((res) => {
        this.poppleData = res.data;
        this.beif = res.data.coverUrl;
        this.poppleData.teacherIds = res.data.teacherIds.split(",").map(Number);
        this.getTables(data);
      });
      this.statusPop = 0;
      this.activeTableStatus = 1;
      this.dialogBox = true;
    },
    //获取大章
    getTables(index) {
      var self = this
      var data = {
        courseId: this.poppleData.courseId,
        status: "0,1",
        pageSize: this.pageSizeChild,
        pageNum: this.currentPageChild,
      };
      var nullBox = [];
      this.$api.inquireCourseListchapter(data).then((res) => {
        res.rows.forEach((item) => {
          item.id = item.chapterId + "";
          item.level = 0;
          item.hasChildren = true;
          nullBox.push(item);
        });
        nullBox.sort(this.sortBy("sort", true));
        self.tableDatas = nullBox;
        self.totalChild = res.total
      });
    },
    //删除
    del(options) {
      var self = this;
      this.$confirm("此操作将删除该课程, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var data = {
            categoryId: options.categoryId,
            courseId: options.courseId,
            courseName: options.courseName,
            teacherIds: options.teacherIds.join(","),
            status: -1,
          };
          this.$api
            .editCourse(data)
            .then((res) => {
              this.$message.success("删除成功!");
              this.search();
            })
            .catch((err) => {
              this.$message.error("删除失败：" + err);
            });
        })
        .catch(() => {});
    },
    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) {
      if (v === undefined) {
        v = {
          status: "0,1",
          pageSize: this.pageSize,
          pageNum: this.currentPage,
        };
      }
      var data = {
        courseName: v.courseName || "",
        categoryId: v.categoryId || "",
        status: v.status === undefined ? "0,1" : v.status,
        pageSize: this.pageSize,
        pageNum: this.currentPage,
      };
      this.loading = true;
      this.$api
        .inquireCourseList(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.$confirm("此操作将关闭窗口, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.dialogBox = false;
          this.fullscreen = false;
          this.poppleData = {};
        })
        .catch(() => {});
    },
    closeBeforeChild() {
      this.$confirm("此操作将关闭窗口, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.innerVisible = false;
          this.fullscreenChild = false;
          // this.poppleData = {};
        })
        .catch(() => {});
    },
    handleSizeChange(v) {
      this.pageSize = v;
      this.currentPage = 1;
      this.search();
    },
    handleCurrentChange(v) {
      this.currentPage = v;
      this.search();
    },
    handleSizeChangeChild(v) {
      this.pageSizeChild = v;
      this.currentPageChild = 1;
      this.getTables();
    },
    handleCurrentChangeChild(v) {
      this.currentPageChild = v;
      this.getTables();
    },
    //点击多级触发异步
    async load(tree, treeNode, resolve) {
      this.treeObj[tree.chapterId] = { tree, treeNode, resolve };
      var data = {
        status: "0,1",
        chapterId: tree.chapterId,
      };
      const loadChildren = await this.$api.inquireCourseListsection(data);
      if (Array.isArray(loadChildren.rows) && loadChildren.rows.length > 0) {
        loadChildren.rows.forEach((item) => {
          item.id = tree.chapterId + "." + item.sectionId;
          item.level = 1;
        });
        loadChildren.rows.sort(this.sortBy("sort", true));
        resolve(loadChildren.rows); // 返回最终数据对象
      } else {
        tree.children = [];
        resolve([]);
      }
    },
    changeTableList() {
      var data = {
        chapterId: this.formTableChild.chapterId,
        sectionId: this.formTableChild.sectionId,
        // videoTime: this.formTableChild.videoTime,
        // videoUrl: this.formTableChild.videoUrl,
        vid: this.formTableChild.vid,
        name: this.formTableChild.name,
        sort: this.formTableChild.sort,
        status: this.formTableChild.status,
      };
      this.$api.editCoursesection(data).then((res) => {
        this.$message.success("修改成功");
        this.getTables(this.poppleData.courseId);

        // 处理懒加载节点，先清空再渲染。
        // 利用refs得到表格的数据结构，拿到 lazyTreeNodeMap 这个懒加载对象。
        // 这里面存储的就是你之前加载的所有节点数据对象了。然后清空操作节点的父节点对象。
        this.$refs.pager.store.states.lazyTreeNodeMap[
          this.formTableChild.chapterId
        ] = [];
        // 根据我们声明的maps对象，拿到父节点。然后手动进行接口请求，重新进行数据渲染。
        const { tree, treeNode, resolve } =
          this.treeObj[this.formTableChild.chapterId];
        this.load(tree, treeNode, resolve);
        this.innerVisible = false;
      });
    },
    //添加or修改章节or子节
    changeList(row, int) {
      this.int = int;
      var kelone = JSON.stringify(row);
      this.formTableChild = JSON.parse(kelone);
      if (int === 0 && row.courseId !== undefined) {
        this.formTableChild = {
          level: 1,
          courseId: row.courseId,
          chapterId: row.chapterId,
        };
      }
      this.innerVisible = true;
    },
    expandChange() {},
    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;
      }
      // 添加
      if (this.int === 0) {
        console.log(this.formTableChild);
        if (this.formTableChild.chapterId) {
          //添加下级
          // if (this.formTableChild.videoUrl === undefined) {
          //   this.$message.error("请输入视频地址");
          //   return;
          // }
          if (this.formTableChild.vid === undefined) {
            this.$message.error("请输入视频ID");
            return;
          }
          var data = {
            chapterId: this.formTableChild.chapterId,
            name: this.formTableChild.name,
            sort: this.formTableChild.sort,
            status: this.formTableChild.status,
            vid: this.formTableChild.vid,
            // videoTime: this.formTableChild.videoTime,
            // videoUrl: this.formTableChild.videoUrl,
          };
          this.$api.addCoursesection(data).then((res) => {
            this.$message.success("添加下级成功");
            this.getTables(this.poppleData.courseId);
            if (
              this.$refs.pager.store.states.lazyTreeNodeMap[
                this.formTableChild.bankChapterId
              ] === undefined
            ) {
            } else {
              this.$refs.pager.store.states.lazyTreeNodeMap[
                this.formTableChild.chapterId
              ] = [];
              // 根据我们声明的maps对象，拿到父节点。然后手动进行接口请求，重新进行数据渲染。
              const { tree, treeNode, resolve } =
                this.treeObj[this.formTableChild.chapterId];
              this.load(tree, treeNode, resolve);
            }
            this.innerVisible = false;
          });
        } else {
          // 添加章节
          var data = {
            courseId: this.poppleData.courseId,
            name: this.formTableChild.name,
            sort: this.formTableChild.sort,
            status: this.formTableChild.status,
          };
          this.$api.addCoursechapter(data).then((res) => {
            this.$message.success("添加成功");
            this.getTables(this.poppleData.courseId);
            this.innerVisible = false;
          });
        }
      }
      //修改
      if (this.int === 1) {
        if (this.formTableChild.sectionId === undefined) {
          var data = {
            chapterId: this.formTableChild.chapterId,
            name: this.formTableChild.name,
            sort: this.formTableChild.sort,
            status: this.formTableChild.status,
          };
          this.$api.editCoursechapter(data).then((res) => {
            this.$message.success("修改成功");
            this.getTables(this.poppleData.courseId);
            this.innerVisible = false;
          });
        } else {
          this.changeTableList();
        }
      }
    },
    delF(row) {
      this.$confirm("是否确认删除该章？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var data = {
            chapterId: row.chapterId,
            name: row.name,
            sort: row.sort,
            status: -1,
          };
          this.$api.editCoursechapter(data).then((res) => {
            this.$message.success("删除成功");
            this.getTables(this.poppleData.courseId);
            this.innerVisible = false;
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    delFChild(rowsz) {
      this.$confirm("是否确认删除该节？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var data = {
            chapterId: rowsz.chapterId,
            sectionId: rowsz.sectionId,
            // videoTime: rowsz.videoTime,
            // videoUrl: rowsz.videoUrl,
            vid: rowsz.vid,
            name: rowsz.name,
            sort: rowsz.sort,
            status: -1,
          };
          this.$api.editCoursesection(data).then((res) => {
            this.$message.success("删除成功");
            this.getTables(this.poppleData.courseId);

            // 处理懒加载节点，先清空再渲染。
            // 利用refs得到表格的数据结构，拿到 lazyTreeNodeMap 这个懒加载对象。
            // 这里面存储的就是你之前加载的所有节点数据对象了。然后清空操作节点的父节点对象。
            this.$refs.pager.store.states.lazyTreeNodeMap[rowsz.chapterId] = [];
            // 根据我们声明的maps对象，拿到父节点。然后手动进行接口请求，重新进行数据渲染。
            const { tree, treeNode, resolve } = this.treeObj[rowsz.chapterId];
            this.load(tree, treeNode, resolve);
            this.innerVisible = false;
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</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__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;
  }
}
</style>
