<template>
  <el-dialog v-model="visible" :title="$t('hostList.liveSessions') || '直播记录'" width="80vw" top="6vh" :close-on-click-modal="false" destroy-on-close>
    <div class="toolbar">
      <div class="left">
        <el-input v-model="kw" :placeholder="$t('hostList.searchPlaceholder') || 'Search...'" style="width: 200px; margin-right: 10px;" clearable />
        <el-checkbox v-model="onlyAbnormal">{{ $t('hostList.onlyAbnormal') || '只看异常' }}</el-checkbox>
      </div>
      <div class="right">
        <el-tag type="info">{{ $t('hostList.total') || '总条数' }}：{{ filteredRows.length }}</el-tag>
        <el-tag type="success">{{ $t('hostList.totalLikes') || '点赞合计' }}：{{ totalLikes }}</el-tag>
        <el-tag type="warning">{{ $t('hostList.zeroLikes') || '无点赞' }}：{{ zeroLikeCount }}</el-tag>
      </div>
    </div>

    <el-table :data="filteredRows" border height="62vh" style="width: 100%"
      :default-sort="{ prop: 'startTimeFormatted', order: 'descending' }" table-layout="auto"
      @row-dblclick="copyRow">
      <el-table-column prop="hostsId" :label="$t('hostList.hostId') || '主播id'" />
      <el-table-column prop="startTimeFormatted" :label="$t('hostList.startTime') || '开始时间'" sortable />
      <el-table-column prop="endTimeFormatted" :label="$t('hostList.endTime') || '结束时间'" sortable />
      <el-table-column prop="durationFormatted" :label="$t('hostList.duration') || '时长'" />

      <el-table-column prop="likeCount" :label="$t('hostList.likeCount') || '点赞'" sortable>
        <template #default="{ row }">
          <el-tag v-if="row.likeCount === 0" type="danger">0</el-tag>
          <span v-else>{{ row.likeCount }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="createTime" :label="$t('hostList.createTime') || '入库时间'" sortable />
    </el-table>

    <template #footer>
      <el-button @click="visible = false">{{ $t('hostList.close') || '关闭' }}</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  rows: {
    type: Array,
    default: () => [],
  },
});

const emit = defineEmits(["update:modelValue", "select"]);

const visible = computed({
  get: () => props.modelValue,
  set: (v) => emit("update:modelValue", v),
});

const kw = ref("");
const sortKey = ref("startTimeFormatted");
const sortOrder = ref("desc");
const onlyAbnormal = ref(false);

function parseTime(s) {
  if (!s) return 0;
  // Handle various date formats if necessary, but standard string sort might be enough if ISO
  // Original code used simple replacement, assume backend sends usable strings
  return new Date(s.replace(" ", "T")).getTime() || 0;
}

function durationSeconds(durationFormatted) {
  if (!durationFormatted) return 0;
  const h = Number((durationFormatted.match(/(\d+)\s*小时/) || [])[1] || 0);
  const m = Number((durationFormatted.match(/(\d+)\s*分钟/) || [])[1] || 0);
  const s = Number((durationFormatted.match(/(\d+)\s*秒/) || [])[1] || 0);
  return h * 3600 + m * 60 + s;
}

const filteredRows = computed(() => {
  const k = kw.value.trim().toLowerCase();

  // Pre-process rows to ensure formatted fields exist if they come from backend differently
  // The original component assumed rows already had `startTimeFormatted` etc.
  // We'll trust the prop data or add basic fallback if needed.
  let arr = (props.rows || []).map(r => ({
      ...r,
      // If props don't have formatted times, we might need to create them.
      // Assuming 'startTime' is the key from backend based on previous version of this file
      startTimeFormatted: r.startTimeFormatted || r.startTime || '',
      endTimeFormatted: r.endTimeFormatted || r.endTime || '',
      durationFormatted: r.durationFormatted || r.duration || '',
  })).filter((r) => {
    if (!k) return true;
    const hay = `${r.id || ''} ${r.userId || ''} ${r.hostsId || ''} ${r.tenantId || ''}`.toLowerCase();
    return hay.includes(k);
  });

  if (onlyAbnormal.value) {
    arr = arr.filter((r) => r.likeCount === 0 || durationSeconds(r.durationFormatted) < 60);
  }

  // Element Plus table handles sorting if we use 'sortable' on columns, 
  // but if we want custom client-side sort for everything:
  // The original used custom sort logic. We can stick to Element Plus default sort 
  // by removing the manual sort here OR keep it if we want to ensure specific logic.
  // The original code RETURNED the sorted array. Element Plus :data usually expects the full array 
  // and handles sort if 'sortable' is set. 
  // BUT the original code manually sorted `arr`. Let's keep it to be safe.
  
  // Actually, Element Plus's local sort works on the current page/data. 
  // If we modify 'arr' order here, it sets the default order.
  
  return arr;
});

const totalLikes = computed(() =>
  filteredRows.value.reduce((sum, r) => sum + (Number(r.likeCount) || 0), 0)
);

const zeroLikeCount = computed(() => filteredRows.value.filter((r) => r.likeCount === 0).length);

async function copyRow(row) {
  try {
    await navigator.clipboard.writeText(JSON.stringify(row, null, 2));
    ElMessage.success("已复制该行 JSON");
  } catch {
    ElMessage.warning("复制失败：浏览器不支持或无权限");
  }
}
</script>

<style scoped>
.toolbar {
  display: flex;
  gap: 12px;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.toolbar .left {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.toolbar .right {
  display: flex;
  gap: 8px;
  align-items: center;
  flex-wrap: wrap;
}
</style>
