<template>
  <div class="app-container">
    <div class="live-layout">
      <!-- 左侧分组列表 -->
      <div class="live-left-panel">
        <div class="group-title">
          <span>直播间分组</span>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-plus"
            circle
            @click="handleAddGroup"
            v-hasPermi="['live:liveGroupType:add']"
          ></el-button>
        </div>
        <div class="group-list">
          <div
            class="group-item"
            :class="{ active: currentGroupId === null }"
            @click="selectGroup(null)"
          >全部</div>
          <div
            v-for="item in groupList"
            :key="item.id"
            class="group-item"
            :class="{ active: currentGroupId === item.id }"
            @click="selectGroup(item.id)"
          >{{ item.liveGroupType }}</div>
        </div>
      </div>
      <!-- 右侧内容区 -->
      <div class="live-right-panel">
    <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"
        />
      </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"
        ></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:operation']"
        >上架</el-button
      >
      <el-button
        plain
        size="mini"
        @click="handleUnshelf"
        v-hasPermi="['live:live:operation']"
        >下架</el-button
      >
      <el-button
        plain
        size="mini"
        @click="handleDeleteSelected"
        v-hasPermi="['live:live:operation']"
        >删除</el-button
      >
    </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"
        width="100"
      />
      <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 v-if="scope.row.status == 1">待直播</el-tag>
          <el-tag v-if="scope.row.status == 2">直播中</el-tag>
          <el-tag v-if="scope.row.status == 3">已结束</el-tag>
          <el-tag 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="danger" 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
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-if="scope.row.status != 2"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['live:live:edit', 'live:live:operation']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleSelect(scope.row)"
            v-hasPermi="['live:live:edit', 'live:live:operation']"
          >查看标签配置</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-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleClearCache(scope.row)"
            v-hasPermi="['live:live:edit']"
            >清理缓存</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)"
              >
                <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:operation']"
              >
                <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:operation']"
              >
                <i class="el-icon-service"></i> 结束
              </el-dropdown-item>
              <el-dropdown-item @click.native="handleCopy(scope.row)">
                <i class="el-icon-service"></i> 复制直播间
              </el-dropdown-item>
              <el-dropdown-item @click.native="handleAudit(scope.row)">
                <i class="el-icon-service"></i> 审核
              </el-dropdown-item>
<!--              <el-dropdown-item -->
<!--                @click.native="handleExportComments(scope.row)"-->
<!--                :disabled="exportingComments[scope.row.liveId]"-->
<!--                v-hasPermi="['live:liveMsg:export']"-->
<!--              >-->
<!--                <i class="el-icon-download"></i> 导出评论-->
<!--              </el-dropdown-item>-->
            </el-dropdown-menu>
          </el-dropdown>
          <!--          <el-button-->
          <!--            v-if="scope.row.status == 2"-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-switch-button"-->
          <!--            @click="handleEnded(scope.row)"-->
          <!--            v-hasPermi="['live:config:edit']"-->
          <!--          >结束</el-button>-->
        </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="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="90px">
        <el-form-item label="直播名称" prop="liveName">
          <el-input v-model="form.liveName" placeholder="请输入直播名称" />
        </el-form-item>
        <el-form-item label="直播间分组" prop="liveGroupType">
          <el-select
            v-model="form.liveGroupType"
            placeholder="请选择直播间分组"
            clearable
            size="small"
            style="width: 100%"
          >
            <el-option
              v-for="item in groupList"
              :key="item.id"
              :label="item.liveGroupType"
              :value="item.id"
            />
          </el-select>
        </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
              v-for="item in liveTypeDictList"
              :key="item.dictValue"
              :label="parseInt(item.dictValue)"
            >
              {{ item.dictLabel }}
            </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-item label="下单消息播报" prop="orderBroadcastEnabled">
          <el-switch
            v-model="form.orderBroadcastEnabled"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="可见范围" prop="visibleScope">
          <el-radio-group v-model="form.visibleScope">
            <el-radio :label="0">私域直播</el-radio>
            <el-radio :label="1">公域直播</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="直播马甲号" prop="vestId">
          <el-select v-model="form.vestId" filterable clearable placeholder="请选择马甲号" style="width:100%" @change="onVestChange">
            <el-option
              v-for="item in lifeVestOptions"
              :key="item.id"
              :label="item.nickName + '(' + item.id + ')'"
              :value="item.id"
            />
          </el-select>
          <div style="color:#909399;font-size:12px;line-height:1.4;margin-top:4px">公域直播必须绑定马甲号；私域可不选</div>
        </el-form-item>
        <el-form-item label="马甲号视频" prop="lifeVideoId" v-if="form.vestId && form.liveType == 2">
          <el-select
            v-model="form.lifeVideoId"
            filterable
            clearable
            placeholder="可选：选用该马甲的短视频（自动带入时长）"
            style="width:100%"
            @change="onLifeVideoSelect"
          >
            <el-option
              v-for="item in lifeVideoOptions"
              :key="item.videoId"
              :label="(item.title || item.fileName || ('视频'+item.videoId)) + (item.duration ? (' / ' + secondsToTime(item.duration)) : '')"
              :value="item.videoId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="直播标签配置" prop="liveTagList">
          <el-table
            :data="form.liveTagList"
            border
            style="width: 100%; margin-bottom: 10px"
          >
            <el-table-column label="序号" type="index" width="60" />
            <el-table-column label="公司" prop="tagName">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.companyId"
                  placeholder="请选择公司"
                  @change="selectCompanyChange(scope.row, scope.$index)"
                >
                  <el-option
                    v-for="item in comapnyDropList"
                    :key="item.companyId"
                    :label="item.companyName"
                    :value="item.companyId"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="所属企微主体" prop="corpId">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.corpId"
                  placeholder="请选择企微主体"
                >
                  <el-option
                    v-for="item in scope.row.corpDropList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="标记行为类型" prop="markType">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.markType"
                  placeholder="请选择标记行为类型"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="item in markTypeDropList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="配置标签" prop="tag">
               <template slot-scope="scope">
                  <div v-if="!!scope.row.qwTagName">
                    {{scope.row.qwTagName}}
                  </div>
                  <el-button
                      type="primary"
                      plain
                      size="mini"
                      @click="addUserTag(scope.row,scope.$index)"

                  >选择标签</el-button>
               </template>
<!--              v-hasPermi="['qw:externalContact:addTag']"-->
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDeleteRow(scope.$index)"
                  size="small"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 新增行按钮 -->
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="handleAddRow"
          >
            新增标签
          </el-button>
        </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="selectTitle" :visible.sync="selectOpen" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="直播标签配置" prop="liveTagList">
          <el-table
            :data="form.liveTagList"
            border
            style="width: 100%; margin-bottom: 10px"
          >
            <el-table-column label="序号" type="index" width="60" />
            <el-table-column label="公司" prop="tagName">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.companyId"
                  placeholder="请选择公司"
                  @change="selectCompanyChange(scope.row, scope.$index)"
                >
                  <el-option
                    v-for="item in comapnyDropList"
                    :key="item.companyId"
                    :label="item.companyName"
                    :value="item.companyId"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="所属企微主体" prop="corpId">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.corpId"
                  placeholder="请选择企微主体"
                >
                  <el-option
                    v-for="item in scope.row.corpDropList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="标记行为类型" prop="markType">
              <template slot-scope="scope">
                <el-select
                  v-model="scope.row.markType"
                  placeholder="请选择标记行为类型"
                  clearable
                  size="small"
                >
                  <el-option
                    v-for="item in markTypeDropList"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue"
                  />
                </el-select>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
    </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>

    <el-dialog title="添加标签" :visible.sync="tagOpen" width="800px" append-to-body>
      <div>搜索标签：
        <el-input v-model="tagChange.tagName" placeholder="请输入标签名称" clearable size="small" style="width: 200px;margin-right: 10px" />
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleSearchTags(tagChange.tagName)">搜索</el-button>
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="cancelSearchTags">重置</el-button>
      </div>
      <el-form ref="form" :model="addTagFormByWatch"  label-width="80px">
        <div v-for="item in tagGroupList" :key="item.id" >
          <div style="font-size: 20px;margin-top: 20px;margin-bottom: 20px;">
            <span class="name-background">{{ item.name }}</span>
          </div>
          <!-- 添加外层滚动容器 -->
          <div class="scroll-wrapper">
            <div class="tag-container">
              <a
                v-for="tagItem in item.tag"
                class="tag-box"
                @click="tagSelection(tagItem)"
                :class="{ 'tag-selected': tagItem.isSelected }"
              >
                {{ tagItem.name }} 【{{tagItem.corpName}}】
              </a>
            </div>
          </div>
        </div>
      </el-form>
      <pagination
        v-show="tagTotal>0"
        :total="tagTotal"
        :page.sync="queryTagParams.pageNum"
        :limit.sync="queryTagParams.pageSize"
        @pagination="getPageListTagGroup"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addTagSubmitForm()">确 定</el-button>
        <el-button @click="addTagCancel">取 消</el-button>
      </div>
    </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import {
  listLive,
  getLive,
  delLive,
  addLive,
  updateLive,
  exportLive,
  selectCompanyTalent,
  updateLiveIsAudit,
  handleShelfOrUn,
  handleDeleteSelected,
  finishLive,
  startLive,
  copyLive,
  getCompanyDropList,
  getQwCorpList,
  getTagsListByCorpId,
  clearLiveCache,
} from "@/api/live/live";
import { exportLiveMsgComments } from "@/api/live/liveMsg";
import { listLiveGroupType, addLiveGroupType } from "@/api/live/liveGroupType";
import { listLifeVest } from "@/api/life/vest";
import { listLifeVideo } from "@/api/life/video";
import Editor from "@/components/Editor/wang";
import user from "@/store/modules/user";
import VideoUpload from "@/components/LiveVideoUpload/single.vue";

export default {
  name: "Live",
  components: { Editor, VideoUpload },
  data() {
    return {
      liveTypeDictList: [],
      // 直播间分组列表
      groupList: [],
      // 当前选中的分组ID，null表示全部
      currentGroupId: null,
      currentCheck:null,
      currentCheckTagIndex:null,
      lastCheckTagRow:null,
      addTagFormByWatch:{
        logId:[],
        tagIds:[]
      },
      tagGroupList: [],
      tagTotal:0,
      //标签弹窗选择
      tagChange:{
        open:false,
        index:null,
      },
      tagOpen: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: "",
      selectTitle: "",
      // 是否显示弹出层
      open: false,
      selectOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        liveName: null,
        liveDesc: null,
        showType: null,
        status: null,
        anchorId: null,
        liveType: null,
        liveGroupType: 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,
        liveTagList: [],
        liveGroupType: null,
      },
      liveTagItemBase: {
        companyId: null,
        corpId: null,
        markType: null,
        qwTagId: null,
        qwTagRealId:null,
        qwTagName: null,
        corpDropList: [],
      },
      // 表单校验
      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=二维码加载失败", // 占位图
      comapnyDropList: [],
      markTypeDropList: [],
      lifeVestOptions: [],
      lifeVideoOptions: [],
      queryTagParams:{
        pageNum: 1,
        pageSize: 5,
        total:0,
        name:null,
        corpId:null,
      },
      // 导出评论状态：key为liveId，value为是否正在导出
      exportingComments: {},
    };
  },
  created() {
    this.getList();
    this.getGroupList();
    this.initCompanyDropList();
    this.loadLifeVestOptions();
    this.getDicts("live_mark_type").then((response) => {
      this.markTypeDropList = response.data;
    });
    // 新增：获取直播类型字典
    this.getDicts("live_type").then((response) => {
      this.liveTypeDictList = response.data;
    });
  },
  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: {
    getQwCorpListByCompanyId(companyId) {
      getQwCorpList(companyId)
        .then((res) => {
          return res.data;
        })
        .catch((res) => {
        });
    },
    initCompanyDropList() {
      getCompanyDropList()
        .then((res) => {
          this.comapnyDropList = res.data;
        })
        .catch((res) => {
        });
    },
    /**
     * 新增标签行
     */
    handleAddRow() {
      var addItem = JSON.parse(JSON.stringify(this.liveTagItemBase));
      this.form.liveTagList.push(addItem);
    },
    handleDeleteRow(index) {
      if (!Array.isArray(this.form.liveTagList)) {
        this.form.liveTagList = [];
        this.$message.warning("暂无标签配置可删除");
        return;
      }
      // if (this.form.liveTagList.length <= 1) {
      //   this.$message.warning('至少保留一个标签配置');
      //   return;
      // }
      this.form.liveTagList.splice(index, 1);
    },
    //直播弹窗选择公司
    selectCompanyChange(row, index) {
      // console.log(row);
      if (!!row.companyId) {
        getQwCorpList(row.companyId)
          .then((res) => {
            row.corpDropList = res.data;
            this.$set(this.form.liveTagList, index, row);
          })
          .catch((res) => {
          });
      }
    },
    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) => {
          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;
      });
    },
    /** 获取直播间分组列表 */
    getGroupList() {
      listLiveGroupType({ pageNum: 1, pageSize: 999 }).then((response) => {
        this.groupList = response.rows;
      });
    },
    /** 选择分组 */
    selectGroup(groupId) {
      this.currentGroupId = groupId;
      this.queryParams.liveGroupType = groupId;
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 新增分组 */
    handleAddGroup() {
      this.$prompt('请输入直播间分组名称', '新增分组', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '分组名称不能为空'
      }).then(({ value }) => {
        addLiveGroupType({ liveGroupType: value }).then(() => {
          this.msgSuccess('新增成功');
          this.getGroupList();
        });
      }).catch(() => {});
    },
    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,
        orderBroadcastEnabled: 1,
        uploadType: 1,
        isTranscode: 0,
        transcodeFileKey: null,
        liveTagList: [],
        liveGroupType: null,
        visibleScope: 0,
        vestId: null,
        lifeVideoId: null,
      };
      this.videoUrl = "";
      this.lifeVideoOptions = [];
      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);
        }
        if (this.form.vestId) {
          this.loadLifeVideoOptions(this.form.vestId);
        }
        //初始化
        if (
          this.form.liveTagList == undefined ||
          this.form.liveTagList == null
        ) {
          this.form.liveTagList = [];
        }else{
          for(let index =0 ;index<this.form.liveTagList.length;index ++){
            this.form.liveTagList[index].markType = this.form.liveTagList[index].markType +"";
            this.selectCompanyChange(this.form.liveTagList[index],index);
          }
        }
        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 = "修改直播间";
      });
    },

    /**
    * 查询标签设置
    */
    handleSelect(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);
        }
        if (this.form.vestId) {
          this.loadLifeVideoOptions(this.form.vestId);
        }
        //初始化
        if (
          this.form.liveTagList == undefined ||
          this.form.liveTagList == null
        ) {
          this.form.liveTagList = [];
        }else{
          for(let index =0 ;index<this.form.liveTagList.length;index ++){
            this.form.liveTagList[index].markType = this.form.liveTagList[index].markType +"";
            this.selectCompanyChange(this.form.liveTagList[index],index);
          }
        }
        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.selectOpen = true;
        this.selectTitle = "查看标签配置";
      });
    },

    /** 提交按钮 */
    submitForm() {
      if (this.form.liveId != null) {
        this.videoUrl = this.form.videoUrl;
      }
      if (this.form.liveType == 2 && this.videoUrl.length == 0) {
        return this.$message.error("请上传视频");
      }
      if (this.form.visibleScope === 1 && !this.form.vestId) {
        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();
            });
          }
        }
      });
    },
    loadLifeVestOptions() {
      listLifeVest({ pageNum: 1, pageSize: 500 }).then((res) => {
        this.lifeVestOptions = res.rows || [];
      }).catch(() => {
        this.lifeVestOptions = [];
      });
    },
    onVestChange(vestId) {
      this.form.lifeVideoId = null;
      this.lifeVideoOptions = [];
      if (vestId) {
        this.loadLifeVideoOptions(vestId);
      }
    },
    loadLifeVideoOptions(vestId) {
      if (!vestId) {
        this.lifeVideoOptions = [];
        return;
      }
      listLifeVideo({ pageNum: 1, pageSize: 200, vestId, isShow: 1 }).then((res) => {
        this.lifeVideoOptions = res.rows || [];
      }).catch(() => {
        this.lifeVideoOptions = [];
      });
    },
    onLifeVideoSelect(lifeVideoId) {
      if (!lifeVideoId) {
        return;
      }
      const video = (this.lifeVideoOptions || []).find((v) => v.videoId === lifeVideoId);
      if (!video) {
        return;
      }
      this.form.videoUrl = video.videoUrl;
      this.videoUrl = video.videoUrl || "";
      this.form.fileName = video.fileName;
      if (video.duration) {
        this.form.duration = Number(video.duration);
        this.form.durationTime = this.secondsToTime(this.form.duration);
        this.timeChange();
      }
      if (!this.form.liveImgUrl && video.coverUrl) {
        this.form.liveImgUrl = video.coverUrl;
      }
    },
    /** 删除按钮操作 */
    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) {
      this.$router.push("/live/liveConfig/" + row.liveId);
    },
    handleManage(row) {
      const routeUrl = this.$router.resolve({
        path: `/live/liveConsole/` + row.liveId,
      }).href;
      window.open(routeUrl, "_blank");
    },
    // 查看二维码图片
    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) => {
                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(() => {});
    },
    /** 清理缓存按钮操作 */
    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(() => {});
    },
    /** 导出按钮操作 */
    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(() => {});
    },
    handleSearchTags(name){
      if (!name){
        return this.$message.error("请输入要搜索的标签")
      }
      this.queryTagParams.name = name;
      this.queryTagParams.pageNum = 1;
      this.queryTagParams.corpId = this.resolveCurrentTagCorpId();
      this.fetchTagGroupList();
    },
    /** 当前标签行企微主体 */
    resolveCurrentTagCorpId() {
      const row = Array.isArray(this.form.liveTagList) && this.currentCheckTagIndex != null
        ? this.form.liveTagList[this.currentCheckTagIndex]
        : null;
      if (row && row.corpId) {
        return row.corpId;
      }
      return this.queryTagParams.corpId || null;
    },
    resetSearchQueryTag() {
      this.tagChange.tagName = null;
      this.queryTagParams.name = null;
      this.queryTagParams.pageNum = 1;
      if (!this.queryTagParams.pageSize) {
        this.queryTagParams.pageSize = 5;
      }
      this.queryTagParams.corpId = this.resolveCurrentTagCorpId();
    },
    fetchTagGroupList() {
      if (!this.queryTagParams.corpId) {
        this.tagGroupList = [];
        this.tagTotal = 0;
        return;
      }
      if (!this.queryTagParams.pageNum) {
        this.queryTagParams.pageNum = 1;
      }
      if (!this.queryTagParams.pageSize) {
        this.queryTagParams.pageSize = 5;
      }
      const params = {
        corpId: this.queryTagParams.corpId,
        pageNum: this.queryTagParams.pageNum,
        pageSize: this.queryTagParams.pageSize,
        name: this.queryTagParams.name || null
      };
      getTagsListByCorpId(params).then(response => {
        this.tagGroupList = response.rows || [];
        this.tagTotal = response.total || 0;
      });
    },
    // 查询标签：入参可能是 corpId 字符串，也可能是分页组件回调 {page, limit}
    getPageListTagGroup(arg) {
      if (arg != null && (typeof arg === 'string' || typeof arg === 'number')) {
        this.queryTagParams.corpId = arg;
        this.queryTagParams.pageNum = 1;
        if (!this.queryTagParams.pageSize) {
          this.queryTagParams.pageSize = 5;
        }
        this.queryTagParams.name = null;
        this.tagChange.tagName = null;
      } else {
        // 分页组件 .sync 已写回 pageNum/pageSize，这里只保留 corpId，勿把 {page,limit} 赋给 corpId
        this.queryTagParams.corpId = this.resolveCurrentTagCorpId();
      }
      this.fetchTagGroupList();
    },
    addUserTag(row,index){
      if(row.companyId==null||row.companyId==""){
        return  this.$message('请选择公司');
      }
      if(row.corpId==null||row.corpId==""){
        return  this.$message('请选择企微主体');
      }
      this.currentCheck= null;
      this.lastCheckTagRow= null;
      this.currentCheckTagIndex = index;
      this.queryTagParams = {
        pageNum: 1,
        pageSize: this.queryTagParams.pageSize || 5,
        total: 0,
        name: null,
        corpId: row.corpId
      };
      this.tagChange.tagName = null;
      this.tagOpen = true;
      this.getPageListTagGroup(row.corpId);
      setTimeout(() => {
        for (let i = 0; i < this.tagGroupList.length; i++) {
          for (let x = 0; x < this.tagGroupList[i].tag.length; x++) {
            this.tagGroupList[i].tag[x].isSelected=false;
          }
        }
      }, 200);
    },
    cancelSearchTags(){
      this.resetSearchQueryTag();
      this.fetchTagGroupList();
    },
    addTagCancel() {
      this.tagOpen = false;
      this.currentCheck= null;
      this.lastCheckTagRow= null;
      this.addTagFormByWatch={
        logIds:[],
        tagIds:[]
      };
    },
    tagSelection(row){
      if(!!this.lastCheckTagRow){
        this.lastCheckTagRow.isSelected= !this.lastCheckTagRow.isSelected;
      }
      row.isSelected= !row.isSelected;
      this.lastCheckTagRow = row;
      this.currentCheck = row;
      this.$forceUpdate();
    },
    //点击确认
    addTagSubmitForm(){
      this.$set(this.form.liveTagList[this.currentCheckTagIndex], "qwTagName", this.currentCheck.name);
      this.$set(this.form.liveTagList[this.currentCheckTagIndex], "qwTagId", this.currentCheck.id);
      this.$set(this.form.liveTagList[this.currentCheckTagIndex], "qwTagRealId", this.currentCheck.tagId);
      this.tagOpen = false;
      this.lastCheckTagRow = null;
      this.currentCheck = null;
      this.currentCheckTagIndex = null;
    },
    /** 导出评论按钮操作 */
    handleExportComments(row) {
      const liveId = row.liveId;
      // 检查是否正在导出
      if (this.exportingComments[liveId]) {
        this.$message.warning("正在导出中，请勿重复操作");
        return;
      }

      // 检查是否有其他直播间正在导出
      const hasExporting = Object.values(this.exportingComments).some(status => status === true);
      if (hasExporting) {
        this.$message.warning("当前已有导出任务进行中，请等待完成后再试");
        return;
      }

      this.$confirm('是否确认导出该直播间的评论数据?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info"
      }).then(() => {
        // 设置导出状态
        this.$set(this.exportingComments, liveId, true);

        exportLiveMsgComments(liveId).then(response => {
          // 创建blob对象
          const blob = new Blob([response], { type: 'application/vnd.ms-excel' });
          // 创建下载链接
          const url = window.URL.createObjectURL(blob);
          const link = document.createElement('a');
          link.href = url;
          link.setAttribute('download', `直播评论_${row.liveName || liveId}_${new Date().getTime()}.xlsx`);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          window.URL.revokeObjectURL(url);

          this.$message.success("导出成功");
        }).catch(error => {
          this.$message.error(error.msg || "导出失败");
        }).finally(() => {
          // 清除导出状态
          this.$set(this.exportingComments, liveId, false);
        });
      }).catch(() => {});
    }

  },
};
</script>

<style scoped>
.app-container {
  position: relative;
  height: calc(100vh - 150px);
  overflow: hidden;
  box-sizing: border-box;
}
.live-layout {
  position: absolute;
  top: 20px;
  left: 20px;
  right: 20px;
  bottom: 20px;
  display: flex;
}
.live-left-panel {
  width: 200px;
  min-width: 200px;
  background: #fff;
  border-right: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
}
.group-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;
  font-weight: bold;
  padding: 16px 16px 12px;
  border-bottom: 1px solid #e8e8e8;
  flex-shrink: 0;
}
.group-list {
  padding: 8px 8px 0;
  overflow-y: auto;
  flex: 1;
}
.group-item {
  padding: 10px 12px;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
  color: #333;
  transition: all 0.2s;
}
.group-item:hover {
  background: #f0f2f5;
}
.group-item.active {
  background: #e6f7ff;
  color: #1890ff;
  font-weight: bold;
}
.live-right-panel {
  flex: 1;
  padding-left: 16px;
  min-width: 0;
  overflow-y: auto;
  overflow-x: hidden;
}
.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; /* 根据实际需求调整 */
}
.tag-box {
  padding: 8px 12px;
  border: 1px solid #989797;
  border-radius: 4px;
  cursor: pointer;
  display: inline-block;
}

.name-background {
  display: inline-block;
  background-color: #abece6; /* 背景颜色 */
  padding: 4px 8px; /* 调整内边距，让背景包裹文字 */
  border-radius: 4px; /* 可选：设置圆角 */
}
.tag-container {
  display: flex;
  flex-wrap: wrap; /* 超出宽度时自动换行 */
  gap: 8px; /* 设置标签之间的间距 */
}

/* 新增的滚动容器样式（不影响原有样式） */
.scroll-wrapper {
  max-height: 130px; /* 大约三行的高度 */
  overflow-y: auto;  /* 垂直滚动 */
  padding-right: 5px; /* 为滚动条留出空间 */
}

/* 美化滚动条（可选） */
.scroll-wrapper::-webkit-scrollbar {
  width: 6px;
}
.scroll-wrapper::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}
.tag-selected {
  background-color: #00bc98;
  color: #fff;
  border-color: #00bc98;
}
</style>
