<template>
  <div class="app-container live-page">

    <div class="live-page__header">
      <h2 class="live-page__title">直播视频</h2>
    </div>

    <div class="live-panel" v-show="showSearch">
      <el-form class="live-search-form" :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="视频名称" prop="videoName">
        <el-input
          v-model="queryParams.videoName"
          placeholder="请输入视频名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="category">
        <el-select
          v-model="queryParams.category"
          placeholder="请选择分类"
          clearable
          filterable
          style="width: 200px"
        >
          <el-option
            v-for="item in categoryOptions"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="可见公司" prop="companyId">
        <el-select
          v-model="queryParams.companyId"
          placeholder="请选择可见公司"
          clearable
          filterable
          style="width: 200px"
        >
          <el-option
            v-for="company in allCompanyOptions"
            :key="company.companyId"
            :label="company.companyName"
            :value="company.companyId"
          />
        </el-select>
      </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>
    </div>

    <div class="live-panel live-panel--table">
<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="['live:liveVideo:add']"
        >新增</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="['live:liveVideo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleBatchUpdateCategory"
        >批量修改分类</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleBatchUpload"
        >批量上传视频</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="liveVideoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="videoId" />
      <el-table-column label="视频名称" align="center" prop="videoName" />
      <el-table-column label="分类" align="center" prop="category" :formatter="categoryFormatter" />
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="视频" align="center" prop="videoUrl" width="96">
        <template slot-scope="scope">
          <div class="live-video-thumb" @click="openVideoPlay(scope.row)">
            <img
              v-if="scope.row.thumbnail"
              :src="scope.row.thumbnail"
              class="live-cell__cover live-cell__cover--square"
              alt=""
            />
            <div v-else class="live-cell__cover live-cell__cover--square live-video-thumb__empty">
              <i class="el-icon-video-camera"></i>
            </div>
            <i class="el-icon-video-play live-video-thumb__play"></i>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="文件大小" align="center">
        <template slot-scope="scope">
          <span>{{ formatFileSize(scope.row.fileSize) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="时长" align="center" prop="duration" :formatter="formatDuration"/>
      <el-table-column label="转码状态" align="center" prop="finishStatus">
        <template slot-scope="scope">
          <span v-if="scope.row.finishStatus == 1" class="live-ok">转码成功</span>
          <span v-else-if="scope.row.finishStatus == 0" class="live-warn">转码中</span>
          <span v-else class="live-muted">---</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateVideoInfo(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdateCompanyIds(scope.row)"
          >修改公司范围</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="handleReuploadVideo(scope.row)"
          >再次上传视频</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"
    />
    </div>

    <!-- 添加或修改直播视频对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <live-video-upload
          :type = "1"
          :isPrivate = "isPrivate"
          :fileKey.sync = "form.fileKey"
          :fileSize.sync = "form.fileSize"
          :videoUrl.sync="form.videoUrl"
          :fileName.sync="form.fileName"
          :line_1.sync="form.lineOne"
          :thumbnail.sync="form.thumbnail"
          :uploadType.sync="form.uploadType"
          :isTranscode.sync="form.isTranscode"
          :transcodeFileKey.sync="form.transcodeFileKey"
          @video-duration="handleVideoDuration"
          @change="handleVideoChange"
          ref="videoUpload"
          append-to-body
        />
        <el-form-item label="视频名称" prop="videoName">
          <el-input v-model="form.videoName" placeholder="请输入视频名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select
            v-model="form.category"
            placeholder="请选择分类"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="公司列表" prop="companyIds">
          <div style="margin-bottom: 10px;">
            <el-button size="mini" type="text" @click="selectAllCompanies">全选</el-button>
            <el-button size="mini" type="text" @click="unselectAllCompanies">全不选</el-button>
            <el-button size="mini" type="text" @click="reverseSelectCompanies">反选</el-button>
            <span style="margin-left: 20px; color: #909399; font-size: 12px;">
              已选择 {{ form.companyIds ? form.companyIds.length : 0 }} 个公司
            </span>
          </div>
          <el-select
            v-model="form.companyIds"
            multiple
            filterable
            placeholder="请选择公司"
            style="width: 100%"
            collapse-tags
            :loading="companyOptionsLoading"
          >
            <el-option
              v-for="company in allCompanyOptions"
              :key="company.companyId"
              :label="company.companyName"
              :value="company.companyId"
            />
          </el-select>
        </el-form-item>
      </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="修改视频信息" :visible.sync="editVideoInfoDialog" width="800px" append-to-body>
      <el-form ref="editVideoInfoForm" :model="editVideoInfoForm" label-width="120px">
        <el-form-item label="视频名称" prop="videoName">
          <el-input v-model="editVideoInfoForm.videoName" placeholder="请输入视频名称" />
        </el-form-item>
        <el-form-item label="分类" prop="category">
          <el-select
            v-model="editVideoInfoForm.category"
            placeholder="请选择分类"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="editVideoInfoForm.sort" :min="0" placeholder="请输入排序号" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="editVideoInfoForm.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditVideoInfo">确 定</el-button>
        <el-button @click="cancelEditVideoInfo">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 修改公司范围对话框 -->
    <el-dialog title="修改公司范围" :visible.sync="editCompanyIdsDialog" width="800px" append-to-body>
      <el-form ref="editCompanyIdsForm" :model="editCompanyIdsForm" label-width="120px">
        <el-form-item label="视频名称">
          <el-input v-model="editCompanyIdsForm.videoName" :disabled="true" />
        </el-form-item>

        <el-form-item label="公司列表" prop="companyIds">
          <div style="margin-bottom: 10px;">
            <el-button size="mini" type="text" @click="selectAllCompaniesForEdit">全选</el-button>
            <el-button size="mini" type="text" @click="unselectAllCompaniesForEdit">全不选</el-button>
            <el-button size="mini" type="text" @click="reverseSelectCompaniesForEdit">反选</el-button>
            <span style="margin-left: 20px; color: #909399; font-size: 12px;">
              已选择 {{ editCompanyIdsForm.companyIds ? editCompanyIdsForm.companyIds.length : 0 }} 个公司
            </span>
          </div>
          <el-select
            v-model="editCompanyIdsForm.companyIds"
            multiple
            filterable
            placeholder="请选择公司"
            style="width: 100%"
            collapse-tags
            :loading="companyOptionsLoading"
          >
            <el-option
              v-for="company in allCompanyOptions"
              :key="company.companyId"
              :label="company.companyName"
              :value="company.companyId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitEditCompanyIds">确 定</el-button>
        <el-button @click="cancelEditCompanyIds">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量修改分类对话框 -->
    <el-dialog title="批量修改分类" :visible.sync="batchUpdateCategoryDialog" width="500px" append-to-body>
      <el-form ref="batchUpdateCategoryForm" :model="batchUpdateCategoryForm" label-width="100px">
        <el-form-item label="分类" prop="category">
          <el-select
            v-model="batchUpdateCategoryForm.category"
            placeholder="请选择分类"
            filterable
            style="width: 100%"
          >
            <el-option
              v-for="item in categoryOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchUpdateCategory">确 定</el-button>
        <el-button @click="cancelBatchUpdateCategory">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 批量上传视频对话框 -->
    <el-dialog title="批量上传视频" :visible.sync="batchUploadDialog" width="900px" append-to-body>
      <div style="margin-bottom: 15px;">
        <el-upload
          ref="batchUpload"
          action="#"
          :http-request="handleBatchUploadRequest"
          accept=".mp4"
          :multiple="true"
          :auto-upload="false"
          :on-change="handleBatchFileChange"
          :on-remove="handleBatchFileRemove"
          :file-list="batchUploadFileList"
        >
          <el-button slot="trigger" size="small" type="primary">选择视频文件</el-button>
          <el-button style="margin-left: 10px;" size="small" type="success" @click="submitBatchUpload">开始上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传mp4文件，且每个文件不超过1G，可同时选择多个文件</div>
        </el-upload>
      </div>
      <div v-if="batchUploadVideos.length > 0" style="margin-top: 20px;">
        <div v-for="(video, index) in batchUploadVideos" :key="index" style="margin-bottom: 20px; border: 1px solid #e4e7ed; padding: 15px; border-radius: 4px;">
          <div style="margin-bottom: 10px; font-weight: bold;">{{ video.fileName }}</div>
          <div class="progress-container" style="width:100% !important;">
            <span class="progress-label">上传进度</span>
            <el-progress
              style="margin-top: 5px;"
              class="progress"
              :text-inside="true"
              :stroke-width="18"
              :percentage="video.progress"
              :status="video.status"
            ></el-progress>
          </div>
          <div v-if="video.status === 'success'" style="margin-top: 10px; color: #67c23a; font-size: 12px;">
            上传成功
          </div>
          <div v-else-if="video.status === 'exception'" style="margin-top: 10px; color: #f56c6c; font-size: 12px;">
            上传失败: {{ video.errorMsg || '未知错误' }}
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveBatchUploadVideos" :disabled="!canSaveBatchUpload">保 存</el-button>
        <el-button @click="cancelBatchUpload">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 重新上传视频对话框 -->
    <el-dialog title="重新上传视频" :visible.sync="reuploadVideoDialog" width="800px" append-to-body>
      <el-form ref="reuploadVideoForm" :model="reuploadVideoForm" label-width="120px">
        <el-form-item label="视频名称">
          <el-input v-model="reuploadVideoForm.videoName" :disabled="true" />
        </el-form-item>
        <live-video-upload
          :type="1"
          :isPrivate="isPrivate"
          :fileKey.sync="reuploadVideoForm.fileKey"
          :fileSize.sync="reuploadVideoForm.fileSize"
          :videoUrl.sync="reuploadVideoForm.videoUrl"
          :fileName.sync="reuploadVideoForm.fileName"
          :line_1.sync="reuploadVideoForm.lineOne"
          :thumbnail.sync="reuploadVideoForm.thumbnail"
          :uploadType.sync="reuploadVideoForm.uploadType"
          :isTranscode.sync="reuploadVideoForm.isTranscode"
          :transcodeFileKey.sync="reuploadVideoForm.transcodeFileKey"
          @video-duration="handleReuploadVideoDuration"
          @change="handleReuploadVideoChange"
          ref="reuploadVideoUpload"
          append-to-body
        />
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitReuploadVideo">确 定</el-button>
        <el-button @click="cancelReuploadVideo">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="视频播放"
      :visible.sync="videoPlayVisible"
      width="720px"
      append-to-body
      @closed="currentPlayUrl = ''"
    >
      <video
        v-if="currentPlayUrl"
        :src="currentPlayUrl"
        controls
        controlsList="nodownload"
        class="live-video-dialog-player"
        @contextmenu.prevent
      ></video>
    </el-dialog>

  </div>
</template>

<script>
import { listLiveVideo, getLiveVideo, delLiveVideo, addLiveVideo, updateLiveVideo, exportLiveVideo, batchUpdateCategory, updateVideoUrl, batchAddLiveVideo } from "@/api/live/liveVideo";
import { getCompanyList } from "@/api/company/company";
import LiveVideoUpload from "@/components/LiveVideoUpload/index.vue";
import { uploadObject } from "@/utils/cos.js";

export default {
  name: "LiveVideo",
  components: { LiveVideoUpload },
  data() {
    return {
      videoPlayVisible: false,
      currentPlayUrl: '',
      //字典
      videoTypeOptions: [],
      categoryOptions: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 直播视频表格数据
      liveVideoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        liveId: -1,
        videoUrl: null,
        videoType: -1,
        sort: null,
        videoName: null,
        remark: null,
        category: null,
        companyId: null,
      },
      // 表单参数
      form: {
        uploadType: 1,
        isTranscode:0,
        transcodeFileKey:null,
        companyIds: [],
        fileSize: null
      },
      // 表单校验
      rules: {
        category: [
          { required: true, message: "分类不能为空", trigger: "change" }
        ]
      },
      isPrivate:null,
      // 是否显示修改视频信息对话框
      editVideoInfoDialog: false,
      // 修改视频信息表单
      editVideoInfoForm: {
        videoId: null,
        videoName: '',
        category: '',
        sort: null,
        remark: ''
      },
      // 是否显示修改公司范围对话框
      editCompanyIdsDialog: false,
      // 修改公司范围表单
      editCompanyIdsForm: {
        videoId: null,
        videoName: '',
        companyIds: []
      },
      // 是否显示批量修改分类对话框
      batchUpdateCategoryDialog: false,
      // 批量修改分类表单
      batchUpdateCategoryForm: {
        category: ''
      },
      // 所有公司选项（用于下拉选择）
      allCompanyOptions: [],
      // 公司选项加载状态
      companyOptionsLoading: false,
      // 是否显示批量上传对话框
      batchUploadDialog: false,
      // 批量上传视频数据
      batchUploadVideos: [],
      // 批量上传文件列表
      batchUploadFileList: [],
      // 是否显示重新上传视频对话框
      reuploadVideoDialog: false,
      // 重新上传视频表单
      reuploadVideoForm: {
        videoId: null,
        videoName: '',
        videoUrl: '',
        fileKey: '',
        fileSize: null,
        fileName: '',
        lineOne: '',
        thumbnail: '',
        uploadType: 1,
        isTranscode: 0,
        transcodeFileKey: null
      }
    };
  },
  created() {
    this.getList();
    this.getAllCompanyOptions();
    this.getDicts("sys_live_video_category").then(response => {
      this.categoryOptions = response.data;
    });
  },
  mounted() {
    this.getAllCompanyOptions();
  },
  methods: {
    openVideoPlay(row) {
      if (!row || !row.videoUrl) {
        this.$message.warning('暂无视频地址');
        return;
      }
      this.currentPlayUrl = row.videoUrl;
      this.videoPlayVisible = true;
    },
    categoryFormatter(row, column) {
      return this.selectDictLabel(this.categoryOptions, row.category);
    },
    handleVideoDuration(duration) {
      this.form.duration = duration;
    },
    handleVideoChange(videoUrl,lineOne){
      this.videoUrl = videoUrl;
      this.form.videoUrl = videoUrl;
      console.log(this.videoUrl)
    },
    // 操作日志类型字典翻译
    formatDuration(row, column) {
      if(row.duration == null) return "00:00"
      const h = Math.floor(row.duration / 3600);
      const m = Math.floor((row.duration % 3600) / 60);
      const s = Math.floor(row.duration % 60);

      // 补零处理
      const format = (num) => num.toString().padStart(2, '0');

      return h > 0
        ? `${h}:${format(m)}:${format(s)}`
        : `${format(m)}:${format(s)}`;
    },
    formatFileSize(size) {
      if (!size) return "--";
      const mb = size / (1024 * 1024);
      return `${mb.toFixed(2)} MB`;
    },
    /** 查询直播视频列表 */
    getList() {
      this.loading = true;
      listLiveVideo(this.queryParams).then(response => {
        this.liveVideoList = response.rows;
        this.liveVideoList.forEach(item => {
          item.videoUrl = item.videoUrl.replace(".m3u8", ".mp4");
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    videoTypeFormatter(row, column) {
      return this.selectDictLabel(this.videoTypeOptions, row.status);
    },
    categoryFormatter(row, column) {
      return this.selectDictLabel(this.categoryOptions, row.category);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        videoId: null,
        liveId: null,
        videoUrl: null,
        videoType: null,
        videoName: null,
        category: null,
        sort: null,
        createTime: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        uploadType: 1,
        isTranscode: 0,
        transcodeFileKey: null,
        companyIds: [],
        fileSize: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        liveId: -1,
        videoUrl: null,
        videoType: -1,
        sort: null,
        videoName: null,
        remark: null,
        category: null,
        companyId: null,
      };
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.videoId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加直播视频";
      this.videoUrl = '';
      setTimeout(() => {
        this.$refs.videoUpload.reset();
      }, 500);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const videoId = row.videoId || this.ids
      getLiveVideo(videoId).then(response => {
        this.form = response.data;

        // 处理companyIds，可能是字符串或数组
        if (response.data.companyIds) {
          if (typeof response.data.companyIds === 'string') {
            this.form.companyIds = response.data.companyIds
              ? response.data.companyIds.split(',').map(Number)
              : [];
          } else if (Array.isArray(response.data.companyIds)) {
            this.form.companyIds = response.data.companyIds.map(Number);
          }
        } else {
          this.form.companyIds = [];
        }

        this.open = true;
        this.title = "修改直播视频";
      });
    },
    /** 获取所有公司选项 */
    getAllCompanyOptions() {
      this.companyOptionsLoading = true;
      getCompanyList().then(response => {
        if (response.code === 200 && response.data) {
          this.allCompanyOptions = response.data || [];
        } else {
          this.allCompanyOptions = [];
        }
        this.companyOptionsLoading = false;
      }).catch(() => {
        this.allCompanyOptions = [];
        this.companyOptionsLoading = false;
      });
    },
    /** 全选公司 */
    selectAllCompanies() {
      this.form.companyIds = this.allCompanyOptions.map(item => item.companyId);
    },
    /** 全不选公司 */
    unselectAllCompanies() {
      this.form.companyIds = [];
    },
    /** 反选公司 */
    reverseSelectCompanies() {
      const allIds = this.allCompanyOptions.map(item => item.companyId);
      const selectedIds = this.form.companyIds || [];
      this.form.companyIds = allIds.filter(id => !selectedIds.includes(id));
    },
    /** 全选公司（修改公司范围） */
    selectAllCompaniesForEdit() {
      this.editCompanyIdsForm.companyIds = this.allCompanyOptions.map(item => item.companyId);
    },
    /** 全不选公司（修改公司范围） */
    unselectAllCompaniesForEdit() {
      this.editCompanyIdsForm.companyIds = [];
    },
    /** 反选公司（修改公司范围） */
    reverseSelectCompaniesForEdit() {
      const allIds = this.allCompanyOptions.map(item => item.companyId);
      const selectedIds = this.editCompanyIdsForm.companyIds || [];
      this.editCompanyIdsForm.companyIds = allIds.filter(id => !selectedIds.includes(id));
    },
    /** 打开修改视频信息对话框 */
    handleUpdateVideoInfo(row) {
      const videoId = row.videoId;
      getLiveVideo(videoId).then(response => {
        if (response.code === 200) {
          this.editVideoInfoForm = {
            videoId: response.data.videoId,
            videoName: response.data.videoName || '',
            category: response.data.category || '',
            sort: response.data.sort || null,
            remark: response.data.remark || ''
          };
          this.editVideoInfoDialog = true;
        }
      }).catch(() => {
        this.msgError("获取数据失败");
      });
    },
    /** 取消修改视频信息 */
    cancelEditVideoInfo() {
      this.editVideoInfoDialog = false;
      this.editVideoInfoForm = {
        videoId: null,
        videoName: '',
        category: '',
        sort: null,
        remark: ''
      };
    },
    /** 提交修改视频信息 */
    submitEditVideoInfo() {
      const data = {
        videoId: this.editVideoInfoForm.videoId,
        videoName: this.editVideoInfoForm.videoName,
        category: this.editVideoInfoForm.category,
        sort: this.editVideoInfoForm.sort,
        remark: this.editVideoInfoForm.remark
      };

      updateLiveVideo(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess("修改成功");
          this.editVideoInfoDialog = false;
          this.getList();
        } else {
          this.msgError(response.msg || "修改失败");
        }
      }).catch(() => {
        this.msgError("修改失败");
      });
    },
    /** 打开修改公司范围对话框 */
    handleUpdateCompanyIds(row) {
      const videoId = row.videoId;
      getLiveVideo(videoId).then(response => {
        if (response.code === 200) {
          this.editCompanyIdsForm = {
            videoId: response.data.videoId,
            videoName: response.data.videoName || '',
            companyIds: []
          };

          // 处理companyIds，可能是字符串或数组
          if (response.data.companyIds) {
            if (typeof response.data.companyIds === 'string') {
              this.editCompanyIdsForm.companyIds = response.data.companyIds
                ? response.data.companyIds.split(',').map(Number)
                : [];
            } else if (Array.isArray(response.data.companyIds)) {
              this.editCompanyIdsForm.companyIds = response.data.companyIds.map(Number);
            }
          }

          this.editCompanyIdsDialog = true;
        }
      }).catch(() => {
        this.msgError("获取数据失败");
      });
    },
    /** 取消修改公司范围 */
    cancelEditCompanyIds() {
      this.editCompanyIdsDialog = false;
      this.editCompanyIdsForm = {
        videoId: null,
        videoName: '',
        companyIds: []
      };
    },
    /** 提交修改公司范围 */
    submitEditCompanyIds() {
      const data = {
        videoId: this.editCompanyIdsForm.videoId,
        companyIds: Array.isArray(this.editCompanyIdsForm.companyIds)
          ? this.editCompanyIdsForm.companyIds
          : []
      };

      updateLiveVideo(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess("修改成功");
          this.editCompanyIdsDialog = false;
          this.getList();
        } else {
          this.msgError(response.msg || "修改失败");
        }
      }).catch(() => {
        this.msgError("修改失败");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.videoType = -1;
          this.form.liveId = -1;
          if (!this.form.videoName) {
            this.form.videoName = this.form.fileName;
          }
          if (!this.form.remark) {
            this.form.remark = this.form.fileName;
          }
          if(this.form.videoUrl == null || this.form.videoUrl == "") {
            this.msgError("请上传视频");
            return;
          }
          this.form.videoUrl = this.form.videoUrl.replace('.mp4', '.m3u8');

          // 确保companyIds是数组
          const submitData = {
            ...this.form,
            companyIds: Array.isArray(this.form.companyIds) ? this.form.companyIds : []
          };

          if (this.form.videoId != null) {
            // 修改
            updateLiveVideo(submitData).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          } else {
            // 新增
            addLiveVideo(submitData).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
              this.reset();
            });
          }

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const videoIds = row.videoId || this.ids;
      this.$confirm('是否确认删除直播视频编号为"' + videoIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delLiveVideo(videoIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有直播视频数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportLiveVideo(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    },
    /** 批量修改分类 */
    handleBatchUpdateCategory() {
      if (this.ids.length === 0) {
        this.msgWarning("请选择要修改的视频");
        return;
      }
      this.batchUpdateCategoryForm.category = '';
      this.batchUpdateCategoryDialog = true;
    },
    /** 取消批量修改分类 */
    cancelBatchUpdateCategory() {
      this.batchUpdateCategoryDialog = false;
      this.batchUpdateCategoryForm.category = '';
    },
    /** 提交批量修改分类 */
    submitBatchUpdateCategory() {
      const data = {
        videoIds: this.ids,
        category: this.batchUpdateCategoryForm.category
      };

      batchUpdateCategory(data).then(response => {
        if (response.code === 200) {
          this.msgSuccess("批量修改成功");
          this.batchUpdateCategoryDialog = false;
          this.getList();
        } else {
          this.msgError(response.msg || "批量修改失败");
        }
      }).catch(() => {
        this.msgError("批量修改失败");
      });
    },
    /** 打开批量上传视频对话框 */
    handleBatchUpload() {
      this.batchUploadFileList = [];
      this.batchUploadVideos = [];
      this.batchUploadDialog = true;
    },
    /** 取消批量上传 */
    cancelBatchUpload() {
      this.batchUploadDialog = false;
      this.batchUploadFileList = [];
      this.batchUploadVideos = [];
      if (this.$refs.batchUpload) {
        this.$refs.batchUpload.clearFiles();
      }
    },
    /** 批量文件变化 */
    handleBatchFileChange(file, fileList) {
      const MAX_SIZE = 1024 * 1024 * 1024;
      if (file.raw && file.raw.size > MAX_SIZE) {
        this.$message.error(`${file.name} 文件大小不能超过1G`);
        // 从文件列表中移除
        const index = fileList.findIndex(f => f.uid === file.uid);
        if (index > -1) {
          fileList.splice(index, 1);
        }
        return;
      }
      this.batchUploadFileList = fileList;

      // 初始化上传数据
      const index = this.batchUploadVideos.length;
      this.batchUploadVideos.push({
        file: file.raw,
        fileName: file.name,
        fileSize: file.size,
        videoUrl: '',
        fileKey: '',
        duration: 0,
        progress: 0,
        status: '',
        errorMsg: ''
      });

      // 获取视频时长
      this.getBatchVideoDuration(file.raw, index);
    },
    /** 批量文件移除 */
    handleBatchFileRemove(file, fileList) {
      this.batchUploadFileList = fileList;
      const index = this.batchUploadVideos.findIndex(v => v.fileName === file.name);
      if (index > -1) {
        this.batchUploadVideos.splice(index, 1);
      }
    },
    /** 获取批量视频时长 */
    getBatchVideoDuration(file, index) {
      const video = document.createElement("video");
      video.preload = "metadata";
      video.onloadedmetadata = () => {
        window.URL.revokeObjectURL(video.src);
        const duration = parseInt(video.duration.toFixed(2));
        if (this.batchUploadVideos[index]) {
          this.batchUploadVideos[index].duration = duration;
        }
      };
      video.src = URL.createObjectURL(file);
    },
    /** 批量上传请求处理 */
    handleBatchUploadRequest(options) {
      // 这个方法不会被调用，因为我们使用auto-upload=false
    },
    /** 开始批量上传 */
    async submitBatchUpload() {
      if (this.batchUploadVideos.length === 0) {
        this.msgWarning("请先选择视频文件");
        return;
      }

      // 重置所有视频状态
      this.batchUploadVideos.forEach(video => {
        video.progress = 0;
        video.status = '';
        video.errorMsg = '';
      });

      // 逐个上传视频
      for (let i = 0; i < this.batchUploadVideos.length; i++) {
        const video = this.batchUploadVideos[i];
        try {
          video.status = '';
          video.progress = 0;

          // 上传到COS
          const updateProgress = (progressData) => {
            video.progress = Math.round(progressData.percent * 100);
          };

          const data = await uploadObject(video.file, updateProgress, 1);

          // 构建视频URL
          let line_1 = `${process.env.VUE_APP_VIDEO_LINE_1}${data.urlPath}`;
          line_1 = line_1.replace(/\.mp4$/, '.m3u8');

          video.videoUrl = line_1;
          video.fileKey = data.urlPath.substring(1);
          video.progress = 100;
          video.status = 'success';
        } catch (error) {
          console.error(`视频 ${video.fileName} 上传失败:`, error);
          video.status = 'exception';
          video.errorMsg = error.message || '上传失败';
        }
      }
    },
    /** 计算是否可以保存 */
    canSaveBatchUpload() {
      if (this.batchUploadVideos.length === 0) {
        return false;
      }
      // 检查是否所有视频都已上传成功
      return this.batchUploadVideos.every(video => video.status === 'success' && video.videoUrl);
    },
    /** 保存批量上传的视频 */
    saveBatchUploadVideos() {
      if (!this.canSaveBatchUpload) {
        this.msgWarning("请等待所有视频上传完成");
        return;
      }

      // 构建保存数据
      const videoList = this.batchUploadVideos.map(video => {
        return {
          videoUrl: video.videoUrl,
          videoName: video.fileName.replace(/\.[^/.]+$/, ""), // 去掉扩展名
          videoType: -1, // 视频库
          liveId: -1,
          fileSize: video.fileSize,
          duration: video.duration,
          finishStatus: 0
        };
      });

      // 调用批量新增接口
      batchAddLiveVideo(videoList).then(response => {
        if (response.code === 200) {
          this.msgSuccess("批量保存成功");
          this.batchUploadDialog = false;
          this.batchUploadFileList = [];
          this.batchUploadVideos = [];
          this.getList();
        } else {
          this.msgError(response.msg || "批量保存失败");
        }
      }).catch(() => {
        this.msgError("批量保存失败");
      });
    },
    /** 打开重新上传视频对话框 */
    handleReuploadVideo(row) {
      this.reuploadVideoForm = {
        videoId: row.videoId,
        videoName: row.videoName || '',
        videoUrl: '',
        fileKey: '',
        fileSize: null,
        fileName: '',
        lineOne: '',
        thumbnail: '',
        uploadType: 1,
        isTranscode: 0,
        transcodeFileKey: null,
        duration: 0
      };
      this.reuploadVideoDialog = true;
      // 重置上传组件
      this.$nextTick(() => {
        if (this.$refs.reuploadVideoUpload) {
          this.$refs.reuploadVideoUpload.reset();
        }
      });
    },
    /** 取消重新上传视频 */
    cancelReuploadVideo() {
      this.reuploadVideoDialog = false;
      this.reuploadVideoForm = {
        videoId: null,
        videoName: '',
        videoUrl: '',
        fileKey: '',
        fileSize: null,
        fileName: '',
        lineOne: '',
        thumbnail: '',
        uploadType: 1,
        isTranscode: 0,
        transcodeFileKey: null,
        duration: 0
      };
    },
    /** 重新上传视频时长回调 */
    handleReuploadVideoDuration(duration) {
      this.reuploadVideoForm.duration = duration;
    },
    /** 重新上传视频URL变化回调 */
    handleReuploadVideoChange(videoUrl) {
      this.reuploadVideoForm.videoUrl = videoUrl;
    },
    /** 提交重新上传视频 */
    submitReuploadVideo() {
      if (!this.reuploadVideoForm.videoUrl) {
        this.msgError("请上传视频");
        return;
      }

      const videoUrl = this.reuploadVideoForm.videoUrl.replace('.mp4', '.m3u8');
      updateVideoUrl({
        videoId: this.reuploadVideoForm.videoId,
        videoUrl: videoUrl
      }).then(response => {
        if (response.code === 200) {
          this.msgSuccess("上传成功");
          this.reuploadVideoDialog = false;
          this.getList();
          this.cancelReuploadVideo();
        } else {
          this.msgError(response.msg || "上传失败");
        }
      }).catch(() => {
        this.msgError("上传失败");
      });
    }
  }
};
</script>

<style scoped>
.video-player {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.progress-container {
  margin-bottom: 5px;
}

.progress-label {
  display: block;
  font-weight: bold;
  font-size: 13px;
  color: #303331;
}
</style>
