<template>
  <div class="el-container-md">
    <!-- 数据统计指标展示区域 -->
    <el-card class="statistics-card" shadow="never">
      <el-row :gutter="20">
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">累计观看人数</div>
            <div class="statistics-value">{{ statisticsData.totalViewers || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">
              累计完课人数
              <el-popover placement="top" width="200" trigger="click">
                <div>
                  <el-input-number v-model="completeWatchTime" :min="0" :precision="0" placeholder="看课时长(分钟)" style="width: 100%;"></el-input-number>
                  <el-button type="primary" size="mini" style="width: 100%; margin-top: 10px;" @click="updateCompleteWatchTime('total')">确定</el-button>
                </div>
                <el-button slot="reference" size="mini" type="text" icon="el-icon-setting" style="margin-left: 5px;">设置</el-button>
              </el-popover>
            </div>
            <div class="statistics-value">{{ statisticsData.totalCompletedCourses || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">直播观看人数</div>
            <div class="statistics-value">{{ statisticsData.liveViewers || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">
              直播完课人数
              <el-popover placement="top" width="200" trigger="click">
                <div>
                  <el-input-number v-model="liveCompleteWatchTime" :min="0" :precision="0" placeholder="看课时长(分钟)" style="width: 100%;"></el-input-number>
                  <el-button type="primary" size="mini" style="width: 100%; margin-top: 10px;" @click="updateCompleteWatchTime('live')">确定</el-button>
                </div>
                <el-button slot="reference" size="mini" type="text" icon="el-icon-setting" style="margin-left: 5px;">设置</el-button>
              </el-popover>
            </div>
            <div class="statistics-value">{{ statisticsData.liveCompletedCourses || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">回放观看人数</div>
            <div class="statistics-value">{{ statisticsData.playbackViewers || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">
              回放完课人数
              <el-popover placement="top" width="200" trigger="click">
                <div>
                  <el-input-number v-model="replayCompleteWatchTime" :min="0" :precision="0" placeholder="看课时长(分钟)" style="width: 100%;"></el-input-number>
                  <el-button type="primary" size="mini" style="width: 100%; margin-top: 10px;" @click="updateCompleteWatchTime('replay')">确定</el-button>
                </div>
                <el-button slot="reference" size="mini" type="text" icon="el-icon-setting" style="margin-left: 5px;">设置</el-button>
              </el-popover>
            </div>
            <div class="statistics-value">{{ statisticsData.playbackCompletedCourses || 0 }}</div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">直播峰值</div>
            <div class="statistics-value">{{ statisticsData.livePeak || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">直播平均时长</div>
            <div class="statistics-value">{{ formatDuration(statisticsData.liveAvgDuration) }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">回放平均时长</div>
            <div class="statistics-value">{{ formatDuration(statisticsData.playbackAvgDuration) }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">GMV</div>
            <div class="statistics-value">¥{{ statisticsData.gmv || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">付费人数</div>
            <div class="statistics-value">{{ statisticsData.paidUsers || 0 }}</div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">付费单数</div>
            <div class="statistics-value">{{ statisticsData.paidOrders || 0 }}</div>
          </div>
        </el-col>
      </el-row>
      <el-row :gutter="20" style="margin-top: 20px;">
        <el-col :span="4">
          <div class="statistics-item">
            <div class="statistics-title">销量统计</div>
            <div class="statistics-value">{{ statisticsData.salesCount || 0 }}</div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 筛选条件区域 -->
    <el-form :model="queryParams" class="live-data-css" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="直播名称" prop="liveName">
        <el-input
          v-model="queryParams.liveName"
          placeholder="请输入直播名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="观看类型" prop="watchType">
        <el-select v-model="queryParams.watchType" placeholder="请选择观看类型" clearable size="small">
          <el-option label="直播" value="live"></el-option>
          <el-option label="回放" value="replay"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="完课状态" prop="completeStatus">
        <el-select v-model="queryParams.completeStatus" placeholder="请选择完课状态" clearable size="small">
          <el-option label="已完课" value="1"></el-option>
          <el-option label="未完课" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="付费状态" prop="payStatus">
        <el-select v-model="queryParams.payStatus" placeholder="请选择付费状态" clearable size="small">
          <el-option label="已付费" value="1"></el-option>
          <el-option label="未付费" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="观看时长" prop="watchDuration">
        <el-input-number
          v-model="queryParams.watchDuration"
          :min="0"
          :precision="0"
          placeholder="观看时长(分钟)"
          size="small"
        ></el-input-number>
      </el-form-item>
      <el-form-item label="时间范围" prop="dateRange">
        <el-date-picker
          v-model="dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          size="small"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <div 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="handleAutoTag">自动打标签</el-button>-->
      <!--      <el-button plain size="mini" @click="handleAutoRemark">自动备注</el-button>-->
      <el-button plain type="primary" size="mini" icon="el-icon-download" :loading="exportLoading" @click="handleExport">导出</el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
      ref="dataTable"
      :data="dataList"
      style="width: 100%"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
      <el-table-column prop="liveName" label="直播间名称" min-width="160" show-overflow-tooltip></el-table-column>
      <el-table-column prop="liveType" label="直播类型" width="100" align="center">
        <template slot-scope="scope">
          <el-tag type="danger" v-if="scope.row.liveType == 1">直播</el-tag>
          <el-tag type="success" v-else-if="scope.row.liveType == 2">录播</el-tag>
          <el-tag v-else-if="scope.row.liveType == 3">直播回放</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag type="info" v-if="scope.row.status == 1">未开始</el-tag>
          <el-tag type="warning" v-else-if="scope.row.status == 2">进行中</el-tag>
          <el-tag type="success" v-else-if="scope.row.status == 3">已结束</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="开始时间" width="180" align="center"></el-table-column>
      <el-table-column prop="finishTime" label="结束时间" width="180" align="center"></el-table-column>
      <el-table-column prop="totalViewers" label="累计观看" width="110" align="center"></el-table-column>
      <el-table-column prop="liveViewers" label="直播观看" width="110" align="center"></el-table-column>
      <el-table-column prop="playbackViewers" label="回放观看" width="110" align="center"></el-table-column>
      <el-table-column prop="liveAvgDuration" label="直播平均时长" width="140" align="center">
        <template slot-scope="scope">{{ formatDuration(scope.row.liveAvgDuration) }}</template>
      </el-table-column>
      <el-table-column prop="playbackAvgDuration" label="回放平均时长" width="140" align="center">
        <template slot-scope="scope">{{ formatDuration(scope.row.playbackAvgDuration) }}</template>
      </el-table-column>
      <el-table-column prop="totalCompletedCourses" label="累计完课" width="110" align="center"></el-table-column>
      <el-table-column prop="liveCompletedCourses" label="直播完课" width="110" align="center"></el-table-column>
      <el-table-column prop="playbackCompletedCourses" label="回放完课" width="110" align="center"></el-table-column>
      <el-table-column prop="gmv" label="GMV" width="120" align="center">
        <template slot-scope="scope">¥{{ scope.row.gmv || 0 }}</template>
      </el-table-column>
      <el-table-column prop="paidUsers" label="付费人数" width="100" align="center"></el-table-column>
      <el-table-column prop="paidOrders" label="付费单数" width="100" align="center"></el-table-column>
      <el-table-column prop="salesCount" label="销量统计" width="100" align="center"></el-table-column>
      <el-table-column label="操作" width="120" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleViewDetail(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      style="margin-top: 20px;"
    />

    <!-- 自动打标签弹窗 -->
    <el-dialog
      title="自动打标签"
      :visible.sync="tagDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="tagForm" label-width="120px">
        <el-form-item label="打标签规则">
          <el-checkbox-group v-model="tagForm.rules">
            <el-checkbox label="liveComplete">直播完课</el-checkbox>
            <el-checkbox label="replayComplete">回放完课</el-checkbox>
            <el-checkbox label="pay">付费行为</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="标签名称">
          <el-input v-model="tagForm.tagName" placeholder="请输入标签名称"></el-input>
        </el-form-item>
        <el-form-item label="备注格式">
          <el-radio-group v-model="tagForm.remarkFormat">
            <el-radio label="time">时间—行为（如：2024-01-01—直播完课）</el-radio>
            <el-radio label="simple">仅行为（如：直播完课）</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="tagDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAutoTag">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 自动备注弹窗 -->
    <el-dialog
      title="自动备注"
      :visible.sync="remarkDialogVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form :model="remarkForm" label-width="120px">
        <el-form-item label="备注规则">
          <el-checkbox-group v-model="remarkForm.rules">
            <el-checkbox label="liveComplete">直播完课</el-checkbox>
            <el-checkbox label="replayComplete">回放完课</el-checkbox>
            <el-checkbox label="pay">付费行为</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="备注格式">
          <el-radio-group v-model="remarkForm.remarkFormat">
            <el-radio label="time">时间—行为（如：2024-01-01—直播完课）</el-radio>
            <el-radio label="simple">仅行为（如：直播完课）</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注位置">
          <el-radio-group v-model="remarkForm.position">
            <el-radio :label="1">添加在最前面</el-radio>
            <el-radio :label="2">添加在最后面</el-radio>
            <el-radio :label="3">替换所有备注</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="remarkDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmAutoRemark">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 详情侧边栏 -->
    <el-drawer
      title="直播间详情"
      :visible.sync="detailDrawerVisible"
      direction="rtl"
      size="60%"
      :before-close="closeDetailDrawer"
    >
      <div v-if="!showUserDetail" class="detail-content">
        <el-card shadow="never" style="margin-bottom: 20px;">
          <div slot="header">
            <span>总体数据</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="handleViewUserDetail">查看用户详情</el-button>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">视频时长：</span>
                <span class="detail-value">{{ formatDuration(detailData.videoDuration || 0) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">累计观看人数：</span>
                <span class="detail-value">{{ detailData.totalViewers || 0 }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">累计完课人数：</span>
                <span class="detail-value">{{ detailData.totalCompletedCourses || 0 }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">到课完课率：</span>
                <span class="detail-value">{{ formatPercent(detailData.totalCompletionRate) }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" style="margin-bottom: 20px;">
          <div slot="header">直播数据</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">直播观看人数：</span>
                <span class="detail-value">{{ detailData.liveViewers || 0 }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">>20分钟人数（直播）：</span>
                <span class="detail-value">{{ detailData.liveOver20Minutes || 0 }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">>30分钟人数（直播）：</span>
                <span class="detail-value">{{ detailData.liveOver30Minutes || 0 }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">到课完课率直播（>20分钟）：</span>
                <span class="detail-value">{{ formatPercent(detailData.liveCompletionRate20) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">到课完课率直播（>30分钟）：</span>
                <span class="detail-value">{{ formatPercent(detailData.liveCompletionRate30) }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" style="margin-bottom: 20px;">
          <div slot="header">回放数据</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">回放观看人数：</span>
                <span class="detail-value">{{ detailData.playbackViewers || 0 }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">>20分钟人数（回放）：</span>
                <span class="detail-value">{{ detailData.playbackOver20Minutes || 0 }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">>30分钟人数（回放）：</span>
                <span class="detail-value">{{ detailData.playbackOver30Minutes || 0 }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">到课完课率回放（>20分钟）：</span>
                <span class="detail-value">{{ formatPercent(detailData.playbackCompletionRate20) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">到课完课率回放（>30分钟）：</span>
                <span class="detail-value">{{ formatPercent(detailData.playbackCompletionRate30) }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" style="margin-bottom: 20px;">
          <div slot="header">时长统计</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">直播峰值：</span>
                <span class="detail-value">{{ detailData.livePeak || 0 }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">直播平均时长：</span>
                <span class="detail-value">{{ formatDuration(detailData.liveAvgDuration || 0) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">回放平均时长：</span>
                <span class="detail-value">{{ formatDuration(detailData.playbackAvgDuration || 0) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">回放完播率：</span>
                <span class="detail-value">{{ formatPercent(detailData.playbackFinishRate) }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" style="margin-bottom: 20px;">
          <div slot="header">订单数据</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">GMV：</span>
                <span class="detail-value">{{ formatMoney(detailData.gmv) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">付费人数：</span>
                <span class="detail-value">{{ detailData.paidUsers || 0 }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">付费单数：</span>
                <span class="detail-value">{{ detailData.paidOrders || 0 }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">峰值转化率：</span>
                <span class="detail-value">{{ formatPercent(detailData.peakConversionRate) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">总到课转化率：</span>
                <span class="detail-value">{{ formatPercent(detailData.totalViewerConversionRate) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">30min完课转化率：</span>
                <span class="detail-value">{{ formatPercent(detailData.completion30MinConversionRate) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">峰值R值：</span>
                <span class="detail-value">{{ formatMoney(detailData.peakRValue) }}</span>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <span class="detail-label">完课R值：</span>
                <span class="detail-value">{{ formatMoney(detailData.completionRValue) }}</span>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <el-card shadow="never" v-if="detailData.productSalesList && detailData.productSalesList.length > 0">
          <div slot="header">单品销量统计</div>
          <el-table :data="detailData.productSalesList" border>
            <el-table-column prop="productName" label="商品名称" min-width="200"></el-table-column>
            <el-table-column prop="salesCount" label="销量" width="100" align="center"></el-table-column>
            <el-table-column prop="salesAmount" label="销售额" width="150" align="center">
              <template slot-scope="scope">
                {{ formatMoney(scope.row.salesAmount) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>

      <!-- 用户详情列表 -->
      <div v-else class="user-detail-content">
        <div style="margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
          <el-button type="text" icon="el-icon-arrow-left" @click="showUserDetail = false">返回</el-button>
          <el-button type="primary" size="small" icon="el-icon-download" :loading="userDetailExportLoading" @click="handleExportUserDetail">导出用户详情</el-button>
        </div>
        <el-table
          :data="userDetailList"
          v-loading="userDetailLoading"
          border
          style="width: 100%"
        >
          <el-table-column type="index" :index="getUserDetailIndex" label="序号" width="60" align="center"></el-table-column>
          <el-table-column prop="userName" label="用户名称" min-width="120"></el-table-column>
          <el-table-column prop="liveWatchDuration" label="直播观看时长" width="140" align="center">
            <template slot-scope="scope">
              {{ formatDuration(scope.row.liveWatchDuration || 0) }}
            </template>
          </el-table-column>
          <el-table-column prop="playbackWatchDuration" label="回放观看时长" width="140" align="center">
            <template slot-scope="scope">
              {{ formatDuration(scope.row.playbackWatchDuration || 0) }}
            </template>
          </el-table-column>
          <el-table-column prop="orderCount" label="订单数" width="100" align="center"></el-table-column>
          <el-table-column prop="orderAmount" label="订单金额" width="120" align="center">
            <template slot-scope="scope">
              {{ formatMoney(scope.row.orderAmount) }}
            </template>
          </el-table-column>
          <el-table-column prop="companyName" label="分公司" min-width="150"></el-table-column>
          <el-table-column prop="salesName" label="销售" min-width="120"></el-table-column>
        </el-table>
        <!-- 用户详情分页组件 -->
        <pagination
          v-show="userDetailTotal > 0"
          :total="userDetailTotal"
          :page.sync="userDetailQueryParams.pageNum"
          :limit.sync="userDetailQueryParams.pageSize"
          @pagination="getUserDetailList"
          style="margin-top: 20px;"
        />
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  listLiveData,
  exportLiveData,
  autoTagAndRemark,
  dashboardData,
  getLiveDataDetailBySql,
  getLiveUserDetailListBySql,
  exportLiveUserDetail
} from "@/api/live/liveData";

export default {
  name: "LiveData",
  data() {
    return {
      liveId: '',
      loading: true,
      exportLoading: false,
      showSearch: true,
      dataList: [],
      total: 0,
      multipleSelection: [],
      allChecked: false,
      isIndeterminate: false,
      dateRange: [],
      // 统计数据
      statisticsData: {
        gmv: 0,
        liveAvgDuration: 0,
        liveCompletedCourses: 0,
        livePeak: 0,
        liveViewers: 0,
        paidOrders: 0,
        paidUsers: 0,
        playbackAvgDuration: 0,
        playbackCompletedCourses: 0,
        playbackViewers: 0,
        salesCount: 0,
        totalCompletedCourses: 0,
        totalViewers: 1
      },
      // 完课时长设置
      completeWatchTime: 0,
      liveCompleteWatchTime: 0,
      replayCompleteWatchTime: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        liveId: null,
        liveName: null,
        watchType: null,
        completeStatus: null,
        payStatus: null,
        watchDuration: null,
        startTime: null,
        endTime: null
      },
      // 打标签弹窗
      tagDialogVisible: false,
      tagForm: {
        rules: [],
        tagName: '',
        remarkFormat: 'time'
      },
      // 备注弹窗
      remarkDialogVisible: false,
      remarkForm: {
        rules: [],
        remarkFormat: 'time',
        position: 1
      },
      // 详情侧边栏
      detailDrawerVisible: false,
      currentLiveId: null,
      detailData: {},
      userDetailList: [],
      userDetailLoading: false,
      showUserDetail: false,
      userDetailExportLoading: false,
      userDetailTotal: 0,
      userDetailQueryParams: {
        pageNum: 1,
        pageSize: 10
      }
    };
  },
  created() {
    this.liveId = this.$route.query.liveId;
    this.queryParams.liveId = this.liveId;

    this.getList();
  },
  methods: {
    /** 获取统计数据 */
    getStatistics() {
      if (!this.liveId) return;
      dashboardData(this.liveId).then(response => {
        if (response.code === 200) {
          this.statisticsData = response.data || {};
        }
      });
    },
    /** 获取列表数据 */
    getList() {
      this.loading = true;
      // 处理时间范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.startTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
      listLiveData(this.queryParams).then(response => {
        if (response.code === 200) {
          this.statisticsData = response.data || {};
          this.dataList = response.list || [];
          this.total = response.total || 0;
        }
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    /** 全选或取消全选 */
    toggleSelectAll(val) {
      if (val) {
        this.toggleSelection(this.dataList);
      } else {
        this.toggleSelection();
      }
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.dataTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.dataTable.clearSelection();
      }
    },
    /** 多选框选中数据 */
    handleSelectionChange(val) {
      this.multipleSelection = val;
      this.allChecked = val.length === this.dataList.length;
      this.isIndeterminate = val.length > 0 && val.length < this.dataList.length;
    },
    /** 导出按钮操作 */
    handleExport() {
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.startTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
      this.$confirm('是否确认导出所有直播数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportLiveData(this.queryParams);
      }).then(response => {
        if (response.code === 200) {
          this.download(response.msg);
        }
        this.exportLoading = false;
      }).catch(() => {
        this.exportLoading = false;
      });
    },
    /** 自动打标签 */
    // handleAutoTag() {
    //   if (this.multipleSelection.length === 0) {
    //     this.$message.warning('请选择要打标签的数据');
    //     return;
    //   }
    //   this.tagDialogVisible = true;
    // },
    /** 确认自动打标签 */
    confirmAutoTag() {
      if (this.tagForm.rules.length === 0) {
        this.$message.warning('请选择打标签规则');
        return;
      }
      const userIds = this.multipleSelection.map(item => item.userId).filter(id => id);
      if (userIds.length === 0) {
        this.$message.warning('所选数据中没有有效的用户ID');
        return;
      }
      const data = {
        userIds: userIds,
        rules: this.tagForm.rules,
        tagName: this.tagForm.tagName,
        remarkFormat: this.tagForm.remarkFormat,
        liveId: this.liveId
      };
      autoTagAndRemark(data).then(response => {
        if (response.code === 200) {
          this.$message.success('打标签成功');
          this.tagDialogVisible = false;
          this.tagForm = {
            rules: [],
            tagName: '',
            remarkFormat: 'time'
          };
          this.getList();
        }
      });
    },
    /** 自动备注 */
    // handleAutoRemark() {
    //   if (this.multipleSelection.length === 0) {
    //     this.$message.warning('请选择要备注的数据');
    //     return;
    //   }
    //   this.remarkDialogVisible = true;
    // },
    /** 确认自动备注 */
    confirmAutoRemark() {
      if (this.remarkForm.rules.length === 0) {
        this.$message.warning('请选择备注规则');
        return;
      }
      const userIds = this.multipleSelection.map(item => item.userId).filter(id => id);
      if (userIds.length === 0) {
        this.$message.warning('所选数据中没有有效的用户ID');
        return;
      }
      // 生成备注内容
      let notes = '';
      const now = new Date();
      const dateStr = now.getFullYear() + '-' +
        String(now.getMonth() + 1).padStart(2, '0') + '-' +
        String(now.getDate()).padStart(2, '0');

      this.remarkForm.rules.forEach((rule, index) => {
        let ruleText = '';
        if (rule === 'liveComplete') {
          ruleText = '直播完课';
        } else if (rule === 'replayComplete') {
          ruleText = '回放完课';
        } else if (rule === 'pay') {
          ruleText = '付费行为';
        }

        if (this.remarkForm.remarkFormat === 'time') {
          notes += (index > 0 ? '；' : '') + dateStr + '—' + ruleText;
        } else {
          notes += (index > 0 ? '；' : '') + ruleText;
        }
      });

      const data = {
        userIds: userIds,
        notes: notes,
        type: this.remarkForm.position,
        nameType: 3, // 不添加客户名称
        filter: false
      };

      batchUpdateExternalContactNotes(data).then(response => {
        if (response.code === 200) {
          this.$message.success('备注成功');
          this.remarkDialogVisible = false;
          this.remarkForm = {
            rules: [],
            remarkFormat: 'time',
            position: 1
          };
          this.getList();
        }
      });
    },
    /** 查看详情 */
    handleViewDetail(row) {
      this.currentLiveId = row.liveId;
      this.detailDrawerVisible = true;
      this.loadDetailData();
    },
    /** 格式化时长 */
    formatDuration(seconds) {
      if (!seconds) return '00:00:00';
      const hours = Math.floor(seconds / 3600);
      const minutes = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;
      return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(secs).padStart(2, '0')}`;
    },
    /** 更新完课时长设置 */
    updateCompleteWatchTime(type) {
      // 这里可以调用API保存设置
      let watchTime = 0;
      if (type === 'total') {
        watchTime = this.completeWatchTime;
      } else if (type === 'live') {
        watchTime = this.liveCompleteWatchTime;
      } else if (type === 'replay') {
        watchTime = this.replayCompleteWatchTime;
      }
      // 更新查询参数并重新获取数据
      this.queryParams.completeWatchTime = watchTime;
      // this.getStatistics();
      this.getList();
      this.$message.success('设置成功');
    },
    /** 加载详情数据 */
    loadDetailData() {
      if (!this.currentLiveId) return;
      // 使用SQL方式获取详情数据
      getLiveDataDetailBySql(this.currentLiveId).then(response => {
        if (response.code === 200) {
          this.detailData = response.data || {};
        }
      });
    },
    /** 查看用户详情 */
    handleViewUserDetail() {
      if (!this.currentLiveId) return;
      this.showUserDetail = true;
      this.userDetailQueryParams.pageNum = 1;
      this.getUserDetailList();
    },
    /** 获取用户详情列表 */
    getUserDetailList() {
      if (!this.currentLiveId) return;
      this.userDetailLoading = true;
      const params = {
        liveId: this.currentLiveId,
        pageNum: this.userDetailQueryParams.pageNum,
        pageSize: this.userDetailQueryParams.pageSize
      };
      getLiveUserDetailListBySql(params).then(response => {
        if (response.code === 200) {
          this.userDetailList = response.rows || response.data || [];
          this.userDetailTotal = response.total || 0;
        }
        this.userDetailLoading = false;
      }).catch(() => {
        this.userDetailLoading = false;
      });
    },
    /** 获取用户详情列表序号 */
    getUserDetailIndex(index) {
      return (this.userDetailQueryParams.pageNum - 1) * this.userDetailQueryParams.pageSize + index + 1;
    },
    /** 关闭详情侧边栏 */
    closeDetailDrawer() {
      this.detailDrawerVisible = false;
      this.showUserDetail = false;
      this.detailData = {};
      this.userDetailList = [];
      this.userDetailTotal = 0;
      this.userDetailQueryParams.pageNum = 1;
      this.currentLiveId = null;
    },
    /** 格式化百分比 */
    formatPercent(value) {
      if (value == null || value === undefined) return '0%';
      return (typeof value === 'number' ? value : parseFloat(value)).toFixed(2) + '%';
    },
    /** 格式化金额 */
    formatMoney(value) {
      if (value == null || value === undefined) return '¥0.00';
      return '¥' + (typeof value === 'number' ? value : parseFloat(value)).toFixed(2);
    },
    /** 导出用户详情数据 */
    handleExportUserDetail() {
      if (!this.currentLiveId) {
        this.$message.warning('无法获取直播间ID');
        return;
      }
      if (!this.userDetailList || this.userDetailList.length === 0) {
        this.$message.warning('暂无用户详情数据可导出');
        return;
      }
      this.$confirm('是否确认导出当前直播间的用户详情数据?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.userDetailExportLoading = true;
        return exportLiveUserDetail(this.currentLiveId);
      }).then(response => {
        if (response.code === 200) {
          this.download(response.msg);
          this.$message.success('导出成功');
        }
        this.userDetailExportLoading = false;
      }).catch(() => {
        this.userDetailExportLoading = false;
      });
    }
  }
};
</script>

<style scoped>
.statistics-card {
  margin-bottom: 20px;
}

.statistics-item {
  text-align: center;
  padding: 15px;
  background: #f5f7fa;
  border-radius: 4px;
}

.statistics-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.statistics-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

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

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

.live-data-css {
  padding-left: 10px;
  padding-top: 30px;
}

.detail-content {
  padding: 20px;
}

.detail-item {
  margin-bottom: 15px;
  line-height: 32px;
}

.detail-label {
  color: #606266;
  font-size: 14px;
}

.detail-value {
  color: #303133;
  font-size: 14px;
  font-weight: bold;
}

.user-detail-content {
  padding: 20px;
}
</style>
