<template>
  <el-dialog v-model="visible" title="直播记录" width="80vw" top="6vh" :close-on-click-modal="false" destroy-on-close>
    <div class="toolbar">
      <div class="left">
        <el-checkbox v-model="onlyAbnormal">只看异常</el-checkbox>
      </div>
      <div class="right">
        <el-tag type="info">总条数：{{ filteredRows.length }}</el-tag>
        <el-tag type="success">点赞合计：{{ totalLikes }}</el-tag>
        <el-tag type="warning">无点赞：{{ zeroLikeCount }}</el-tag>
      </div>
    </div>

    <el-table :data="filteredRows" border height="62vh" style="width: 100%"
      :default-sort="{ prop: 'startTimeFormatted', order: 'descending' }" table-layout="auto">
      <el-table-column prop="hostsId" label="主播id" />
      <el-table-column prop="startTimeFormatted" label="开始时间" />
      <el-table-column prop="endTimeFormatted" label="结束时间" />
      <el-table-column prop="durationFormatted" label="时长" />

      <el-table-column prop="likeCount" label="点赞" 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="入库时间" />
    </el-table>

    <template #footer>
      <el-button @click="visible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="js">
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;
  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();

  let arr = (props.rows || []).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);
  }

  const key = sortKey.value;
  const order = sortOrder.value;

  arr = [...arr].sort((a, b) => {
    const av = a[key];
    const bv = b[key];

    if (key === "startTimeFormatted" || key === "endTimeFormatted" || key === "createTime") {
      const aa = parseTime(String(av));
      const bb = parseTime(String(bv));
      return order === "desc" ? bb - aa : aa - bb;
    }

    if (typeof av === "number" && typeof bv === "number") {
      return order === "desc" ? bv - av : av - bv;
    }

    return order === "desc"
      ? String(bv).localeCompare(String(av))
      : String(av).localeCompare(String(bv));
  });

  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);

function reset() {
  kw.value = "";
  sortKey.value = "startTimeFormatted";
  sortOrder.value = "desc";
  onlyAbnormal.value = false;
}

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

function emitSelect(row) {
  emit("select", row);
  ElMessage.success(`已选中：ID ${row.id}`);
}
</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>
