<template>
  <div class="detail_content">

    <div class="steps-content">
      <a-form-model
        :model="step1FormModel"
        :label-col="{span: 8}"
        :wrapper-col="{span: 14}"
        :rules="step1FormRules"
        ref="step1FormModelRef"
        style="padding-top: 10px;padding-bottom: 10px"
      >

        <a-form-model-item
          label="课程类型"
          prop="type"
        >
          <a-radio-group
            name="courseType"
            default-value="SINGLE"
            v-model="step1FormModel.type"
          >
            <a-radio value="SINGLE">
              单集
            </a-radio>
            <a-radio value="SERIES">
              系列
            </a-radio>

          </a-radio-group>
        </a-form-model-item>

        <a-form-model-item
          label="课程名称"
          prop="name"
        >
          <a-input v-model="step1FormModel.name" />
        </a-form-model-item>

        <a-form-model-item
          label="上传封面"
          prop="logoUrl"
        >
          <a-upload
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :customRequest="uploadLogo"
            :before-upload="beforeUpload"
            @change="handleChange"
          >
            <img
              v-if="step1FormModel.logoUrl"
              width="200"
              height="200"
              :src="step1FormModel.logoUrl"
              alt="logo"
            />
            <div v-else>
              <a-icon :type="loading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
        </a-form-model-item>

        <a-form-model-item label="上传视频">
          <div
            v-for="(video,index) in videoSeries"
            :label="video.chaperName"
            :key="video.videoId"
            class="video-series"
          >
            <a-row
              type="flex"
              justify="start"
              align="middle"
            >
              <a-col :span="6">
                <img
                  :src="video.coverURL"
                  width="100%"
                />
              </a-col>
              <a-col :span="12">
                <div class="video-desc">第{{index+1}}级</div>
                <div class="video-desc">{{video.chaperName}}</div>
              </a-col>
            </a-row>
          </div>
          <a-button @click="showVideoUploadModal">上传视频</a-button>
        </a-form-model-item>

        <a-form-model-item
          label="课程简介"
          prop="introduce"
        >
          <a-textarea
            row="2"
            v-model="step1FormModel.introduce"
          />
        </a-form-model-item>
        <a-form-model-item
          label="课程介绍"
          prop="detail"
        >
          <a-textarea
            row="4"
            v-model="step1FormModel.detail"
          />
        </a-form-model-item>

        <a-form-model-item
          label="系列名称"
          prop="seriesId"
          v-if="step1FormModel.type == 'SERIES'"
        >
          <a-select
            :value="currentSeries"
            label-in-value
            show-search
            placeholder="输入或查询系列"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            @search="handleSeriesSearch"
            @change="handleSeriesChange"
          >
            <a-select-option
              v-for="d in this.seriesData"
              :key="d.value"
            >
              {{ d.text }}
            </a-select-option>
          </a-select>

        </a-form-model-item>

        <a-form-model-item
          label="收费模式"
          prop="chargeModel"
        >
          <a-radio-group
            name="chargeModel"
            default-value="FREE"
            v-model="step1FormModel.chargeModel"
          >
            <a-radio value="FREE">
              免费
            </a-radio>
            <a-radio value="VIP_FREE">
              会员免费
            </a-radio>
            <a-radio value="PAY">
              付费点播
            </a-radio>

          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item
          v-if="step1FormModel.chargeModel == 'PAY'"
          label="非会员价格"
          prop="price"
        >
          <a-input
            prefix="¥"
            v-model="step1FormModel.price"
          />
        </a-form-model-item>
        <a-form-model-item
          v-if="step1FormModel.chargeModel == 'PAY'"
          label="有效时间"
          prop="validPeriod"
        >
          <a-input
            suffix="小时"
            v-model="step1FormModel.validPeriod"
          />
        </a-form-model-item>
        <a-form-model-item
          v-if="step1FormModel.chargeModel == 'PAY'"
          label="会员价格"
          prop="vipPrice"
        >
          <a-input
            prefix="¥"
            v-model="step1FormModel.vipPrice"
          />
        </a-form-model-item>
        <a-form-model-item label="所属讲师">
          <a-select
            placeholder="选择讲师"
            v-model="step1FormModel.teacherId"
            @change="handleTeacherChange"
          >

            <a-select-opt-group
              v-for="(org) in this.teachers"
              :key="org.id"
              :label="org.name"
            >
              <a-select-option
                v-for="(t) in org.teachers"
                :key="t.id"
                :value="t.id"
              >
                {{ t.name }}
              </a-select-option>
            </a-select-opt-group>

          </a-select>
        </a-form-model-item>
        <a-form-model-item label="课程标签">

          <a-select
            mode="multiple"
            placeholder="选择课程标签"
            v-model="step1FormModel.tags"
            @change="handleTagChange"
          >
            <a-select-option
              v-for="(t) in this.tags"
              :key="t.id"
              :value="t.id"
            >
              {{ t.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item
          label="可见范围"
          prop="allow"
        >
          <a-radio-group
            name="allow"
            default-value="ALL"
            v-model="step1FormModel.allow"
          >
            <a-radio value="ALL">
              全部
            </a-radio>
            <a-radio value="SPECIFY">
              指定企业
            </a-radio>
          </a-radio-group>
        </a-form-model-item>

        <a-form-model-item
          v-if="step1FormModel.allow === 'SPECIFY'"
          label="指定企业"
        >
          <a-select
            mode="multiple"
            placeholder="选择企业"            
             v-model="step1FormModel.allowOrgIds"
            @change="handleEnterpriseChange"
          >
            <a-select-option
              v-for="(t) in this.enterprise"
              :key="t.id"
              :value="t.id"
            >
              {{ t.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-item :wrapper-col="{ span: 24 }">
          <div class="btn-div">
            <a-button
              type="primary"
              @click="onSave"
            >
              保存
            </a-button>
            <a-button
              class="cancel-btn"
              @click="onCancel"
            >返回</a-button>
          </div>
        </a-form-item>
      </a-form-model>
    </div>

    <template>
      <a-modal
        :visible="videoUploadModalVisible"
        title="视频上传"
        @ok="videoUpload"
        @cancel="closeVideoUploadModal"
        :destroyOnClose="true"
      >
        <a-form>
          <a-form-item>
            <a-input
              v-model="video.title"
              placeholder="输入视频标题"
              allowClear
            ></a-input>
          </a-form-item>
          <a-form-item>
            <a-upload
              ref="videoUploaderRef"
              name="file"
              :multiple="false"
              :show-upload-list="true"
              :loading="loading"
              :customRequest="uploadVideo"
              :before-upload="beforeVideoUpload"
            >
              <a-button>
                <a-icon type="upload" />选择视频文件</a-button>
            </a-upload>
          </a-form-item>
        </a-form>
      </a-modal>
    </template>

  </div>
</template>
<script>
import { uploadFile } from "@/api/biz/resource";
import { disposereq } from "@/utils/util";
import { fetchList as teacherFetchList } from "@/api/biz/teacher";
import {
  saveStep1,
  saveStep2,
  getDetail,
  fetchAliyunAuth,
  fetchAliyunPolicy,
  refreshAliyunPolicy,
  fetchVideoInfo,
  saveCourse,
  fetchSeriesList,
  saveSeriesInfo,
} from "@/api/biz/course";

import { fetchList as fetchTagList } from "@/api/biz/courseTag";

import { fetchList as fetchEnterprise } from "@/api/biz/enterprise";

//系列待选列表表格列定义
let seriesColumns = [
  {
    title: "系列名称",
    dataIndex: "name",
    align: "center",
  },
];
//讲师待选列表表格列定义
let teacherColumns = [
  {
    title: "讲师名称",
    dataIndex: "name",
    align: "center",
  },
  {
    title: "培训机构",
    dataIndex: "orgName",
    align: "center",
  },
];
//章节表格列定义
let chaperColumns = [
  {
    title: "章节名称",
    dataIndex: "name",
    align: "center",
  },
  {
    title: "视频",
    dataIndex: "videoUrl",
    align: "center",
  },
  {
    title: "操作",
    key: "action",
    scopedSlots: { customRender: "videoTblAction" },
    align: "center",
  },
];
export default {
  // 创建完毕
  created() {
    // console.log(this.$route.query.id)
    //路由传过来的课程ID，新建是为空
    let courseId = this.$route.query.id;
    if (courseId) {
      this.getCourseDetail(courseId);
    }
    fetchAliyunAuth().then((res) => {
      if (res.resp_code == 200) {
        this.data = res.datas;
        this.aliyunRegion = this.data.region;
        this.aliyunUserId = this.data.userId;
      } else {
        this.$message.info(res.resp_msg);
      }
    });

    fetchEnterprise({
      pageIndex: 1,
      pageSize: 1000,
    }).then((res) => {
      this.enterprise = res.data;
    });

    fetchTagList({
      pageIndex: 1,
      pageSize: 1000,
    }).then((res) => {
      this.tags = res.data;
    });

    teacherFetchList({
      name: "",
      pageIndex: 1,
      pageSize: 1000,
    }).then((res) => {
      if (res.code == 200) {
        this.teacherData = res.data;
        const _teachers = [];
        res.data.forEach((d) => {
          const tg = _teachers.find((t) => t.id === d.orgId);
          if (!tg) {
            _teachers.push({ id: d.orgId, name: d.orgName, teachers: [d] });
          } else {
            tg.teachers.push(d);
          }
        });
        this.teachers = _teachers;
      }
    });
  },
  // 即将更新渲染
  beforeUpdate() {},
  data() {
    //第一步保存时系列字段验证
    let validateSerial = (rule, value, callback) => {
      if (
        this.step1FormModel.type == "SERIES" &&
        this.step1FormModel.seriesId == ""
      ) {
        callback(new Error("请选择系列"));
      } else {
        callback();
      }
    };
    //第一步保存时课程价格验证
    let validatePrice = (rule, value, callback) => {
      if (this.step1FormModel.chargeModel == "PAY") {
        if (value == "") {
          callback(new Error("不能为空"));
          return;
        }
        if (value == "0") {
          callback(new Error("不能为0"));
          return;
        }
        let exp = /^(([1-9]\d*)|\d)(\.\d{1,2})?$/;
        if (!exp.test(value)) {
          callback(new Error("金额格式不正确"));
          return;
        }
        callback();
      } else {
        callback();
      }
    };
    //第一步保存时有效时间验证
    let validateValidPeriod = (rule, value, callback) => {
      if (this.step1FormModel.chargeModel == "PAY") {
        if (value == "") {
          callback(new Error("不能为空"));
          return;
        }
        if (value == "0") {
          callback(new Error("不能为0"));
          return;
        }
        let exp = /^[0-9]*$/;
        if (!exp.test(value)) {
          callback(new Error("只能为空数字"));
          return;
        }
        callback();
      } else {
        callback();
      }
    };
    //第一步保存时会员价格验证
    let validateVipPrice = (rule, value, callback) => {
      if (this.step1FormModel.chargeModel == "PAY") {
        if (value == "") {
          callback(new Error("不能为空"));
          return;
        }
        if (value == "0") {
          callback(new Error("不能为0"));
          return;
        }
        let exp = /^(([1-9]\d*)|\d)(\.\d{1,2})?$/;
        if (!exp.test(value)) {
          callback(new Error("金额格式不正确"));
          return;
        }
        callback();
      } else {
        callback();
      }
    };
    return {
      enterpriese: [],
      currentSeries: {},
      tags: [],
      videoSeries: [],
      videoTitle: "",
      video: { id: "", img: "", file: "", fileName: "", title: "" },
      teachers: [],
      seriesData: [],
      onUploadProgress: undefined,
      authProgress: 0,
      uploadDisabled: true,
      resumeDisabled: true,
      pauseDisabled: true,
      uploader: null,
      statusText: "",
      aliyunRegion: "",
      aliyunUserId: "",
      //当前第几步
      currentStep: 0,
      //步骤列表
      steps: [
        {
          title: "第一步",
          content: "添加课程基本信息",
        },
        {
          title: "第二步",
          content: "添加课件和标签",
        },
        {
          title: "完成",
          content: "完成添加课程",
        },
      ],
      //第一步保存时验证规则定义
      step1FormRules: {
        name: [{ required: true, message: "不能为空", trigger: "blur" }],
        seriesId: [{ validator: validateSerial, trigger: "change" }],
        price: [{ validator: validatePrice, trigger: "change" }],
        validPeriod: [{ validator: validateValidPeriod, trigger: "change" }],
        vipPrice: [{ validator: validateVipPrice, trigger: "change" }],
      },
      //第一步表单数据对象
      step1FormModel: {
        id: "",
        name: "",
        type: "SINGLE",
        introduce: "",
        detail: "",
        logoUrl: "",
        teacherId: "",
        teacherName: "",
        chargeModel: "FREE",
        price: "",
        vipPrice: "",
        validPeriod: "",
        seriesId: "",
        seriesName: "",
        allow: "ALL",
        allowOrgIds: [],
        tagIds: [],
        tagNames: [],
      },
      //上传封面时的进度条
      loading: false,
      //选择系列弹出窗口的显示控制
      seriesModalVisible: false,
      //系列待选表格列定义
      seriesColumns: seriesColumns,
      //系列待选表格数据对象
      seriesData: [],
      //系列待选表格加载进度条
      seriesLoading: false,
      //系列待选表格分页控制对象
      seriesPagination: {},
      //系列待选表格选中项的ID
      seriesSelectedRowKeys: [],
      //选择讲师弹出窗口显示控制
      teacherModalVisible: false,
      //视频上传窗口
      videoUploadModalVisible: false,
      //讲师待选表格列定义
      teacherColumns: teacherColumns,
      //讲师待选表格数据对象
      teacherData: [],
      //讲师待选表格加载进度条
      teacherLoading: false,
      //讲师待选表格分页控制对象
      teacherPagination: {
        showSizeChanger: true,
      },
      //选择讲师的ID
      teacherSelectedRowKeys: [],
      //讲师待选表格查询参数对象
      teacherSearchPage: {
        name: "",
        pageIndex: 1,
        pageSize: 10,
      },
      //记录第一步操作表单修改次数，用于判断是否要提交后台保存，> 1时说明表单修改过需要保存
      step1ModifyCount: 0,
      //第二步添加章节点弹出窗口显示控制
      videoModalVisible: false,
      //第二步章节列表列定义
      chaperColumns: chaperColumns,
      //第二步章节表格数据对象
      chaperData: [],
      //第二步章节表格加载进度条
      chaperTblLoading: false,
    };
  },
  methods: {
    handleEnterpriseChange(value) {
      this.step1FormModel.allowOrgIds = value;
    },
    handleSeriesSearch(value) {
      this.fetchSeriesData(value, (data) => {
        const _items = [];
        data.forEach((d) => {
          _items.push({ value: d.id, text: d.name });
        });
        this.seriesData = _items;
      });
    },
    fetchSeriesData(value, callback) {
      fetchSeriesList({
        name: value,
        pageIndex: 1,
        pageSize: 500,
      }).then((res) => {
        if (res.count === 0) {
          callback([{ name: value, id: -1 }]);
        } else {
          console.log(res.data);
          const item = res.data.find((d) => d.name.trim() === value);
          if (!item) {
            //未找到完全匹配的
            res.data.unshift({ name: value, id: -1 });
          }
          callback(res.data);
        }
      });
    },
    handleSeriesChange(value) {
      if (value.key === -1) {
        //新建
        saveSeriesInfo({ name: value.label }).then((res) => {
          if (res.resp_code === 200) {
            this.currentSeries = { key: res.datas, label: value.label };
          }
        });
      } else {
        this.currentSeries = value;
      }
    },
    handleTagChange(values) {
      console.log(values);
    },
    handleTeacherChange(value) {
      this.teachers.forEach((org) => {
        const teacher = org.teachers.find((t) => t.id === value);
        if (teacher) {
          this.step1FormModel.teacherId = teacher.id;
          this.step1FormModel.teacherName = teacher.name;
        }
      });
    },
    onSave() {
      const {
        allow,
        allowOrgIds,
        chargeModel,
        detail,
        introduce,
        logoUrl,
        name,
        price,
        teacherId,
        teacherName,
        type,
        validPeriod,
        vipPrice,
        tagIds,
      } = this.step1FormModel;

      const chaperList = [];
      this.videoSeries.forEach((chapter, index) => {
        chaperList.push({
          chaperName: chapter.chaperName,
          videoId: chapter.videoId,
          sortNo: index,
        });
      });
      const course = {
        allow,
        allowOrgIds,
        chargeModel,
        detail,
        introduce,
        logoUrl,
        name,
        price,
        teacherId,
        teacherName,
        type,
        validPeriod,
        vipPrice,
        chaperList,
        tagIds,
      };
      if (this.currentSeries) {
        course.seriesId = this.currentSeries.key;
        course.seriesName = this.currentSeries.label
          ? this.currentSeries.label.trim()
          : this.currentSeries.label;
      }

      saveCourse(course).then((res) => {
        if (res.resp_code === 200) {
          this.$message.success("课程保存成功");
        } else {
          this.$message.info(res.resp_msg);
        }
      });
    },
    //获取课程详情
    getCourseDetail(id) {
      getDetail(id)
        .then((res) => {
          if (res.resp_code == 200) {
            this.step1FormModel = { ...res.datas };
            const _ctags = [];
            this.step1FormModel.tagList.forEach((t) => {
              _ctags.push(t.tagId);
            });
            this.step1FormModel.tags = _ctags;
            
            const _enterprise = [];
            this.step1FormModel.allowOrgList.forEach((t) => {
              _enterprise.push(t.orgId);
            });
            this.step1FormModel.allowOrgIds = _enterprise;

            this.currentSeries = {
              key: this.step1FormModel.seriesId,
              label: this.step1FormModel.seriesName,
            };
            const _videoSeries = [];
            res.datas.chaperList.forEach((cc) => {
              _videoSeries.push({
                chaperName: cc.name,
                videoId: cc.id,
                coverURL: cc.snapshotUrl,
              });
            });
            this.videoSeries = _videoSeries;
          } else {
            this.$message.info(res.resp_msg);
          }
        })
        .catch((err) => {
          disposereq(this, err);
        });
    },
    //跳转下一步
    nextStep() {
      if (this.currentStep == 0) {
        this.saveStep1();
      }
    },
    //保存第一步表单数据
    saveStep1() {
      // console.log(this.step1FormModel)
      if (this.step1ModifyCount <= 1) {
        //未修改，无需保存
        this.currentStep++;
        return;
      }
      this.$refs.step1FormModelRef.validate((valid) => {
        if (valid) {
          if (!this.step1FormModel.logoUrl) {
            this.$message.info("请上传封面");
            return false;
          }
          //请求后台保存
          let saveObj = { ...this.step1FormModel };
          saveStep1(saveObj)
            .then((res) => {
              if (res.resp_code == 200) {
                let courseId = res.datas;
                this.step1FormModel.id = courseId;
                this.currentStep++;
              } else {
                this.$message.info(res.resp_msg);
              }
            })
            .catch((err) => {
              disposereq(this, err);
            });
        }
      });
    },
    //上一步
    prevStep() {
      this.currentStep--;
    },
    //最后一步完成操作
    completeStep() {
      this.$message.info("完成");
    },
    //上传封面时上传中的回调
    handleChange(info) {
      // console.log(info.file.status)
      if (info.file.status === "uploading") {
        this.loading = true;
        return;
      }
    },
    //上传封面时上传前的验证
    beforeUpload(file) {
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.info("只能上传图片");
      }
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("Image must smaller than 10MB!");
      }
      return isJpgOrPng && isLt2M;
    },
    //返回课程列表
    onCancel() {
      this.$router.push("/edu/biz/course/index");
    },
    //上传封面
    uploadLogo(data) {
      const formData = new FormData();
      formData.append("file", data.file);
      uploadFile(formData)
        .then((res) => {
          if (res.data.resp_code == 200) {
            this.step1FormModel.logoUrl = res.data.datas.url;
          } else {
            this.$message.info("上传失败");
          }
          this.loading = false;
        })
        .catch((err) => {
          disposereq(this, err);
        });
    },
    beforeVideoUpload(file) {
      const { type } = file;
      if (!this.video.title) {
        this.$message.error("请填写视频标题");
        return false;
      }
      if (type.startsWith("video")) {
        return true;
      } else {
        this.$message.error("请选择视频文件");
        return false;
      }
    },

    uploadVideo({ file }) {
      var Title = this.video.title;
      this.video.fileName = file.name;
      this.video.file = file.file;
      var userData = '{"Vod":{}}';
      if (this.uploader) {
        this.uploader.stopUpload();
        this.authProgress = 0;
        this.statusText = "";
      }
      this.uploader = this.createUploader();
      this.uploader.addFile(file, null, null, null, userData);
      this.uploadDisabled = false;
      this.pauseDisabled = true;
      this.resumeDisabled = true;
      this.authUpload();
    },
    authUpload() {
      // 然后调用 startUpload 方法, 开始上传
      if (this.uploader !== null) {
        this.uploader.startUpload();
        this.uploadDisabled = true;
        this.pauseDisabled = false;
      }
    },
    createUploader(type) {
      let self = this;
      let uploader = new AliyunUpload.Vod({
        timeout: 60000,
        partSize: 1048576,
        parallel: 5,
        retryCount: 3,
        retryDuration: 2,
        region: self.aliyunRegion,
        userId: self.aliyunUserId,
        // 添加文件成功
        addFileSuccess: function(uploadInfo) {
          self.uploadDisabled = false;
          self.resumeDisabled = false;
        },
        // 开始上传
        onUploadstarted: function(uploadInfo) {
          if (!uploadInfo.videoId) {
            fetchAliyunPolicy({
              fileName: self.video.fileName,
              title: self.video.title,
            }).then((res) => {
              if (res.resp_code == 200) {
                const data = res.datas;
                let uploadAuth = data.uploadAuth;
                let uploadAddress = data.uploadAddress;
                let videoId = data.videoId;
                self.video.id = videoId;
                uploader.setUploadAuthAndAddress(
                  uploadInfo,
                  uploadAuth,
                  uploadAddress,
                  videoId
                );
              } else {
                self.$message.info(res.resp_msg);
                return;
              }
            });
            self.$message.info("文件开始上传");
          } else {
            refreshAliyunPolicy(uploadInfo.videoId).then((res) => {
              if (res.resp_code == 200) {
                const data = res.datas;
                let uploadAuth = data.uploadAuth;
                let uploadAddress = data.uploadAddress;
                let videoId = data.videoId;
                self.video.id = videoId;
                uploader.setUploadAuthAndAddress(
                  uploadInfo,
                  uploadAuth,
                  uploadAddress,
                  videoId
                );
              } else {
                self.$message.info(res.resp_msg);
                return;
              }
            });
          }
        },
        // 文件上传成功
        onUploadSucceed: function(uploadInfo) {
          self.$message.success("文件上传成功");
        },
        // 文件上传失败
        onUploadFailed: function(uploadInfo, code, message) {
          self.$message.error("文件上传失败");
        },
        // 取消文件上传
        onUploadCanceled: function(uploadInfo, code, message) {
          self.$message.error("文件已暂停上传");
        },
        // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
        onUploadProgress: function(uploadInfo, totalSize, progress) {
          let progressPercent = Math.ceil(progress * 100);
          self.authProgress = progressPercent;
          self.$refs.videoUploaderRef.onProgress(
            { percent: progressPercent },
            uploadInfo.file
          );
          if (progressPercent === 100) {
            self.$refs.videoUploaderRef.onSuccess(null, uploadInfo.file);
          }
        },
        // 上传凭证超时
        onUploadTokenExpired: function(uploadInfo) {
          refreshAliyunPolicy(uploadInfo.videoId).then((res) => {
            if (res.resp_code == 200) {
              const data = res.datas;
              let uploadAuth = data.uploadAuth;
              uploader.resumeUploadWithAuth(uploadAuth);
            } else {
              self.$message.info(res.resp_msg);
              return;
            }
          });
          self.$message.error("文件上传超时");
        },
        // 全部文件上传结束
        onUploadEnd: function(uploadInfo) {
          // self.$message.success("文件上传完毕");
        },
      });
      return uploader;
    },

    //选择系列弹出窗口确认操作
    seriesSelected() {
      this.seriesModalClose();
    },
    //选择系列弹出窗口取消操作
    seriesModalClose() {
      this.seriesModalVisible = false;
    },
    //显示选择系列弹出窗口
    openSeriesModal() {
      this.seriesModalVisible = true;
    },
    //系列待选表格分页操作
    seriesHandleTableChange() {},
    //系列待选表格选中操作
    seriesSelectChange(selectedRowKeys) {},
    //显示讲师待选窗口
    showTeacherModal() {
      this.teacherHandlSearch();
      this.teacherModalVisible = true;
    },
    showVideoUploadModal() {
      this.videoUploadModalVisible = true;
    },
    closeVideoUploadModal() {
      this.videoUploadModalVisible = false;
      this.video = {};
    },
    videoUpload() {
      if (this.video) {
        const { title, id } = this.video;
        fetchVideoInfo(id).then((res) => {
          if (res.resp_code == 200) {
            const { coverURL, duration } = res.datas;
            this.videoSeries.push({
              chaperName: title,
              videoId: id,
              coverURL,
              duration,
            });
            this.video = {};
            this.videoUploadModalVisible = false;
          }
        });
      }
    },

    //讲师待选窗口确认操作
    teacherSelected() {
      if (this.teacherSelectedRowKeys.length == 0) {
        this.$message.info("请选择讲师");
        return false;
      }
      this.step1FormModel.teacherId = this.teacherSelectedRowKeys[0];
      let teacherObj = this.teacherData.filter(
        (e) => e.id == this.teacherSelectedRowKeys[0]
      )[0];
      // console.log(teacherObj)
      this.step1FormModel.teacherName = teacherObj.name;
      // console.log(this.step1FormModel)
      this.teacherModalClose();
    },
    //关闭讲师待选窗口
    teacherModalClose() {
      this.teacherModalVisible = false;
      this.seriesSelectedRowKeys = [];
      this.teacherData = [];
      this.teacherPagination = {};
      this.teacherSelectedRowKeys = [];
      this.teacherSearchPage = {
        name: "",
        pageIndex: 1,
        pageSize: 10,
      };
    },
    //待选讲师表格分页操作
    teacherHandleTableChange(pagination, filters, sorter) {
      let queryParam = { ...this.teacherSearchPage };
      queryParam.pageIndex = pagination.current;
      queryParam.pageSize = pagination.pageSize;
      this.getTeacherList(queryParam);
    },
    //选中讲师操作
    teacherSelectChange(selectedRowKeys) {
      // console.log(selectedRowKeys)
      this.teacherSelectedRowKeys = selectedRowKeys;
    },
    //待选讲师表格查询
    teacherHandlSearch() {
      this.getTeacherList(this.teacherSearchPage);
    },
    //查询讲师
    getTeacherList(query) {
      this.teacherLoading = true;
      teacherFetchList(query)
        .then((res) => {
          if (res.code == 200) {
            this.teacherData = res.data;
            var paper = { ...this.teacherPagination };
            paper.current = query.pageIndex;
            paper.total = res.count;
            this.teacherPagination = paper;
          } else {
            this.$message.info(res.resp_msg);
          }
          this.teacherLoading = false;
        })
        .catch((err) => {
          this.teacherLoading = false;
          disposereq(this, err);
        });
    },
    //显示添加章节窗口
    showVideoModal() {
      this.videoModalVisible = true;
    },
  },
  watch: {
    //监视第一步表单是否有修改操作
    step1FormModel: {
      handler(val, oldVal) {
        this.step1ModifyCount++;
      },
      deep: true,
    },
  },
};
</script>
<style>
.detail_content {
  background-color: #f0f2f5;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.search_box {
  width: 100%;
  box-sizing: border-box;
  padding: 14px;
  background-color: #fff;
}
.steps-content {
  width: 100%;
  background-color: #fff;
}
.uploadImg {
  cursor: pointer;
}
.table_top {
  padding-bottom: 14px;
}
.video-desc {
  margin-left: 10px;
  height: 100%;
  font-weight: bold;
  font-size: 14px;
  word-break: break-all;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}
.video-series {
  margin-top: 5px;
}
.btn-div {
  text-align: center;
}
.cancel-btn {
  margin-left: 15px;
}
</style>