<template>
  <div class="app-container">
    <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:live:add']"
        >新增</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="直播名称" prop="liveName">
        <el-input
          v-model="queryParams.liveName"
          placeholder="请输入直播名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="直播状态" prop="liveStatus">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择直播状态"
          clearable
          size="small"
        >
          <el-option label="待直播" value="1"></el-option>
          <el-option label="直播中" value="2"></el-option>
          <el-option label="已结束" value="3"></el-option>
          <el-option label="直播回放中" value="4"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="公司名称" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名称"
          clearable
          size="small"
        />
      </el-form-item>
      <el-form-item label="直播类型" prop="liveType">
        <el-select
          v-model="queryParams.liveType"
          placeholder="请选择直播类型"
          clearable
          size="small"
        >
          <el-option label="直播" value="1"></el-option>
          <el-option label="录播" value="2"></el-option>
          <el-option label="直播回放" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTimeS">
        <el-date-picker
          v-model="queryParams.startTimeS"
          type="datetime"
          placeholder="选择起始时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="small"
        ></el-date-picker>
      </el-form-item>
      <!-- 开始时间-范围结束 -->
      <el-form-item label="结束时间" prop="endTimeE">
        <el-date-picker
          v-model="queryParams.endTimeE"
          type="datetime"
          placeholder="选择结束时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          size="small"
          :disabled="!queryParams.startTimeS"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="上下架" prop="isShow">
        <el-select
          v-model="queryParams.isShow"
          placeholder="请选择上下架状态"
          clearable
          size="small"
        >
          <el-option label="上架" value="1"></el-option>
          <el-option label="下架" value="2"></el-option>
        </el-select>
      </el-form-item>
      <!-- 审核状态 -->
      <el-form-item label="审核状态" prop="isAudit">
        <el-select
          v-model="queryParams.isAudit"
          placeholder="请选择审核状态"
          clearable
          size="small"
        >
          <el-option label="审核未通过" value="0"></el-option>
          <el-option label="审核通过" value="1"></el-option>
        </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-button icon="el-icon-download" size="mini" v-hasPermi="['live:live:export']" @click="handleExport">导出</el-button>
      </el-form-item>
    </el-form>
    <div class="selection-toolbar">
      <el-checkbox :indeterminate="isIndeterminate" v-model="allChecked" @change="toggleSelectAll">
        {{ multipleSelection.length > 0 ? `已选 ${multipleSelection.length} 条` : '选中本页' }}
      </el-checkbox>
      <el-button  plain size="mini" @click="handleShelf" v-hasPermi="['live:live:edit']">上架</el-button>
      <el-button  plain size="mini" @click="handleUnshelf" v-hasPermi="['live:live:edit']">下架</el-button>
      <el-button  plain size="mini" @click="handleDeleteSelected" v-hasPermi="['live:live:remove']">删除</el-button>
<!--      <el-dropdown>-->
<!--        <el-button plain size="mini">-->
<!--          更多操作<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>-->
<!--        </el-button>-->
<!--        <el-dropdown-menu slot="dropdown">-->
<!--          <el-dropdown-item>操作一</el-dropdown-item>-->
<!--          <el-dropdown-item>操作二</el-dropdown-item>-->
<!--        </el-dropdown-menu>-->
<!--      </el-dropdown>-->
    </div>
    <el-table ref="liveTable" v-loading="loading" :data="liveList"  @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="直播ID" align="center" prop="liveId" />
      <el-table-column label="直播封面" align="center" prop="liveImgUrl" width="180">
        <template slot-scope="scope">
          <el-image style="width: 90px;height: 90px;" :src="scope.row.liveImgUrl" mode="aspectFill" :preview-src-list="[scope.row.liveImgUrl]" />
        </template>
      </el-table-column>
      <el-table-column label="直播名称" align="center" prop="liveName" />
      <el-table-column label="显示类型" align="center" prop="showType">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.showType == 1">横屏</el-tag>
          <el-tag v-if="scope.row.showType == 2">竖屏</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="直播状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="warning" v-if="scope.row.status == 1">待直播</el-tag>
          <el-tag style="color:#3491FA;background-color:#E8F7FF;border-color: #E8F7FF;" v-if="scope.row.status == 2">直播中</el-tag>
          <el-tag type="info" v-if="scope.row.status == 3">已结束</el-tag>
          <el-tag style="color:#9B6DDA;background-color:#F5E8FF;border-color: #F5E8FF;" v-if="scope.row.status == 4">直播回放中</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="公司名称" align="center" prop="companyName" >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.companyName">{{ scope.row.companyName }}</el-tag>
          <el-tag v-else>总台</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="直播类型" align="center" prop="liveType">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.liveType == 1">直播</el-tag>
          <el-tag type="success" v-if="scope.row.liveType == 2">录播</el-tag>
          <el-tag v-if="scope.row.liveType == 3">直播回放</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180" />
      <el-table-column label="结束时间" align="center" prop="finishTime" width="180" />
      <el-table-column label="上下架" align="center" prop="isShow">
        <template slot-scope="scope">
         <el-tag v-if="scope.row.isShow == 1">上架</el-tag>
         <el-tag type="info" v-if="scope.row.isShow == 2">下架</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核状态" align="center" prop="isAudit">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.isAudit == 0">审核未通过</el-tag>
          <el-tag v-if="scope.row.isAudit == 1">审核通过</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.companyName != '总台' && scope.row.status != 2"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['live:live:edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.companyName == '总台'"
            size="mini"
            type="text"
            style="color: #00CC66"
            icon="el-icon-edit"
            @click="handleView(scope.row)"
            v-hasPermi="['live:live:edit']"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            @click="handleConfig(scope.row)"
            v-hasPermi="['live:config:list']"
          >配置</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-service"
            @click="handleManage(scope.row)"
            v-hasPermi="['live:console:list']"
          >进入直播间</el-button>
          <el-dropdown trigger="hover">
            <el-button size="mini" type="text" icon="el-icon-more">
              更多
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <!-- 结束按钮 -->
              <el-dropdown-item
                v-if="scope.row.status == 2 && scope.row.liveType == 1"
                @click.native="showLivingUrl(scope.row)"
                v-hasPermi="['live:live:query']"
              >
                <i class="el-icon-switch-button"></i> 推流码
              </el-dropdown-item>

              <!-- 去直播按钮 -->
              <el-dropdown-item
                v-if="scope.row.status != 2"
                @click.native="handleStart(scope.row)"
                v-hasPermi="['live:live:edit']"
              >
                <i class="el-icon-monitor"></i> 去直播
              </el-dropdown-item>

              <!-- 进入直播间按钮 -->
              <el-dropdown-item
                v-if="scope.row.status == 2"
                @click.native="handleEnded(scope.row)"
                v-hasPermi="['live:live:edit']"
              >
                <i class="el-icon-service"></i> 结束
              </el-dropdown-item>
              <el-dropdown-item
                @click.native="handleCopy(scope.row)"
                v-hasPermi="['live:live:edit']"
              >
                <i class="el-icon-service"></i> 复制直播间
              </el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.liveCodeUrl == null"
                @click.native="handleGenerateCode(scope.row)"
                v-hasPermi="['live:live:edit']"
              >
                <i class="el-icon-service"></i> 生成二维码
              </el-dropdown-item>
              <el-dropdown-item
                v-if="scope.row.liveCodeUrl != null"
                @click.native="handleCheckCode(scope.row)"
              >
                <i class="el-icon-service"></i> 查看二维码
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="直播二维码"
      :visible.sync="qrcodeDialogVisible"
    width="500px"
    :close-on-click-modal="true"
    :show-close="true"
    top="10vh"
    >
    <div class="qrcode-img-container">

      <img
        :src="currentQrcodeUrl"
        alt="直播二维码"
        class="qrcode-img"
        @error="handleImgError"
      >
    </div>
    </el-dialog>

    <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="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="直播名称" prop="liveName">
          <el-input v-model="form.liveName" placeholder="请输入直播名称" :disabled="isViewOnly"/>
        </el-form-item>
        <el-form-item label="显示类型" prop="showType">
          <el-radio-group v-model="form.showType" :disabled="isViewOnly">
            <el-radio :label="1">横屏</el-radio>
            <el-radio :label="2">竖屏</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="直播类型" prop="liveType">
          <el-radio-group v-model="form.liveType" :disabled="isViewOnly">
            <el-radio :label="1">直播</el-radio>
            <el-radio :label="2">录播</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        <el-form-item label="直播达人" prop="talentId">-->
<!--          <el-select filterable v-model="form.talentId" placeholder="请选择达人">-->
<!--            <el-option-->
<!--              v-for="item in talentList"-->
<!--              :key="item.talentId"-->
<!--              :label="item.nickName"-->
<!--              :value="item.talentId">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
        <el-form-item label="直播描述" prop="liveDesc">
          <Editor ref="myeditor" :height="300" @on-text-change="updateText"  />
          <!--          <Editor v-model="form.liveDesc" :height="300" placeholder="直播描述" />-->
        </el-form-item>
        <el-form-item label="录播视屏" prop="videoUrl" v-if="form.liveType == 2" >
          <video-upload :fileKey.sync="form.fileKey" :fileSize.sync="form.fileSize"
                        :videoUrl.sync="form.videoUrl" :fileName.sync="form.fileName" :line_1.sync="form.lineOne"
                        :uploadType.sync="form.uploadType" :isTranscode.sync="form.isTranscode"
                        :isViewOnly="isViewOnly"
                        ref="videoUpload"
                        :transcodeFileKey.sync="form.transcodeFileKey" @video-duration="handleVideoDuration"
                        @change="handleVideoChange"></video-upload>
        </el-form-item>
<!--        <video-upload-->
<!--          v-if="form.liveType == 2"-->
<!--          :type = "1"-->
<!--          :isPrivate = "isPrivate"-->
<!--          :fileKey.sync = "form.fileKey"-->
<!--          :fileSize.sync = "form.fileSize"-->
<!--          :videoUrl.sync="videoUrl"-->
<!--          :fileName.sync="form.fileName"-->
<!--          :line_2.sync="form.lineTwo"-->
<!--          :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="startTime">
          <el-date-picker size="small"
                          v-model="form.startTime"
                          @change="timeChange"
                          type="datetime"
                          :disabled="isViewOnly"
                          format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          :picker-options="{
                            timePickerOptions: {
                              selectableRange: '00:00:00 - 23:59:59',
                              format: 'HH:mm:ss'
                            }
                          }"
                          placeholder="选择开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="finishTime" v-loading="timeLoading">
          <el-date-picker size="small"
                          v-model="form.finishTime"
                          type="datetime"
                          :disabled="isViewOnly"
                          format="yyyy-MM-dd HH:mm:ss"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          :picker-options="{
                            timePickerOptions: {
                              selectableRange: '00:00:00 - 23:59:59',
                              format: 'HH:mm:ss'
                            }
                          }"
                          placeholder="视屏播放结束">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="直播封面" prop="liveImgUrl">
          <image-upload v-model="form.liveImgUrl" :limit="1" :disabled="isViewOnly"/>
        </el-form-item>
        <el-form-item label="上下架" prop="isShow">
          <el-radio-group v-model="form.isShow" :disabled="isViewOnly">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="2">下架</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" v-show="!isViewOnly">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="rtmpUrlVisible"
      width="30%"
    >
      <div>服务器地址：{{serverName}}</div>
      <div>推流码：{{livingCode}}</div>
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="rtmpUrlVisible = false">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listLive,
  getLive,
  delLive,
  addLive,
  updateLive,
  exportLive,
  selectCompanyTalent,
  handleShelfOrUn,
  handleDeleteSelected,
  finishLive,
  startLive, copyLive,generateCode
} from "@/api/live/live";
import Editor from '@/components/Editor/wang';
import user from '@/store/modules/user';
import VideoUpload from "@/components/VideoUpload/index.vue";

export default {
  name: "Live",
  components: { Editor,VideoUpload },
  data() {
    return {
      // 是否只读
      isViewOnly:false,
      baseUrl: process.env.VUE_APP_BASE_API,
      uploadUrl:process.env.VUE_APP_BASE_API+"/common/uploadOSS",
      isPrivate:null,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      timeLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 直播表格数据
      liveList: [],
      // 达人列表
      talentList: [{talentId:111,nickName:"测试达人"},{talentId:222,nickName:"测试达人2"}],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      liveDesc:null,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        liveName: null,
        liveDesc: null,
        showType: null,
        status: null,
        anchorId: null,
        startTimeS: null,
        endTimeE: null,
        liveType: null,
        startTime: null,
        finishTime: null,
        liveImgUrl: null,
        liveConfig: null,
        isShow: null,
        isDel: null,
        qwQrCode: null,
        rtmpUrl: null,
      },
      // 表单参数
      form: {
        uploadType: 1,
        isTranscode:0,
        transcodeFileKey:null,
        videoUrl: null,
        fileKey: null,
        fileName: null,
        fileSize: null,
        lineOne: null,
      },
      // 表单校验
      rules: {
        liveName: [
          { required: true, message: "不能为空", trigger: "burl" }
        ],
        showType: [
          { required: true, message: "不能为空", trigger: "burl" }
        ],
        liveType: [
          { required: true, message: "不能为空", trigger: "burl" }
        ],
        startTime: [
          { required: true, message: "不能为空", trigger: "burl" }
        ],
        liveImgUrl: [
          { required: true, message: "不能为空", trigger: "burl" }
        ],
        isShow: [
          { required: true, message: "不能为空", trigger: "change" }
        ],
        talentId: [
          { required: true, message: "不能为空", trigger: "change" }
        ]
      },
      multipleSelection: [],
      allChecked: false,
      isIndeterminate: false,
      rtmpUrlVisible:false,
      serverName: '',
      livingCode:'',
      videoUrl: "",
      qrcodeDialogVisible: false,  // 弹窗显示状态：默认隐藏
      currentQrcodeUrl: "",        // 当前要展示的二维码地址
      defaultImg: "https://via.placeholder.com/400x400?text=二维码加载失败"  // 占位图
    };
  },
  created() {
    this.getList();
  },
  watch: {
    'form.startTime': {
      handler(newVal) {
        // 1. 若 startTime 为空，直接返回（避免无效处理）
        if (!newVal) return;

        // 2. 将字符串时间转为 Date 对象（处理 "yyyy-MM-dd HH:mm:ss" 格式）
        const timeObj = new Date(newVal);
        // 兼容时间解析失败的情况（如格式错误）
        if (isNaN(timeObj.getTime())) return;

        // 3. 强制将秒数设为 1 并补零（即 01 秒）
        timeObj.setSeconds(1); // 固定秒数为 1
        const formattedSeconds = this.pad(timeObj.getSeconds()); // 补零为 "01"

        // 4. 重新拼接完整的时间字符串（保持原格式：yyyy-MM-dd HH:mm:ss）
        const year = timeObj.getFullYear();
        const month = this.pad(timeObj.getMonth() + 1); // 月份从 0 开始，需 +1
        const day = this.pad(timeObj.getDate());
        const hours = this.pad(timeObj.getHours());
        const minutes = this.pad(timeObj.getMinutes());

        // 5. 更新 form.startTime，完成格式强制修正
        this.form.startTime = `${year}-${month}-${day} ${hours}:${minutes}:${formattedSeconds}`;
      },
      immediate: true, // 初始化时立即执行一次（确保初始值也符合格式）
      deep: false // startTime 是字符串，无需深度监听
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1;
      if (!isLt1M) {
        this.$message.error('上传图片大小不能超过 1MB!');
      }
      return   isLt1M;
    },
    handleAvatarSuccess(res, file) {
      if(res.code==200){
        this.form.thumbnail=res.url;
        this.$forceUpdate()
      }
      else{
        this.msgError(res.msg);
      }
    },
    handleShelf(){
      if (this.multipleSelection.length > 0) {
        var liveList = []
          this.multipleSelection.forEach(item => {
            liveList.push(item.liveId);
          })
        handleShelfOrUn({"liveIds":liveList,"isShow":1}).then(res=>{
          if (res.code == 200) {
            this.getList();
            this.$refs.liveTable.clearSelection();
          } else {
            this.$message.error(res.msg);
          }
        })
      } else {
        this.$message.info("请选择上架直播！")
      }

    },
    handleUnshelf(){
      if (this.multipleSelection.length > 0) {
        var liveList = []
        this.multipleSelection.forEach(item => {
          console.log(typeof(item.liveId))
          console.log(item.liveId)
          liveList.push(item.liveId);
        })
        handleShelfOrUn({"liveIds":liveList,"isShow":2}).then(res=>{
          if (res.code == 200) {
            this.getList();
            this.$refs.liveTable.clearSelection();
          } else {
            this.$message.error(res.msg);
          }
        })
      } else {
        this.$message.info("请选择下架直播！")
      }
    },
    handleDeleteSelected(){
      if (this.multipleSelection.length > 0) {
        var liveList = []
        this.multipleSelection.forEach(item => {
          liveList.push(item.liveId);
        })
        handleDeleteSelected({"liveIds":liveList}).then(res=>{
          if (res.code == 200) {
            this.getList();
            this.$refs.liveTable.clearSelection();
          } else {
            this.$message.error(res.msg);
          }
        })
      } else {
        this.$message.info("请选择被删除的直播！")
      }
    },
    // 全选或取消全选
    toggleSelectAll(val) {
      this.checked = val; // 更新 checkbox 的状态
      if (val) {
        // 如果 checkbox 被选中，则全选
        this.toggleSelection(this.liveList);
      } else {
        // 如果 checkbox 被取消选中，则取消全选
        this.toggleSelection();
      }
    },
    toggleSelection(rows) {
      if (rows && !this.isIndeterminate) {
        rows.forEach(row => {
          this.$refs.liveTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.liveTable.clearSelection();
      }
    },
    // 多选框选中数据
    handleSelectionChange(val) {
      this.multipleSelection = val;
      // 根据选择项的数量更新 checkbox 的状态
      this.allChecked = val.length === this.liveList.length;
      this.isIndeterminate = val.length > 0 && val.length < this.liveList.length;
    },
    /** 查询直播列表 */
    getList() {
      this.loading = true;
      listLive(this.queryParams).then(response => {
        this.liveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleVideoDuration(duration) {
      this.form.duration = duration;
    },
    handleVideoChange(videoUrl,lineOne){
      this.videoUrl = videoUrl;
      this.form.videoUrl = videoUrl;
    },
    changeDuration(e){
      this.form.duration = e.duration;
      this.form.durationTime = e.time;
      this.$forceUpdate();
      this.timeChange();
    },
    timeChange(){
      if(!this.form.startTime) return;
      if(!this.form.duration) return;
      const startDateTime = new Date(this.form.startTime);
      // 将视频时长（秒）加到开始时间
      const endDateTime = new Date(startDateTime.getTime() + this.form.duration * 1000); // 毫秒为单位
      // 格式化为年月日 时分秒
      this.form.finishTime = this.formatDate(endDateTime);
      this.$forceUpdate();
    },
    // 将秒数转换为时分秒
    secondsToTime(seconds) {
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = Math.floor(seconds % 60);
      return `${this.pad(hours)}:${this.pad(minutes)}:${this.pad(secs)}`;
    },
    // 补零处理
    pad(number) {
      return number < 10 ? `0${number}` : number;
    },
    // 格式化日期为 年月日 时分秒
    formatDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        showType: 1,
        liveType: 2,
        isShow: 1,
        isTranscode:0,
        uploadType:1,
        transcodeFileKey:null
      };
      this.videoUrl = "";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.status = null;
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.isViewOnly = false
      this.reset();
      this.open = true;

      setTimeout(() => {
        this.$refs.myeditor.setText("");
        this.$refs.videoUpload.reset();
      }, 100);
      this.title = "添加直播间";
    },
    updateText(text){
      setTimeout(() => {
        if (this.isViewOnly) {
          this.$refs.myeditor.setText(this.liveDesc);
          this.form.liveDesc=this.liveDesc;
        } else {
          this.form.liveDesc=text;
        }
      }, 1);

    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isViewOnly = false
      this.reset();
      const liveId = row.liveId || this.ids
      getLive(liveId).then(response => {
        this.form = response.data;
        if(this.form.duration){
          this.form.durationTime = this.secondsToTime(this.form.duration)
        }
        this.liveDesc = this.form.liveDesc

        setTimeout(() => {
          if(this.form.liveDesc==null){
            this.$refs.myeditor.setText("");
          }else{
            this.$refs.myeditor.setText(this.form.liveDesc);
          }
          this.form.videoUrl = row.videoUrl
        }, 1);
        this.open = true;
        this.title = "修改直播间";
      });
    },
    /** 修改按钮操作 */
    handleView(row) {
      this.isViewOnly = true
      this.reset();
      const liveId = row.liveId || this.ids
      getLive(liveId).then(response => {
        this.form = response.data;
        if(this.form.duration){
          this.form.durationTime = this.secondsToTime(this.form.duration)
        }
        this.liveDesc = this.form.liveDesc

        setTimeout(() => {
          if(this.form.liveDesc==null){
            this.$refs.myeditor.setText("");
          }else{
            this.$refs.myeditor.setText(this.form.liveDesc);
          }
          this.form.videoUrl = row.videoUrl
        }, 1);
        this.open = true;
        this.title = "查看直播间";
      });
    },
    /** 提交按钮 */
    submitForm() {
      if(this.form.liveId != null) { this.videoUrl = this.form.videoUrl; }
      if(this.form.liveType==2 && this.videoUrl.length == 0) {return this.$message.error("请上传视频");}
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.videoUrl = this.videoUrl;
          if (this.form.liveId != null) {
            updateLive(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLive(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const liveIds = row.liveId || this.ids;
      this.$confirm('是否确认删除直播编号为"' + liveIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delLive(liveIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleConfig(row) {
      console.info(row)
      this.$router.push('/live/liveConfig/' + row.liveId)
    },
    handleManage(row) {
      this.$router.push('/live/liveConsole/' + row.liveId)
    },
    handleEnded(row){
      this.$confirm('是否确认关闭直播间?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        finishLive({"liveId":row.liveId}).then(response=>{this.getList()})
      }).catch(() => {});
    },
    handleCopy(row){
      this.$confirm('是否确认复制直播间?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.loading = true;
        copyLive({"liveId":row.liveId}).then(response=>{this.getList();this.loading = false;})
      }).catch(() => {});
    },
    handleGenerateCode(row){
      this.$confirm('是否确认生成直播间小程序二维码?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        generateCode({"liveId":row.liveId}).then(response=>{
          if(response.code == 200){
            row.liveCodeUrl = response.data.liveCodeUrl
          }
        })
      }).catch(() => {});
    },
    // 查看二维码图片
    handleCheckCode(row) {
      // 先校验图片地址是否存在
      if (!row.liveCodeUrl) {
        this.$message.warning("二维码图片地址不存在，请稍后重试");
        return;
      }
      // 赋值当前图片地址 + 打开弹窗
      this.currentQrcodeUrl = row.liveCodeUrl;
      this.qrcodeDialogVisible = true;
    },
    // 2. 图片加载失败：替换为占位图
    handleImgError(e) {
      e.target.src = this.defaultImg;
    },
    handleStart(row){
      if(row.isShow == 2){
        this.$message.error("直播间已下架")
        return
      }
      this.$confirm('是否确认开启直播间?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        startLive({"liveId":row.liveId}).then(response=>{this.getList()})
      }).catch(() => {});
    },
    showLivingUrl(row){
      this.serverName=''
      this.livingCode=''
      this.rtmpUrlVisible = true
      this.serverName = row.rtmpUrl.slice(0,row.rtmpUrl.lastIndexOf('/') + 1)
      this.livingCode = row.rtmpUrl.slice(row.rtmpUrl.lastIndexOf('/') + 1)
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有直播数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportLive(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.selection-toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  padding-left: 10px;
}

.selection-toolbar .el-checkbox {
  margin-right: 10px;
}

/* 调整 checkbox 内部输入框的对齐 */
.selection-toolbar .el-checkbox .el-checkbox__inner {
  top: 8px; /* 根据实际需求调整 */
}
/* 图片容器：居中 + 内边距 */
.qrcode-img-container {
  text-align: center;
  padding: 20px 0;
}

/* 图片样式：自适应弹窗宽度，避免溢出 */
.qrcode-img {
  max-width: 100%;    /* 最大宽度不超过容器 */
  max-height: 400px;  /* 最大高度限制，避免过高 */
  cursor: pointer;    /* 鼠标悬浮变指针，提示可点击 */
  transition: all 0.3s ease;  /* 过渡动画，hover 更流畅 */
}

/* 图片 hover 效果：轻微放大 */
.qrcode-img:hover {
  transform: scale(1.02);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);  /* 加阴影增强层次感 */
}

/* 底部提示文字样式 */
.qrcode-footer {
  text-align: center !important;  /* 覆盖 Element 默认样式，居中显示 */
}

.text-gray {
  color: #666;
  font-size: 12px;
}
</style>
