<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属达人" prop="talentName">
        <el-input
          v-model="queryParams.talentName"
          placeholder="请输入所属达人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="视频标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入视频标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="是否热门" prop="isHot">
        <el-select v-model="queryParams.isHot" placeholder="请选择来源" clearable size="small">
          <el-option
            v-for="dict in orOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in specShowOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="线路" prop="uploadType">
        <el-select v-model="queryParams.uploadType" placeholder="请选择线路" clearable size="small">
          <el-option
            v-for="dict in uploadTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="来源" prop="source">
        <el-select v-model="queryParams.source" placeholder="请选择来源" clearable size="small">
          <el-option
            v-for="dict in sourceOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
       <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="createTime" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="change"></el-date-picker>
      </el-form-item>
      <el-form-item label="审核时间" prop="auditTime">
        <el-date-picker v-model="auditTime" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="auditChange"></el-date-picker>
      </el-form-item>



      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:userVideo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:userVideo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['course:userVideo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['course:userVideo:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
        v-if="queryParams.isAudit==0 || queryParams.isAudit==-1"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="auditVideo"
          v-hasPermi="['course:userVideo:audit']"
        >批量审核</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
        v-if="queryParams.status==0 && queryParams.status!=''"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="putOn"
          v-hasPermi="['course:userVideo:putOn']"
        >上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-if="queryParams.status==1 && queryParams.status!=''"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="pullOff"
          v-hasPermi="['course:userVideo:pullOff']"
        >下架</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-tabs type="card" v-model="queryParams.isAudit" @tab-click="handleClickX">
      <el-tab-pane v-for="(item,index) in isAuditOptions" :label="item.dictLabel" :name="item.dictValue"></el-tab-pane>
    </el-tabs>
    <el-table v-loading="loading" :data="userVideoList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="videoId" />
      <el-table-column label="视频标题" align="center" prop="title" show-overflow-tooltip />
      <el-table-column label="视频缩略图" align="center" prop="thumbnail" width="110px">
        <template slot-scope="scope">
           <el-popover
             placement="right"
             title=""
             trigger="hover">
             <img slot="reference" :src="scope.row.thumbnail" width="100" height="100">
             <img :src="scope.row.thumbnail" style="max-width: 150px;">
           </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="视频时长(秒)" align="center" prop="duration" />
      <el-table-column label="所属达人" align="center" prop="talentName" />
      <el-table-column label="点赞量" align="center" prop="likes" />
      <el-table-column label="播放量" align="center" prop="views" />
      <el-table-column label="审核人" align="center" prop="auditUserName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="审核时间" align="center" prop="auditTime" width="180"/>
      <el-table-column label="来源" align="center" prop="source">
        <template slot-scope="scope">
          <dict-tag :options="sourceOptions" :value="scope.row.source"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150px">
        <template slot-scope="scope">
          <el-button v-if="scope.row.isAudit!=1"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="auditVideo(scope.row)"
            v-hasPermi="['course:userVideo:audit']"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleDetails(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:userVideo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:userVideo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课堂视频对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" v-loading="uploadLoading">
        <el-form-item label="视频标题" prop="title">
          <el-input v-model="form.title" type="textarea" :rows="2" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="视频描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="2"  placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="关联达人" >
          <el-select v-model="form.talentId" remote filterable reserve-keyword placeholder="输入手机号搜索" :remote-method="talentMethod" clearable >
            <el-option
              v-for="item in talentList"
              :key="item.talentId"
              :label="item.nickName +'#'+item.phone"
              :value="item.talentId">
              <span style="float: left">{{ item.talentId }}</span>
              <span style="margin-left: 30px ;">{{item.nickName}}</span>
              <span style="margin-left: 30px">{{ item.phone }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="关联疗法" prop="productId" >
          <el-select v-model="form.productId" remote filterable reserve-keyword placeholder="输入套餐包别名搜索" :remote-method="packageMethod" clearable @change="selectPackage" >
            <el-option
              v-for="item in packageList"
              :key="item.packageId"
              :label="item.secondName +'#'+item.packageId"
              :value="item.packageId">
              <span style="float: left">{{ item.packageId }}</span>
              <span style="margin-left: 30px ;">{{item.packageName}}</span>
              <span style="margin-left: 30px">{{ item.secondName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="form.isAudit ==1">
          <el-radio-group v-model="form.status">
            <el-radio :label="item.dictValue" v-for="item in specShowOptions" >{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="视频缩略图" prop="thumbnail">
          <el-upload
            v-model="form.thumbnail"
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
      :headers="uploadHeaders"
    >
            <img v-if="form.thumbnail" :src="form.thumbnail" class="avatar" width="300px">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <video-upload
          :type="2"
          :videoUrl.sync="videoUrl"
          :fileKey.sync = "form.fileKey"
          :fileSize.sync = "form.fileSize"
          :line_1.sync="form.txPcdnUrl"
          :line_2.sync="form.hwObsUrl"
          :thumbnail.sync="form.thumbnail"
          :uploadType.sync="form.uploadType"
          @video-duration="handleVideoDuration"
          @change="handleVideoChange"
          ref="videoUpload"
        />
        <el-row>
          <el-col :span="8">
            <el-form-item label="收藏数" prop="favoriteNum">
              <el-input-number v-model="form.favoriteNum" :min="0"   label="收藏数"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="播放量" prop="views">
              <el-input-number v-model="form.views" :min="0"  label="浏览量"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="点赞量" prop="likes">
              <el-input-number v-model="form.likes" :min="0"   label="点赞量"></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="分享数" prop="shares">
              <el-input-number v-model="form.shares" :min="0"   label="分享数"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="评论数" prop="comments">
              <el-input-number v-model="form.comments" :min="0"   label="分享数"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="tags"  label="标签">
              <el-select v-model="tags" placeholder="请选择标签" multiple filterable clearable size="small">
                <el-option
                  v-for="dict in tagList"
                  :key="dict.tagId"
                  :label="dict.tagName"
                  :value="dict.tagId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="auditDialog.title" :visible.sync="auditDialog.open" width="800px" append-to-body @close="auditDialogClose">
      <el-form ref="auditForm" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="审核" prop="isAudit">
        <el-radio-group v-model="auditForm.isAudit">
          <el-radio :label="item.dictValue" v-for="item in auditRadio" >{{item.dictLabel}}</el-radio>
        </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" v-model="auditForm.remark" placeholder="备注" />
        </el-form-item>
        <el-form-item prop="tags" style="width: 500px" label="标签">
          <el-select v-model="auditTags" placeholder="请选择标签" multiple filterable clearable size="small">
            <el-option
              v-for="dict in tagList"
              :key="dict.tagId"
              :label="dict.tagName"
              :value="dict.tagId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" >
        <el-button type="primary" @click="submitAuditForm">提交</el-button>
        <el-button @click="auditDialogClose">取消</el-button>
      </div>
    </el-dialog>
    <el-drawer
      :with-header="false"
      size="75%"
      :visible.sync="show.open">
      <userVideoDetails  ref="userVideoDetails" />
    </el-drawer>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import VideoUpload from '@/components/VideoUpload/index';
import { listUserVideo, getUserVideo, delUserVideo, addUserVideo, updateUserVideo, exportUserVideo,auditUserVideo,putOn,pullOff } from "@/api/course/userVideo";
import {getSignature,uploadHuaWeiVod} from "@/api/common"
import { listBySearch} from "@/api/course/userTalent";
import { subList} from "@/api/course/userVideoTags";
import { packageBySearch} from "@/api/his/package";
import TcVod from 'vod-js-sdk-v6'
import userVideoDetails from '../../components/course/userVideoDetails.vue';
import { BasicCredentials } from '@huaweicloud/huaweicloud-sdk-core';
import { VodClient, VodRegion, CreateAssetByFileUploadRequest,ShowAssetTempAuthorityRequest } from '@huaweicloud/huaweicloud-sdk-vod';
import axios from 'axios';
import { Loading } from 'element-ui';
import { uploadObject } from '@/utils/cos.js';
import { uploadToOBS } from '@/utils/obs.js';
export default {
  name: "UserVideo",
  components: {
    userVideoDetails,VideoUpload
  },
  data() {
    return {
      uploadHeaders: { Authorization: "Bearer " + getToken() },
      tagsOptions:[],
      tags:[],

      //所有的标签
      tagList:[],
      uploadTypeOptions:[{
        "dictLabel": "线路一",
        "dictValue": 1
      },
        {
          "dictLabel": "线路二",
          "dictValue": 2
        },

      ],
      specShowOptions:[],
      finalQuality:1,
      packageItem:{},
      uploadLoading:false,
      show:{
        title:"短视频详情",
        open :false
      },
      auditRadio: [{
        "dictLabel": "通过",
        "dictValue": 1
      }, {
        "dictLabel": "驳回",
        "dictValue": -1
      }],
      auditDialog:{
        title:"短视频审核",
        open:false
      },
      auditTags:[],
      auditForm:{
        videoIds:[],
        isAudit:null,
        tags:''
      },
      auditRules:{
        isAudit: [
          { required: true, message: "请选择审核状态", trigger: "blur" }
        ],
      },
      isAuditOptions:[],
      talentParam:{
        phone:null,
        talentId:null,
      },
      packageParam:{
        secondName:null,
        packageId:null,
        isShow:1,
        status:1
      },
      talentList:[],
      packageList:[],
      files:[],
      fileList: [],
      // 上传成功后的地址
      videoURL: '',
      // 进度条百分比
      progress: 0,
      // 上传视频获取成功后拿到的fileID【备用】
      fileId: '',
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      videoUrl: "",
      videoAccept:"video/*",
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      baseUrl: process.env.VUE_APP_BASE_API,
      cateOptions:[],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课堂视频表格数据
      userVideoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 课程ID字典
      courseIdOptions: [],
      // 视频状态 1：草稿，2：待审核，3：发布字典
      statusOptions: [],
      // 是否展示字典
      orOptions: [],
      // 来源 1 用户 2 后台字典
      sourceOptions: [],
      // 删除标志字典
      isDelOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        description: null,
        url: null,
        thumbnail: null,
        duration: null,
        userId: null,
        cateId: null,
        courseId: null,
        likes: null,
        views: null,
        comments: null,
        status: null,
        courseSort: null,
        isHot: null,
        isShow: null,
        isAudit: 0,
        auditBy: null,
        auditTime: null,
        source: null,
        isDel: null,
        shares: null,
        tags: '',
        productId: null,
        productJson: null,
        sTime:null,
        eTime:null,
        auditsTime:null,
        auditeTime:null,
      },
       createTime:null,
       auditTime:null,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "短视频标题不能为空", trigger: "blur" }
        ],
        // talentId: [
        //   { required: true, message: "关联达人不能为空", trigger: "change" }
        // ],
        thumbnail: [
          { required: true, message: "请上传视频封面", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getTagList();
    this.getDicts("sys_course_tags").then(response => {
      this.tagsOptions = response.data;
    });
    this.getDicts("sys_spec_show").then(response => {
      this.specShowOptions = response.data;
    });
    this.getDicts("sys_user_video_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_company_or").then(response => {
      this.orOptions = response.data;
    });
    this.getDicts("sys_user_video_cate").then(response => {
      this.cateOptions = response.data;
    });
    this.getDicts("sys_video_source").then(response => {
      this.sourceOptions = response.data;
    });
    this.getDicts("sys_company_isaudit").then(response => {
      this.isAuditOptions = response.data;
    });
    this.getDicts("sys_company_or").then(response => {
      this.isDelOptions = response.data;
    });
  },
  methods: {
    getTagList(){
      subList().then(response => {
        this.tagList = response.data;
      });
    },
    handleVideoChange(){
      if(this.form.uploadType===1){
        this.videoUrl = this.form.txPcdnUrl;
      }else if(this.form.uploadType===2){
        this.videoUrl = this.form.hwObsUrl;
      }
      console.log("选择的video=======>>>>>>>",this.videoUrl)
    },
    handleVideoDuration(duration) {
      this.form.duration = duration;
    },
    selectPackage(){
      const packageItem = this.packageList.find(item=> item.packageId === this.form.productId);
      console.log(packageItem);
      if (packageItem) {
          this.packageItem = packageItem;
      }
    },
    handleDetails(row){
      this.show.open=true;
      setTimeout(() => {
        this.$refs.userVideoDetails.getDetails(row.videoId);
      }, 500);
    },
    submitAuditForm(){
      this.$refs["auditForm"].validate(valid => {
        if(valid){
          if(this.auditTags.length>0){
            this.auditForm.tags=this.auditTags.toString();
          }
          else{
            this.auditForm.tags = null
          }
          if (this.auditForm.videoIds !== []) {
            auditUserVideo(this.auditForm).then(response => {
              this.msgSuccess("审核成功");
              this.auditDialogClose();
              this.getList();
            });
          }
        }
      });
    },
    change(){
      if(this.createTime!=null){
        this.queryParams.sTime=this.createTime[0];
        this.queryParams.eTime=this.createTime[1];
      }else{
        this.queryParams.sTime=null;
        this.queryParams.eTime=null;
      }

    },
    auditChange(){
      if(this.auditTime!=null){
        this.queryParams.auditsTime=this.auditTime[0];
        this.queryParams.auditeTime=this.auditTime[1];
      }else{
        this.queryParams.auditsTime=null;
        this.queryParams.auditeTime=null;
      }

    },
    auditDialogClose(){
      this.auditDialog.open = false;
    },
    auditVideo(row){
      this.auditForm={
        videoIds:[],
        isAudit:1
      },
      this.auditDialog.open=true;
      this.auditForm.videoIds = row.videoId ? [row.videoId] : this.ids;
    },

    handleClickX(){
      this.getList()
    },
    talentMethod(query){
      if (query !== '') {
        this.talentParam.phone = query;
        listBySearch(this.talentParam).then(response => {
          this.talentList = response.data;
        });
      }
    },
    packageMethod(query){
      if (query !== '') {
        this.packageParam.secondName = query;
        packageBySearch(this.packageParam).then(response => {
          this.packageList = response.data;
        });
      }
    },

    /** 查询课堂视频列表 */
    getList() {
      this.loading = true;
      listUserVideo(this.queryParams).then(response => {
        this.userVideoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        videoId: null,
        title: null,
        description: null,
        url: null,
        thumbnail: null,
        duration: null,
        createTime: null,
        userId: null,
        cateId: null,
        courseId: null,
        likes: null,
        views: null,
        comments: null,
        favoriteNum:null,
        status: null,
        isHot: null,
        isShow: null,
        isAudit: null,
        auditBy: null,
        auditTime: null,
        updateTime: null,
        source: null,
        isDel: null,
        shares: null,
        tags: null,
        txCdnUrl:null,
        txPcdnUrl:null,
        hwObsUrl:null,
        productId: null,
        productJson: null
      };
      this.tags=[];
      this.talentList=null
      this.packageList=null
      this.packageParam={
        packageId:null,
        secondName:null
      }
      this.packageParam={
        packageId:null,
        secondName:null
      }
      this.talentParam={
        talentId:null,
        phone:null
      }
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.createTime=null;
      this.queryParams.sTime=null;
      this.queryParams.eTime=null;
      this.auditTime=null;
      this.queryParams.auditsTime=null;
      this.queryParams.auditeTime=null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.videoId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handleAvatarSuccess(res, file) {
      if(res.code===200){
            this.form.thumbnail=res.url;
            this.$forceUpdate()
          }
          else{
            this.msgError(res.msg);
          }
    },
    beforeAvatarUpload(file) {
      return new Promise((resolve, reject) => {
        if (file.size / 1024 / 1024 > 3) {
          this.$message.error('上传的图片不能超过3MB');
          reject();
          return;
        }
        if (file.size / 1024 / 1024 > 1) {
          const loadingInstance = Loading.service({ text: '图片内存过大正在压缩图片...' });
          // 文件大于1MB时进行压缩
          this.compressImage(file).then((compressedFile) => {
            loadingInstance.close();
            if (compressedFile.size / 1024 > 500) {
              this.$message.error('图片压缩后仍大于500KB');
              reject();
            } else {
              // this.$message.success(`图片压缩成功，最终质量为: ${this.finalQuality.toFixed(2)}`);
              console.log(`图片压缩成功，最终质量为: ${this.finalQuality.toFixed(2)}`);
              console.log(`最终内存大小为: ${(compressedFile.size/1024).toFixed(2)}KB`);
              resolve(compressedFile);
            }
          }).catch((err) => {
            loadingInstance.close();
            console.error(err);
            reject();
          });
        } else {
          resolve(file);
        }
      });
      // const isLt1M = file.size / 1024 / 1024 < 1;
      // if (!isLt1M) {
      //   this.$message.error('上传图片大小不能超过 1MB!');
      // }
      // return   isLt1M;
    },
    compressImage(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (event) => {
          const img = new Image();
          img.src = event.target.result;
          img.onload = () => {
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            const width = img.width;
            const height = img.height;
            canvas.width = width;
            canvas.height = height;
            ctx.drawImage(img, 0, 0, width, height);

            let quality = 1; // 初始压缩质量
            let dataURL = canvas.toDataURL('image/jpeg', quality);

            // 逐步压缩，直到图片大小小于500KB并且压缩质量不再降低
            while (dataURL.length / 1024 > 500 && quality > 0.1) {
              quality -= 0.01;
              dataURL = canvas.toDataURL('image/jpeg', quality);
            }
            this.finalQuality = quality; // 存储最终的压缩质量

            if (dataURL.length / 1024 > 500) {
              reject(new Error('压缩后图片仍然大于500KB'));
              return;
            }

            const arr = dataURL.split(',');
            const mime = arr[0].match(/:(.*?);/)[1];
            const bstr = atob(arr[1]);
            let n = bstr.length;
            const u8arr = new Uint8Array(n);
            while (n--) {
              u8arr[n] = bstr.charCodeAt(n);
            }
            const compressedFile = new Blob([u8arr], { type: mime });
            compressedFile.name = file.name;
            resolve(compressedFile);
          };
          img.onerror = (error) => {
            reject(error);
          };
        };
        reader.onerror = (error) => {
          reject(error);
        };
      });
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课堂视频";
      this.process = 0;
      this.videoUrl=null;
      this.packageItem = null;
      setTimeout(() => {
        this.$refs.videoUpload.resetUpload();
      }, 500);

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const videoId = row.videoId || this.ids
      this.videoUrl=null;
      getUserVideo(videoId).then(response => {

        this.form = response.data;
        if(response.data.url!=null&&response.data.url!==''){
            this.videoUrl = response.data.url;
          }
        if(response.data.tags!=null){
          this.tags = response.data.tags.split(",");
        }
        this.form.status = response.data.status.toString();
        setTimeout(() => {
          this.$refs.videoUpload.resetUpload();
        }, 500);
        this.talentParam.talentId = response.data.talentId;
        listBySearch(this.talentParam).then(response => {
          this.talentList = response.data;
        });
        if(response.data.productId!=null){
          this.packageParam.packageId = response.data.productId;
          packageBySearch(this.packageParam).then(response => {
            this.packageList = response.data;
          });
        }
        this.open = true;
        this.title = "修改课堂视频";
      });
      // setTimeout(() => {
      //     this.form.duration=parseInt(this.$refs.myvideo.duration);
      //     console.log(this.$refs.myvideo.duration);
      // }, 2000);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.tags.length>0){
            this.form.tags=this.tags.toString();
          }
          else{
            this.form.tags=null
          }
          this.form.url = this.videoUrl;
          if(this.form.url==null || this.form.url===''){
            this.$message({
              message: '请上传视频！',
              type: 'info'
            });
          return
          }
          if(this.form.duration==null){
            this.$message({
              message: '未识别到视频时长请稍等。。。',
              type: 'info'
            });
          return
          }
          if(this.packageItem!=null&&this.packageItem!==''){
            this.form.productJson = JSON.stringify(this.packageItem)
          }
          console.log("组装数据=====>",this.form);
          if (this.form.videoId != null) {
            updateUserVideo(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUserVideo(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const videoIds = row.videoId || this.ids;
      this.$confirm('是否确认删除课堂视频编号为"' + videoIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delUserVideo(videoIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有课堂视频数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportUserVideo(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    putOn() {
      const videoIds =this.ids;
      if(videoIds==null||videoIds===""){
         return this.$message("未选择短视频");
      }
      this.$confirm('是否确认批量上架短视频?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return putOn(videoIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("上架成功");
        }).catch(function() {});
    },
    pullOff() {
      const videoIds =this.ids;
      if(videoIds==null||videoIds===""){
         return this.$message("未选择短视频");
      }
      this.$confirm('是否确认批量下架短视频?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return pullOff(videoIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("下架成功");
        }).catch(function() {});
    }
  }
};
</script>
<style scoped>
.tag-box{
  margin: 10px;
  padding: 5px;
  background-color: #f7f7f7 ;
  border-radius: 4px;
  border: 1px solid #d0d0d0 ;
}
.tag-selectd{
  background-color: rgb(231, 244, 255) ;
  border: 1px solid rgb(11, 162, 255) ;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
   .avatar-uploader .el-upload {
       border: 1px dashed #d9d9d9;
       border-radius: 6px;
       cursor: pointer;
       position: relative;
       overflow: hidden;
     }
     .avatar-uploader .el-upload:hover {
       border-color: #409EFF;
     }

     .avatar-uploader-icon {
       font-size: 28px;
       color: #8c939d;
       width: 150px;
       height: 150px;
       line-height: 150px;
       text-align: center;
     }
</style>
