<template>
  <div class="app-container live-page">
    <div class="live-page__header">
      <div class="live-page__title-wrap">
        <h2 class="live-page__title">直播间</h2>
        <p class="live-page__desc">管理直播、录播与回放场次</p>
      </div>
      <div class="live-page__actions">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['live:live:add']"
        >新建直播间</el-button>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </div>
    </div>

    <div class="live-panel" v-show="showSearch">
      <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="72px" class="live-search-form">
        <el-form-item label="直播名称" prop="liveName">
          <el-input v-model="queryParams.liveName" placeholder="搜索名称" clearable size="small" />
        </el-form-item>
        <el-form-item label="直播ID" prop="liveId">
          <el-input v-model="queryParams.liveId" placeholder="直播ID" clearable size="small" />
        </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-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-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 class="live-search-form__ops">
          <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>

    <div class="live-panel live-panel--table">
      <div class="selection-toolbar">
        <el-checkbox :indeterminate="isIndeterminate" v-model="allChecked" @change="toggleSelectAll">
          {{ multipleSelection.length > 0 ? `已选 ${multipleSelection.length} 条` : '选中本页' }}
        </el-checkbox>
        <div class="selection-toolbar__btns">
          <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>
        </div>
      </div>
      <el-table
        ref="liveTable"
        v-loading="loading"
        :data="liveList"
        class="live-table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="48" align="center" />
        <el-table-column label="直播间" min-width="260">
          <template slot-scope="scope">
            <div class="live-cell">
              <el-image
                class="live-cell__cover"
                :src="scope.row.liveImgUrl"
                fit="cover"
                :preview-src-list="scope.row.liveImgUrl ? [scope.row.liveImgUrl] : []"
              >
                <div slot="error" class="live-cell__cover-empty">无封面</div>
              </el-image>
              <div class="live-cell__meta">
                <div class="live-cell__name" :title="scope.row.liveName">{{ scope.row.liveName }}</div>
                <div class="live-cell__sub">ID {{ scope.row.liveId }} · {{ scope.row.companyName || '总台' }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="110">
          <template slot-scope="scope">
            <span class="live-status" :class="'is-' + scope.row.status">
              <i class="live-status__dot"></i>
              <template v-if="scope.row.status == 1">待直播</template>
              <template v-else-if="scope.row.status == 2">直播中</template>
              <template v-else-if="scope.row.status == 3">已结束</template>
              <template v-else-if="scope.row.status == 4">回放中</template>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" width="90">
          <template slot-scope="scope">
            <span class="live-muted">
              <template v-if="scope.row.liveType == 1">直播</template>
              <template v-else-if="scope.row.liveType == 2">录播</template>
              <template v-else-if="scope.row.liveType == 3">回放</template>
            </span>
          </template>
        </el-table-column>
        <el-table-column label="画面" align="center" width="80">
          <template slot-scope="scope">
            <span class="live-muted">{{ scope.row.showType == 2 ? '竖屏' : '横屏' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="开始时间" align="center" prop="startTime" width="168" />
        <el-table-column label="结束时间" align="center" prop="finishTime" width="168" />
        <el-table-column label="上架" align="center" width="80">
          <template slot-scope="scope">
            <span :class="scope.row.isShow == 1 ? 'live-ok' : 'live-muted'">{{ scope.row.isShow == 1 ? '上架' : '下架' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核" align="center" width="96">
          <template slot-scope="scope">
            <span :class="scope.row.isAudit == 1 ? 'live-ok' : 'live-warn'">{{ scope.row.isAudit == 1 ? '已通过' : '未通过' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="left" width="220" fixed="right" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleUpdate(scope.row)" v-hasPermi="['live:live:edit']" v-if="scope.row.status != 2">修改</el-button>
            <el-button size="mini" type="text" @click="handleConfig(scope.row)" v-hasPermi="['live:config:list']">配置</el-button>
            <el-button size="mini" type="text" @click="handleManage(scope.row)" v-hasPermi="['live:console:list']">进入</el-button>
            <el-dropdown trigger="hover">
              <el-button size="mini" type="text">更多<i class="el-icon-arrow-down el-icon--right"></i></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)">推流码</el-dropdown-item>
                <el-dropdown-item v-if="scope.row.status != 2" @click.native="handleStart(scope.row)">去直播</el-dropdown-item>
                <el-dropdown-item v-if="scope.row.status == 2" @click.native="handleEnded(scope.row)">结束</el-dropdown-item>
                <el-dropdown-item @click.native="handleCopy(scope.row)">复制直播间</el-dropdown-item>
                <el-dropdown-item @click.native="handleAudit(scope.row)">审核</el-dropdown-item>
                <el-dropdown-item @click.native="handleClearCache(scope.row)">清理缓存</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <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="请输入直播名称" />
        </el-form-item>
        <el-form-item label="显示类型" prop="showType">
          <el-radio-group v-model="form.showType">
            <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">
            <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">-->
<!--          <file-upload v-model="form.videoUrl" :limit="1" :file-size="3" :file-type="['mp4']" />-->
<!--          <el-button @click="getVideoDuration" v-loading="timeLoading">读取视屏时长</el-button>-->
<!--          <p style="margin: 0;padding: 0;" v-loading="timeLoading">视屏时长：<span style="color: #ff4949;">{{form.durationTime}}</span></p>-->
<!--        </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"
                        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"
                          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"
                          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" />
        </el-form-item>
        <el-form-item label="上下架" prop="isShow">
          <el-radio-group v-model="form.isShow">
            <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">确 定</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,
  updateLiveIsAudit,
  handleShelfOrUn,
  handleDeleteSelected,
  finishLive, startLive,
  copyLive,clearLiveCache
} 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 {
      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,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        liveName: null,
        liveId: null,
        liveDesc: null,
        showType: null,
        status: null,
        anchorId: null,
        liveType: null,
        startTime: null,
        startTimeS: null,
        endTimeE: 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);
      }
    },
    handleVideoDuration(duration) {
      this.form.duration = duration;
    },
    handleVideoChange(videoUrl,lineOne){
      this.videoUrl = videoUrl;
      this.form.videoUrl = videoUrl;
    },

    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)
    },
    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;
      });
    },
    urlChange(url) {
      this.form.videoUrl = url;
      this.getVideoDuration();
    },
    getVideoDuration() {
      this.timeLoading = true;
      const videoElement = document.createElement('video');
      videoElement.src = this.form.videoUrl;
      videoElement.onloadedmetadata = () => {
        this.form.duration = Math.floor(videoElement.duration);  // 秒
        this.form.durationTime = this.secondsToTime(this.form.duration);
        this.timeChange();
        this.timeLoading = false;
      };
    },
    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,
        uploadType:1,
        isTranscode:0,
        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.reset();
      this.open = true;
      setTimeout(() => {
        this.$refs.myeditor.setText("");
        this.$refs.videoUpload.reset();
      }, 100);
      this.title = "添加直播间";
    },
    updateText(text){
      this.form.liveDesc=text
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const liveId = row.liveId || this.ids
      getLive(liveId).then(response => {
        this.form = response.data;
        this.videoUrl = this.form.videoUrl;
        if(this.form.duration){
          this.form.durationTime = this.secondsToTime(this.form.duration)
        }
        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)
    },
    // 查看二维码图片
    handleCheckCode(row) {
      // 先校验图片地址是否存在
      if (!row.liveCodeUrl) {
        this.$message.warning("二维码图片地址不存在，请稍后重试");
        return;
      }
      // 赋值当前图片地址 + 打开弹窗
      this.currentQrcodeUrl = row.liveCodeUrl;
      this.qrcodeDialogVisible = true;
    },
    // 2. 图片加载失败：替换为占位图
    handleImgError(e) {
      e.target.src = this.defaultImg;
    },
    handleAudit( row){
      this.$alert('是否审核通过？', '审核', {
        confirmButtonText: '同意',
        cancelButtonText: '不同意',
        showCancelButton: true, // 显示取消按钮（即“不同意”）
        distinguishCancelAndClose: true,
        type: 'warning',
        callback: action => {
          let isAudit;
          if(action === 'cancel') isAudit = 0;
          if(action === 'confirm') isAudit = 1;
          if("confirm" === action || "cancel" === action){
            updateLiveIsAudit( {"liveId" : row.liveId, "isAudit" : isAudit}).then(res => {
              console.log(res)
              console.log(res>0)
              if (res > 0) {
                this.getList()
                this.$message.success("审核成功")
              }else {
                this.$message.error(res.msg)
              }
            })
          }
        }
      });
    },
    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(() => {});
    },
    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(() => {});
    },
    /** 导出按钮操作 */
    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(() => {});
    }
    ,/** 清理缓存按钮操作 */
    handleClearCache(row) {
      this.$confirm("是否确认清理该直播间的缓存?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          clearLiveCache(row.liveId).then((response) => {
            if (response.code === 200) {
              this.msgSuccess("缓存清理成功");
            } else {
              this.msgError(response.msg || "缓存清理失败");
            }
          });
        })
        .catch(() => {});
    },
  }
};
</script>

<style scoped>
.live-page {
  --live-border: #e8eaed;
  --live-text: #1f2329;
  --live-sub: #8a919f;
  --live-accent: #1a6d5b;
  --live-soft: #f4f6f8;
}

.live-page__header {
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  gap: 16px;
  margin-bottom: 16px;
}

.live-page__title {
  margin: 0;
  font-size: 22px;
  font-weight: 600;
  color: var(--live-text);
  letter-spacing: 0.02em;
}

.live-page__desc {
  margin: 4px 0 0;
  font-size: 13px;
  color: var(--live-sub);
}

.live-page__actions {
  display: flex;
  align-items: center;
  gap: 8px;
}

.live-panel {
  background: #fff;
  border: 1px solid var(--live-border);
  border-radius: 10px;
  padding: 14px 16px 4px;
  margin-bottom: 14px;
}

.live-panel--table {
  padding: 12px 12px 4px;
}

.live-search-form .el-form-item {
  margin-bottom: 12px;
}

.live-search-form__ops {
  margin-left: 4px;
}

.selection-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 10px;
  padding: 2px 4px 8px;
  border-bottom: 1px solid var(--live-soft);
}

.selection-toolbar__btns {
  display: flex;
  gap: 8px;
}

.live-table ::v-deep .el-table__header th {
  background: var(--live-soft);
  color: #5c6470;
  font-weight: 500;
}

.live-table ::v-deep .el-table__row td {
  padding: 12px 0;
}

.live-cell {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}

.live-cell__cover {
  width: 56px;
  height: 74px;
  border-radius: 8px;
  flex-shrink: 0;
  background: var(--live-soft);
  overflow: hidden;
}

.live-cell__cover-empty {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: var(--live-sub);
  background: var(--live-soft);
}

.live-cell__meta {
  min-width: 0;
  text-align: left;
}

.live-cell__name {
  font-size: 14px;
  font-weight: 600;
  color: var(--live-text);
  line-height: 1.35;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.live-cell__sub {
  margin-top: 4px;
  font-size: 12px;
  color: var(--live-sub);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.live-status {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: var(--live-text);
}

.live-status__dot {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  background: #c0c4cc;
}

.live-status.is-1 .live-status__dot { background: #e6a23c; }
.live-status.is-2 .live-status__dot { background: #f56c6c; box-shadow: 0 0 0 3px rgba(245, 108, 108, 0.18); }
.live-status.is-3 .live-status__dot { background: #909399; }
.live-status.is-4 .live-status__dot { background: #409eff; }

.live-muted { color: var(--live-sub); font-size: 13px; }
.live-ok { color: var(--live-accent); font-size: 13px; }
.live-warn { color: #c45656; font-size: 13px; }

.qrcode-img-container {
  text-align: center;
  padding: 20px 0;
}

.qrcode-img {
  max-width: 100%;
  max-height: 400px;
}
</style>
