<template>
  <div>
    <el-form-item label="视频上传">
      <div class="upload_video" id="upload_video">
        <div class="upload-toolbar">
          <el-upload
            class="upload-picker"
            ref="upload"
            action="#"
            accept=".mp4"
            :limit="1"
            :show-file-list="false"
            :on-remove="handleRemove"
            :on-change="handleChange"
            :auto-upload="false"
            :key="uploadKey"
          >
            <el-button slot="trigger" size="small" type="primary">选取视频</el-button>
          </el-upload>
          <el-button
            size="small"
            type="success"
            :loading="uploadLoading"
            :disabled="!hasLocalFile"
            @click="submitUpload"
          >点击上传</el-button>
          <el-button
            v-if="showControl"
            size="small"
            type="success"
            plain
            @click="openVideoLibrary"
          >视频库选取</el-button>
        </div>
        <p class="upload-tip">只能上传mp4文件，且不超过500M</p>
        <div v-if="displayFileName" class="upload-file-info">
          <i class="el-icon-document" />
          <span class="upload-file-name" :title="displayFileName">{{ displayFileName }}</span>
        </div>
        <div class="progress-container">
          <div class="progress-row">
            <span class="progress-label">线路一</span>
            <span class="progress-percent">{{ txProgress }}%</span>
          </div>
          <el-progress
            class="progress-bar"
            :percentage="txProgress"
            :stroke-width="18"
            :show-text="false"
            :status="txProgress >= 100 ? 'success' : undefined"
          />
        </div>
        <div class="progress-container">
          <div class="progress-row">
            <span class="progress-label">线路二</span>
            <span class="progress-percent">{{ hwProgress }}%</span>
          </div>
          <el-progress
            class="progress-bar"
            :percentage="hwProgress"
            :stroke-width="18"
            :show-text="false"
            :status="hwProgress >= 100 ? 'success' : undefined"
          />
        </div>
      </div>
    </el-form-item>
    <el-form-item label="视频播放">
      <video v-if="videoUrl" ref="myvideo" :src="videoUrl" id="video" width="100%" height="300px" controls></video>
      <div v-if="fileName">视频文件名: {{ fileName }}</div>
      <div v-if="fileKey">文件Key: {{ fileKey }}</div>
      <div v-if="fileSize">文件大小(MB): {{ (fileSize / (1024 * 1024)).toFixed(2) }} MB</div>
    </el-form-item>
    <!-- 仅当showControl为true时显示播放线路选择器 -->
    <el-form-item v-if="showControl" label="播放线路">
      <el-radio-group v-model="localUploadType">
        <el-radio :label="1" >线路一</el-radio>
        <el-radio :label="2" >线路二</el-radio>
        <!--        <el-radio :label="3" >线路三</el-radio>-->
      </el-radio-group>
    </el-form-item>

    <!-- 视频库选择对话框 -->
    <el-dialog title="视频库选择" :visible.sync="libraryOpen" width="900px" append-to-body>
      <!-- 搜索条件 -->
      <el-form :inline="true" :model="libraryQueryParams" class="library-search">
        <el-form-item label="素材名称">
          <el-input
            v-model="libraryQueryParams.resourceName"
            placeholder="请输入素材名称"
            clearable
            size="small"
            @keyup.enter.native="handleLibraryQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleLibraryQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetLibraryQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 视频列表 -->
      <el-table v-loading="libraryLoading" :data="libraryList" @row-click="handleLibrarySelect" highlight-current-row>
        <el-table-column label="素材名称" align="center" prop="resourceName" />
        <el-table-column label="文件名称" align="center" prop="fileName" />
        <el-table-column label="缩略图" align="center">
          <template slot-scope="scope">
            <el-popover
              placement="right"
              title=""
              trigger="hover"
            >
              <img alt="" slot="reference" :src="scope.row.thumbnail" style="width: 80px; height: 50px" />
              <img alt="" :src="scope.row.thumbnail" style="max-width: 150px;" />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="视频时长" align="center">
          <template slot-scope="scope">
            <span>{{ formatDuration(scope.row.duration) }}</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination
        v-show="libraryTotal>0"
        :total="libraryTotal"
        :page.sync="libraryQueryParams.pageNum"
        :limit.sync="libraryQueryParams.pageSize"
        @pagination="getLibraryList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="confirmVideoSelection">确 定</el-button>
        <el-button @click="cancelVideoSelection">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {getThumbnail} from "@/api/course/userVideo";
import { uploadObject } from "@/utils/cos.js";
import { uploadToHSY } from "@/utils/hsy.js";
import Pagination from "@/components/Pagination";
import { listVideoResource } from '@/api/course/videoResource';
import Vue from 'vue';

export default {
  components: {
    Pagination
  },
  props: {
    videoUrl: {
      type: String,
      default: "",
    },
    fileKey: {
      type: String,
      default: "",
    },
    fileSize: {
      type: Number,
      default: null,
    },
    fileName: {
      type: String,
      default: "",
    },
    line_1: {
      type: String,
      default: "",
    },
    line_2: {
      type: String,
      default: "",
    },
    line_3: {
      type: String,
      default: "",
    },
    thumbnail: {
      type: String,
      default: "",
    },
    uploadType: {
      type: Number,
      default: null,
    },
    type: {
      type: Number,
      default: null,
    },
    isPrivate: {
      type: Number,
      default: 0,
    },

    // 使用一个变量控制显示，默认为true显示所有控制项
    showControl: {
      type: Boolean,
      default: true,
    }
  },
  data() {
    return {
      videoName:'',
      isHidden : false,
      localUploadType: this.uploadType,
      duration: 0,
      fileId: "",
      uploadTypeOptions: [
        { dictLabel: "线路一", dictValue: 1 }, // 腾讯云 COS
        { dictLabel: "线路二", dictValue: 2 }, // 火山云点播
        // { dictLabel: "华为云VOD", dictValue: 4 },
        // { dictLabel: "腾讯云VOD", dictValue: 5 },
      ],
      fileList: [],
      txProgress: 0,
      hwProgress: 0,
      uploadLoading: false,
      uploadKey: 0,
      // 视频库选择相关数据
      libraryOpen: false,
      libraryLoading: false,
      libraryTotal: 0,
      libraryList: [],
      selectedVideo: null,
      libraryQueryParams: {
        pageNum: 1,
        pageSize: 10,
        resourceName: null
      }
    };
  },
  computed: {
    hasLocalFile() {
      return this.fileList.length > 0;
    },
    displayFileName() {
      if (this.fileList.length > 0) {
        return this.fileList[0].name;
      }
      return this.fileName || "";
    }
  },
  watch: {
    localUploadType(newType) {
      this.$emit("update:uploadType", newType);
      this.$emit("change");
    },
    uploadType(newType) {
      this.localUploadType = newType;
    },
  },
  methods: {
    normalizeProgress(value) {
      const num = Number(value);
      if (!Number.isFinite(num)) {
        return 0;
      }
      if (num <= 1) {
        return Math.min(100, Math.max(0, Math.round(num * 100)));
      }
      return Math.min(100, Math.max(0, Math.round(num)));
    },
    // 打开视频库对话框
    openVideoLibrary() {
      this.libraryOpen = true;
      this.selectedVideo = null;
      this.getLibraryList();
    },
    handleChange(file, fileList) {
      this.fileList = fileList;
      this.getVideoDuration(file.raw);
    },
    getVideoDuration(file) {
      const video = document.createElement("video");
      video.preload = "metadata";
      video.onloadedmetadata = () => {
        window.URL.revokeObjectURL(video.src);
        this.duration = parseInt(video.duration.toFixed(2));
        console.log("视频时长=========>",this.duration);
        this.$emit("video-duration", this.duration);
        console.log("文件大小=====>",file.size);
        this.$emit("update:fileSize", file.size);
      };
      video.src = URL.createObjectURL(file);
    },
    async submitUpload() {
      if (this.fileList.length < 1) {
        return this.$message.error("请先选取视频，再进行上传");
      }
      this.uploadLoading = true;
      this.txProgress = 0;
      this.hwProgress = 0;
      try {
        await this.getFirstThumbnail();
        await this.uploadVideoToTxPcdn();
        await this.uploadVideoToHsy();
        this.$emit("update:fileName", this.fileList[0].name);
      } finally {
        this.uploadLoading = false;
      }
    },
    //获取第一帧封面
    async getFirstThumbnail(){
      const file = this.fileList[0].raw;
      getThumbnail(file).then(response => {
        console.log("获取到第一帧为封面======>",response.url)
        this.$emit("update:thumbnail", response.url);
      })
    },
    // 更新火山云线路进度条
    updateHwProgress(progress) {
      if (typeof progress === "number") {
        this.hwProgress = this.normalizeProgress(progress);
        return;
      }
      if (progress && typeof progress.percent === "number") {
        this.hwProgress = this.normalizeProgress(progress.percent);
      }
    },
    // 更新腾讯线路进度条
    updateTxProgress(progressData) {
      if (progressData && typeof progressData.percent === "number") {
        this.txProgress = this.normalizeProgress(progressData.percent);
      }
    },
    //上传腾讯云Pcdn
    async uploadVideoToTxPcdn() {
      try {
        const file = this.fileList[0].raw;
        const data = await uploadObject(file, this.updateTxProgress,this.type);
        const lineBase = Vue.prototype.$runtimeConfig.VUE_APP_VIDEO_LINE_1 || process.env.VUE_APP_VIDEO_LINE_1 || '';
        const line_1 = `${lineBase}${data.urlPath}`;
        const urlPathWithoutFirstSlash = data.urlPath.startsWith('/') ? data.urlPath.substring(1) : data.urlPath;
        this.$emit("update:fileKey", urlPathWithoutFirstSlash);
        this.$emit("update:videoUrl", line_1);
        this.$emit("update:line_1", line_1);
        this.txProgress = 100;
        this.$message.success("线路一上传成功");
      } catch (error) {
        this.txProgress = 0;
        console.error('线路一上传失败', error);
        this.$message.error(error?.message || "线路一上传失败");
      }
    },
    // 上传火山云点播（线路二）
    async uploadVideoToHsy() {
      try {
        const file = this.fileList[0].raw;
        const data = await uploadToHSY(file, this.updateHwProgress, this.type);
        const videoBase = Vue.prototype.$runtimeConfig.VUE_APP_VIDEO_URL || process.env.VUE_APP_VIDEO_URL || '';
        if (!videoBase) {
          throw new Error('未配置火山云视频地址，请在「系统参数 → 前端配置」中填写')
        }
        const line_2 = `${videoBase}/${data.SourceInfo.FileName}`;
        this.$emit("update:line_2", line_2);
        this.hwProgress = 100;
        this.$message.success("线路二上传成功");
      } catch (error) {
        this.hwProgress = 0;
        console.error('线路二上传失败', error);
        const msg = error?.message || error?.extra?.message || "线路二上传失败";
        this.$message.error(msg);
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList.length);
    },
    resetUpload() {
      // 重置内部状态
      this.txProgress = 0;
      this.hwProgress = 0;
      this.fileList = [];
      this.uploadKey++;
      this.localUploadType = this.uploadType;
    },
    /** 查询视频库列表 */
    getLibraryList() {
      this.libraryLoading = true;
      listVideoResource(this.libraryQueryParams).then(response => {
        this.libraryList = response.rows;
        this.libraryTotal = response.total;
        this.libraryLoading = false;
      });
    },
    /** 搜索视频库按钮操作 */
    handleLibraryQuery() {
      this.libraryQueryParams.pageNum = 1;
      this.getLibraryList();
    },
    /** 重置视频库查询按钮操作 */
    resetLibraryQuery() {
      this.libraryQueryParams = {
        pageNum: 1,
        pageSize: 10,
        resourceName: null
      };
      this.handleLibraryQuery();
    },
    /** 视频库选择行点击 */
    handleLibrarySelect(row) {
      this.selectedVideo = row;
    },
    /** 格式化视频时长 */
    formatDuration(seconds) {
      if (!seconds) return '00:00';

      const minutes = Math.floor(seconds / 60);
      const remainingSeconds = seconds % 60;

      return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    },
    /** 确认选择视频 */
    confirmVideoSelection() {
      if (!this.selectedVideo) {
        this.$message.warning("请选择一个视频");
        return;
      }

      // 更新组件内部数据
      this.$emit("update:fileName", this.selectedVideo.fileName);
      this.$emit("update:thumbnail", this.selectedVideo.thumbnail);
      this.$emit("update:line_1", this.selectedVideo.line1);
      this.$emit("update:line_2", this.selectedVideo.line2);
      this.$emit("update:line_3", this.selectedVideo.line3);
      this.$emit("update:fileSize", this.selectedVideo.fileSize);
      this.$emit("update:fileKey", this.selectedVideo.fileKey);
      this.$emit("update:uploadType", this.selectedVideo.uploadType);
      this.$emit("video-duration", this.selectedVideo.duration);

      // 设置预览URL
      this.$emit("update:videoUrl", this.selectedVideo.videoUrl);

      // 题目
      this.$emit("selectProjects", this.selectedVideo.projectIds)

      this.libraryOpen = false;
    },
    /** 取消视频选择 */
    cancelVideoSelection() {
      this.libraryOpen = false;
      this.selectedVideo = null;
    }
  }
};
</script>

<style scoped>
.upload_video {
  width: 100%;
  max-width: 560px;
}

.upload-toolbar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.upload_video ::v-deep .upload-picker {
  display: inline-block;
  line-height: normal;
}

.upload_video ::v-deep .upload-picker .el-upload {
  display: inline-block;
  margin: 0;
  border: none;
}

.upload-tip {
  margin: 8px 0 0;
  font-size: 12px;
  line-height: 1.5;
  color: #909399;
}

.upload-file-info {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  padding: 8px 10px;
  font-size: 13px;
  line-height: 1.4;
  color: #606266;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
}

.upload-file-info .el-icon-document {
  flex-shrink: 0;
  font-size: 16px;
  color: #409eff;
}

.upload-file-name {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.progress-container {
  width: 100%;
  margin-top: 12px;
}

.progress-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}

.progress-label {
  font-weight: bold;
  font-size: 13px;
  color: #303133;
}

.progress-percent {
  font-size: 12px;
  color: #606266;
}

.progress-bar {
  width: 100%;
}

.progress-bar ::v-deep .el-progress-bar__outer {
  background-color: #ebeef5;
}

.progress-bar ::v-deep .el-progress-bar__inner {
  transition: width 0.3s ease;
}
</style>

<style>
/* 视频库弹窗表格行可点击（弹窗 append-to-body，不宜 scoped） */
.library-search {
  margin-bottom: 15px;
}

.el-table .el-table__row:hover {
  cursor: pointer;
}
</style>
