<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" :disabled="isReadOnly">
                    <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="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" :disabled="isReadOnly">
                    <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="name">
                <a-input v-model="step1FormModel.name" :disabled="isReadOnly" />
            </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" :disabled="isReadOnly">
                    <img v-if="step1FormModel.logoUrl" width="200" height="200" style="width:auto!important" :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" class="video-image">
                            <div class="video-image-background">
                                <img :src="video.coverUrl" width="100%" height="100%" />
                                <div class="video-image-toolbar">
                                    <a-icon type="delete" @click="deleteVideo(video)" />
                                    <a-icon type="edit" @click="editVideo(video)" />
                                </div>
                                <div class="video-image-cover"></div>
                                <div class="video-image-play">
                                    <a-icon type="play-circle" />
                                </div>
                                <div class="video-image-time">{{formatDuraton(video.duration)}}</div>
                            </div>
                        </a-col>
                        <a-col :span="12">
                            <div class="video-desc">第{{index+1}}集</div>
                            <div class="video-desc">{{video.name}}</div>
                        </a-col>
                    </a-row>
                </div>
                <a-button @click="showVideoUploadModal" :disabled="isReadOnly">上传视频</a-button>
            </a-form-model-item>

            <a-form-model-item label="课程简介" prop="introduce">
                <a-textarea row="2" v-model="step1FormModel.introduce" :disabled="isReadOnly" />
            </a-form-model-item>
            <a-form-model-item label="课程介绍" prop="detail">
                <!-- <a-textarea
            row="4"
            v-model="step1FormModel.detail"
          /> -->
                <a-upload name="detailUpload" accept="image/*" list-type="picture-card" :file-list="detailPicList" :multiple="true" :customRequest="uploadDetailPic" :before-upload="beforUploadDetailPic" @change="uploadDetailPicChange" :remove="uploadDetailRemove" :disabled="isReadOnly">
                    <div v-if="detailPicList.length < 8">
                        <a-icon type="plus" />
                        <div>
                            上传图片
                        </div>
                    </div>
                </a-upload>
            </a-form-model-item>

            <a-form-model-item label="上传附件">
                <div v-for="(attachment) in attachments" :label="attachment.title" :key="attachment.id" class="video-series">
                    <a-row type="flex" justify="start" align="middle">
                        <a-col :span="12">
                            <div class="video-desc">
                                <a-icon type="paper-clip" class="attachment-icon" />{{attachment.title}}</div>
                        </a-col>
                    </a-row>
                </div>
                <a-button @click="showAttachmentUploadModal" :disabled="isReadOnly">上传附件</a-button>
            </a-form-model-item>

            <a-form-model-item label="收费模式" prop="chargeModel">
                <a-radio-group name="chargeModel" default-value="FREE" v-model="step1FormModel.chargeModel" :disabled="isReadOnly">
                    <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" :disabled="isReadOnly">

                    <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" label-in-value placeholder="选择课程标签" v-model="selectedTags" @change="handleTagChange" :disabled="isReadOnly">
                    <a-select-option v-for="(t) in this.tags" :key="t.tagId" :value="t.tagId">
                        {{ t.tagName }}
                    </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" :disabled="isReadOnly">
                    <a-radio value="ALL">
                        全部
                    </a-radio>
                    <a-radio value="SPECIFY">
                        指定企业
                    </a-radio>
                    <a-radio value="USER_TAG">
                        标签可见
                    </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-model-item v-if="step1FormModel.allow === 'USER_TAG'" label="选择标签">
                <a-select mode="multiple" placeholder="选择标签" v-model="selectedUserTagIds" @change="handleUserTagChange">
                    <a-select-option v-for="(t) in this.userTagList" :key="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" :disabled="isReadOnly">
                        保存
                    </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" centered>
            <a-form>
                <a-form-item>
                    <a-input v-model="video.title" placeholder="视频标题" allowClear></a-input>
                </a-form-item>
                <div class="video_type">
                    <a-radio-group :options="[
                        { label: '上传添加', value: 'ALI' },
                        { label: 'URL添加', value: 'URL' },
                        ]" default-value="ALI" @change="onVideoTypeChanged" />
                </div>
                <a-form-item v-if="video.videoType==='ALI'">
                    <a-upload ref="videoUploaderRef" name="file" :multiple="false" :show-upload-list="true" :customRequest="uploadVideo" :before-upload="beforeVideoUpload">
                        <a-button>
                            <a-icon type="upload" />选择视频文件</a-button>
                    </a-upload>
                </a-form-item>
                 <a-form-item v-if="video.videoType==='URL'">
                    <a-input v-model="video.videoUrl" placeholder="视频URL" allowClear></a-input>
                </a-form-item>
            </a-form>
        </a-modal>
    </template>

    <template>
        <a-modal :visible="attachmentUploadModalVisible" title="附件上传" @ok="saveAttachments" @cancel="closeAttachmentUploadModal" :destroyOnClose="true" centered>
            <a-form>
                <a-form-item>
                    <a-input v-model="attachment.title" placeholder="附件标题" allowClear></a-input>
                </a-form-item>
                <a-form-item>
                    <a-upload ref="attachmentUploaderRef" name="file" :multiple="false" :show-upload-list="true" :customRequest="uploadAttachment" :before-upload="beforeAttachmentUpload">
                        <a-button>
                            <a-icon type="upload" />选择附件文件</a-button>
                    </a-upload>
                </a-form-item>
            </a-form>
        </a-modal>
    </template>

    <template>
        <a-modal :visible="showVideoEditor" title="修改视频名称" @ok="updateVideoTitle" @cancel="closeVideoEditor" :destroyOnClose="true">
            <a-form>
                <a-form-item>
                    <a-input v-model="video2update.name" placeholder="输入视频标题" allowClear></a-input>
                </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 {
  getDetail,
  fetchAliyunAuth,
  fetchAliyunPolicy,
  refreshAliyunPolicy,
  fetchVideoInfo,
  saveCourse,
  fetchSeriesList,
  saveSeriesInfo,
  deleteChaper,
  updateChaperTitle,
} from "@/api/biz/course";

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

import { fetchList as fetchUserTagList } from "@/api/admin/user_tag";

export default {
  // 创建完毕
  created() {
    //路由传过来的课程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;
    });
    fetchUserTagList({
      pageIndex: 1,
      pageSize: 10000,
    }).then((res) => {
      this.userTagList = res.data;
    });

    fetchTagList({
      pageIndex: 1,
      pageSize: 1000,
    }).then((res) => {
      const _tags = [];
      res.data.forEach((d) => {
        _tags.push({
          tagId: d.id,
          tagName: d.name,
        });
      });
      this.tags = _tags;
    });

    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 {
      isReadOnly: this.$route.query.isReadOnly == "true",
      attachment: {
        title: "",
      },
      attachments: [],
      video2update: {},
      enterprise: [],
      currentSeries: {},
      tags: [],
      selectedTags: [],
      videoSeries: [],
      video: {
        id: "",
        img: "",
        file: "",
        fileName: "",
        title: "",
        videoType: "ALI",
      },
      showVideoEditor: false,
      teachers: [],
      seriesData: [],
      onUploadProgress: undefined,
      authProgress: 0,
      uploadDisabled: true,
      resumeDisabled: true,
      pauseDisabled: true,
      uploader: null,
      statusText: "",
      aliyunRegion: "",
      aliyunUserId: "",
      //第一步保存时验证规则定义
      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: [],
        userTagIds: "",
        videoType: "upload",
      },
      //上传封面时的进度条
      loading: false,
      //选择系列弹出窗口的显示控制
      seriesModalVisible: false,
      //视频上传窗口
      videoUploadModalVisible: false,
      //附件上传窗口
      attachmentUploadModalVisible: false,
      teacherSearchPage: {
        name: "",
        pageIndex: 1,
        pageSize: 10,
      },
      detailPicList: [],
      userTagList: [],
      selectedUserTagIds: [],
    };
  },
  methods: {
    onVideoTypeChanged(e) {
      this.video.videoType = e.target.value;
    },
    editVideo(video) {
      this.video2update = video;
      this.showVideoEditor = true;
    },
    updateVideoTitle() {
      const data = {
        chaperId: this.video2update.id,
        chaperName: this.video2update.name,
      };
      updateChaperTitle(data).then((resp) => {
        if (resp.resp_code === 200) {
          this.$message.success("视频名称修改成功");
        } else {
          this.$message.error(`视频名称修改失败:${resp.resp_msg}`);
        }
      });

      this.showVideoEditor = false;
    },
    closeVideoEditor() {
      this.showVideoEditor = false;
    },
    deleteVideo(video) {
      let self = this;
      this.$confirm({
        title: `确认要删除${video.name ? video.name : ""}吗?`,
        content: "删除操作同时会删除已经上传的视频文件",
        onOk() {
          if (video.id != undefined) {
            deleteChaper(video.id).then((resp) => {
              if (resp.resp_code === 200) {
                self.videoSeries.forEach((item, index) => {
                  console.log(item, video);
                  if (item.id === video.id) {
                    self.videoSeries.splice(index, 1);
                  }
                });
              }
            });
          } else if (video.videoId != undefined) {
            self.videoSeries.forEach((item, index) => {
              console.log(item, video);
              if (item.videoId === video.videoId) {
                self.videoSeries.splice(index, 1);
              }
            });
          }
        },
        onCancel() {},
      });
    },
    formatDuraton(t) {
      let time = Math.round(t);
      if (time > -1) {
        var hour = Math.floor(time / 3600);
        var min = Math.floor(time / 60) % 60;
        var sec = time % 60;
        if (hour > 0) {
          if (hour < 10) {
            time = "0" + hour + ":";
          } else {
            time = hour + ":";
          }
        } else {
          time = "";
        }
        if (min > 0) {
          if (min < 10) {
            time += "0";
          }
          time += min + ":";
        } else {
          time = "";
        }
        if (sec < 10) {
          time += "0";
        }
        time += sec;
      }
      return time;
    },
    handleEnterpriseChange(value) {
      this.step1FormModel.allowOrgIds = value;
    },
    handleUserTagChange(value) {
      this.selectedUserTagIds = value;
      this.step1FormModel.userTagIds = value.join(",");
      // console.log(this.step1FormModel.userTagIds);
    },
    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 {
          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(value)
      this.selectedTags = 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,
        userTagIds,
      } = this.step1FormModel;
      //验证
      if (!name) {
        this.$message.info("请输入课程名称");
        return;
      }
      if (!logoUrl) {
        this.$message.info("请上传封面");
        return;
      }
      if (this.videoSeries.length == 0) {
        this.$message.info("请上传视频");
        return;
      }
      if (chargeModel == "PAY") {
        if (price == "") {
          this.$message.info("非会员价格不能为空");
          return;
        }
        if (price == "0") {
          this.$message.info("非会员价格不能为0");
          return;
        }
        let exp = /^(([1-9]\d*)|\d)(\.\d{1,2})?$/;
        if (!exp.test(price)) {
          this.$message.info("非会员价格金额格式不正确");
          return;
        }
        if (validPeriod == "") {
          this.$message.info("有效时间不能为空");
          return;
        }
        if (validPeriod == "0") {
          this.$message.info("有效时间不能为0");
          return;
        }
        let exp1 = /^[0-9]*$/;
        if (!exp1.test(validPeriod)) {
          this.$message.info("有效时间只能为空数字");
          return;
        }

        if (vipPrice == "") {
          this.$message.info("会员价格不能为空");
          return;
        }
        if (vipPrice == "0") {
          this.$message.info("会员价格不能为0");
          return;
        }
        if (!exp.test(vipPrice)) {
          this.$message.info("会员价格金额格式不正确");
          return;
        }
      }
      // validateValidPeriod
      // validateVipPrice
      const chaperList = [];
      this.videoSeries.forEach((chapter, index) => {
        chaperList.push(chapter);
      });

      const course = {
        allow,
        allowOrgIds,
        chargeModel,
        detail,
        introduce,
        logoUrl,
        name,
        price,
        teacherId,
        teacherName,
        type,
        validPeriod,
        vipPrice,
        chaperList,
        tagIds,
        attachmenIds: [],
        userTagIds,
      };
      if (this.currentSeries) {
        course.seriesId = this.currentSeries.key;
        course.seriesName = this.currentSeries.label
          ? this.currentSeries.label.trim()
          : this.currentSeries.label;
      }

      const courseId = this.$route.query.id;
      if (courseId) {
        course.id = parseInt(courseId, 10);
      }

      const _tags = [];
      this.selectedTags.forEach((t) => {
        _tags.push(t.key);
      });
      course.tagIds = _tags;

      this.attachments.forEach((a) => {
        course.attachmenIds.push(a.id);
      });
      //课程介绍上传图片处理
      if (this.detailPicList.length > 0) {
        let urlList = this.detailPicList.map((e) => {
          return e.url;
        });
        course.detail = urlList.join(",");
      }

      saveCourse(course).then((res) => {
        if (res.resp_code === 200) {
          this.$message.success("课程保存成功");
          this.$router.push("/edu/biz/course/index");
        } else {
          this.$message.info(res.resp_msg);
        }
      });
    },
    //获取课程详情
    getCourseDetail(id) {
      getDetail(id)
        .then((res) => {
          if (res.resp_code == 200) {
            this.step1FormModel = {
              ...res.datas,
            };
            //构建课程介绍图片list
            // console.log(res.datas)
            if (res.datas.detail) {
              var picUrlAry = res.datas.detail.split(",");
              // console.log(picUrlAry)
              var list = [];
              var index = -1;
              picUrlAry.forEach((e) => {
                var obj = {};
                obj.uid = index + "";
                obj.name = obj.uid;
                obj.status = "done";
                obj.url = e;
                // console.log(obj)
                index--;
                list.push(obj);
              });

              this.detailPicList = list;
            }
            if (this.step1FormModel.allowOrgList) {
              const _enterprise = [];
              this.step1FormModel.allowOrgList.forEach((t) => {
                _enterprise.push(t.orgId);
              });
              this.step1FormModel.allowOrgIds = _enterprise;
            }

            if (this.step1FormModel.tagList) {
              this.step1FormModel.tagList.forEach((t) => {
                this.selectedTags.push({
                  key: t.tagId,
                  label: t.tagName,
                });
              });
            }

            this.currentSeries = {
              key: this.step1FormModel.seriesId,
              label: this.step1FormModel.seriesName,
            };

            // console.log(res.datas);

            const _attachments = [];
            res.datas.attachmentList.forEach((a) => {
              _attachments.push({
                id: a.resourceId,
                title: a.resourceName,
              });
            });
            this.attachments = _attachments;

            const _videoSeries = [];
            res.datas.chaperList.forEach((cc) => {
              _videoSeries.push({
                ...cc,
              });
            });
            this.videoSeries = _videoSeries;
            //用户标签
            console.log(this.step1FormModel.allow);
            if (this.step1FormModel.allow == "USER_TAG") {
              this.step1FormModel.userTagIds.split(",").forEach((item) => {
                this.selectedUserTagIds.push(parseInt(item));
              });
            }
          } else {
            this.$message.info(res.resp_msg);
          }
        })
        .catch((err) => {
          disposereq(this, err);
        });
    },

    //上传封面时上传中的回调
    handleChange(info) {
      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;
      const title = file.name.substring(0, file.name.indexOf("."));
      if (this.video.title == undefined || this.video.title == "") {
        this.video.title = title;
      }
      if (type.startsWith("video")) {
        return true;
      } else {
        this.$message.error("请选择视频文件");
        return false;
      }
    },

    beforeAttachmentUpload(file) {
      const { type } = file;
      const title = file.name.substring(0, file.name.indexOf("."));
      this.attachment.title = title;
    },

    saveAttachments() {
      if (this.attachment) {
        const { title, id } = this.attachment;
        if (!title) {
          this.$message.error("请填写附件标题");
          return;
        }
        if (!id) {
          this.$message.error("请上传附件文件");
          return;
        }

        this.attachments.push({
          title: title,
          id: id,
        });
        this.attachment = {};
        this.attachmentUploadModalVisible = false;
      }
    },

    uploadAttachment(data) {
      let self = this;
      const formData = new FormData();
      formData.append("file", data.file);
      uploadFile(formData)
        .then((res) => {
          if (res.data.resp_code == 200) {
            self.$refs.attachmentUploaderRef.onProgress(
              {
                percent: 100,
              },
              data.file
            );
            self.attachment.id = res.data.datas.id;
            self.$refs.attachmentUploaderRef.onSuccess(null, data.file);
          } else {
            this.$message.info("上传失败");
          }
          this.loading = false;
        })
        .catch((err) => {
          disposereq(this, err);
        });
    },

    uploadVideo({ file }) {
      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) {
          self.uploadVideoStatus = "uploading";
          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;
              }
            });
          } 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("文件上传成功");
          self.uploadVideoStatus = "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() {
      if (
        this.step1FormModel.type === "SINGLE" &&
        this.videoSeries.length > 0
      ) {
        this.$message.error("课程类型为单集,请先删除已有视频文件");
        return;
      } else {
        this.videoUploadModalVisible = true;
      }
    },
    closeVideoUploadModal() {
      this.videoUploadModalVisible = false;
      this.video = { videoType: "ALI" };
    },

    showAttachmentUploadModal() {
      this.attachmentUploadModalVisible = true;
    },
    closeAttachmentUploadModal() {
      this.attachmentUploadModalVisible = false;
      this.attachment = {};
    },

    videoUpload() {
      if (this.video) {
        const { title, id, videoType, videoUrl } = this.video;
        if (!title) {
          this.$message.error("请填写视频标题");
          return;
        }

        if (videoType === "ALI") {
          if (!id) {
            this.$message.error("请上传视频文件");
            return;
          }
          fetchVideoInfo(id).then((res) => {
            if (res.resp_code == 200) {
              const { coverURL, duration } = res.datas;
              if (this.step1FormModel.type === "SINGLE") {
                this.videoSeries = [
                  {
                    name: title,
                    videoId: id,
                    coverUrl: coverURL,
                    duration,
                  },
                ];
              } else {
                this.videoSeries.push({
                  name: title,
                  videoId: id,
                  coverUrl: coverURL,
                  duration,
                });
              }

              this.video = {};
              this.videoUploadModalVisible = false;
            }
          });
        } else {
          this.videoSeries.push({
            name: title,
            videoType: videoType,
            videoUrl: videoUrl,
          });
          this.videoUploadModalVisible = false;
        }
      }
    },
    //查询讲师
    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;
    },
    //上传课程简介图片
    uploadDetailPic(data) {
      const formData = new FormData();
      let uid = data.file.uid;
      formData.append("file", data.file);
      uploadFile(formData)
        .then((res) => {
          if (res.data.resp_code == 200) {
            this.detailPicList = this.detailPicList.map((e) => {
              if (e.uid == uid) {
                e.status = "done";
                e.url = res.data.datas.url;
              }
              return e;
            });
          } else {
            this.detailPicList.forEach((e) => {
              if (e.uid == uid) {
                e.status = "error";
              }
            });
          }
        })
        .catch((err) => {
          disposereq(this, err);
        });
    },
    beforUploadDetailPic(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("图片大小须小于2MB!");
      }
      return isLt2M;
    },
    uploadDetailPicChange(info) {
      if (info.file.status == "uploading") {
        this.detailPicList.push(info.file);
      }
    },
    uploadDetailRemove(file) {
      let newList = [];
      this.detailPicList.forEach((e) => {
        if (e.uid != file.uid) {
          newList.push(e);
        }
      });
      this.detailPicList = newList;
      return true;
    },
  },
};
</script>

<style>
.video_type {
  margin-bottom: 6px;
}
.attachment-icon {
  margin-right: 5px;
}

.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;
}

.video-image-background {
  background-position: 50%;
  background-repeat: no-repeat;
  background-size: contain;
  width: 100%;
  height: 100%;
}

.video-image {
  width: 120px;
  height: 68px;
  background: #d5d5d5 url("../../../assets/img/course/video-bg.png") no-repeat
    50%;
  display: inline-block;
  position: relative;
  cursor: pointer;
  background-size: 60px;
}

.video-image-time {
  position: absolute;
  text-align: right;
  color: #fff;
  width: 100%;
  right: 0;
  bottom: 0;
  z-index: 2;
  height: 24px;
  line-height: 24px;
  padding: 0 3px;
  background-image: linear-gradient(-180deg, transparent, rgba(0, 0, 0, 0.8));
}

.video-image-toolbar {
  position: absolute;
  text-align: right;
  color: #fff;
  width: 100%;
  right: 0;
  top: 0;
  z-index: 2;
  height: 24px;
  line-height: 24px;
  padding: 0 3px;
}

.video-image-play {
  position: absolute;
  top: 20px;
  left: 52px;
  z-index: 3;
  color: #fff;
  opacity: 0.4;
}

.video-image-cover {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 1;
}
</style>
