<template>
  <div class="hostList cyber-form">
    <!-- 顶部筛选区域 - 玻璃态设计 -->
    <div class="filter-header glass-header">
      <!-- 第一行：主要筛选条件 -->
      <div class="filter-row primary-filters">
        <!-- 左侧筛选控件 -->
        <div class="filter-group flex-start gap-4">
          <el-checkbox class="cyber-checkbox" v-model="queryFormData.isFilter"
            :label="t('hostsList.filterPrivateUsers')" size="large" />

          <div class="input-group">
            <label class="input-label">
              <span class="label-icon">💰</span>
              {{ t('hostsList.coins') }}
            </label>
            <div class="input-pair">
              <el-input v-model="queryFormData.coinMin" :placeholder="t('hostsList.minCoins')" size="large"
                type="number" :disabled="streamdialogVisibletext || isRunnings" />
              <span class="input-divider">/</span>
              <el-input v-model="queryFormData.coinMax" :placeholder="t('hostsList.maxCoins')" size="large"
                type="number" :disabled="streamdialogVisibletext || isRunnings" />
            </div>
          </div>

          <div class="input-group">
            <label class="input-label">
              <span class="label-icon">📊</span>
              {{ t('hostsList.level') }}
            </label>
            <div class="input-pair">
              <el-input v-model="queryFormData.levelMin" :placeholder="t('hostsList.minLevel')" size="large"
                type="number" :disabled="streamdialogVisibletext || isRunnings" />
              <span class="input-divider">/</span>
              <el-input v-model="queryFormData.levelMax" :placeholder="t('hostsList.maxLevel')" size="large"
                type="number" :disabled="streamdialogVisibletext || isRunnings" />
            </div>
          </div>
        </div>
        <div class="info-pill" style="margin-top: 15px;">
          <span class="info-label" style="font-size: 16px">{{ t('hostsList.runningTime') }}:</span>
          <span class="info-value mono" style="font-size: 16px">
            {{ String(hourstuo).padStart(2, '0') }}:{{
              String(minutestuo).padStart(2, '0')
            }}:{{ String(secondstuo).padStart(2, '0') }}
          </span>
          <span class="info-divider"></span>
          <span class="info-label" style="font-size: 16px">{{ t('hostsList.total') }}:</span>
          <span class="info-value" style="font-size: 16px">{{ getBrotherInfodata.total }}</span>
          <span class="info-divider"></span>
          <span class="info-label" style="font-size: 16px">{{ t('hostsList.valid') }}:</span>
          <span class="info-value primary" style="font-size: 16px">{{ getBrotherInfodata.valid }}</span>
        </div>
        <!-- 右侧操作按钮 -->
        <div class="action-group flex-start gap-3">
          <el-button @click="streamdialogVisible = true" :disabled="isRunnings" class="cyber-btn-primary"
            type="primary">
            <span class="btn-icon">📍</span>
            {{
              streamdialogVisibletext
                ? t('hostsList.specifiedRooms')
                : t('hostsList.specifyRooms')
            }}
          </el-button>

          <el-button v-show="queryFormData.isRunning" class="cyber-btn-success" type="primary" @click="getBigBrother">
            {{ t('hostsList.start') }}
          </el-button>

          <el-button v-show="!queryFormData.isRunning" class="cyber-btn-danger" type="primary" @click="BigBrotherstop">
            {{ t('hostsList.end') }}
          </el-button>
        </div>
      </div>

      <!-- 分割线 -->
      <div class="filter-divider"></div>

      <!-- 第二行：搜索和操作 -->
      <div class="filter-row secondary-filters">
        <div class="filter-group flex-start gap-4">
          <el-select v-model="searchForm.region" filterable :placeholder="t('hostsList.selectCountry')" size="large"
            class="cyber-select">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>

          <el-input v-model="searchForm.displayId" :placeholder="t('hostsList.bigBrotherId')" size="large"
            class="cyber-input-search" clearable>
            <template #prefix>
              <span class="input-prefix-icon">@</span>
            </template>
          </el-input>

          <el-button class="ghost-btn" @click="serch">
            <span class="btn-icon">🔍</span>
            {{ t('hostsList.search') }}
          </el-button>

          <el-button class="ghost-btn" @click="reset">
            <span class="btn-icon">🔄</span>
            {{ t('hostsList.reset') }}
          </el-button>

          <el-button class="ghost-btn" :disabled="tableData.length == 0" @click="exportList">
            <span class="btn-icon">📥</span>
            {{ t('hostsList.exportExcel') }}
          </el-button>

          <el-button @click="filterdialogVisible = true" class="ghost-btn">
            <span class="btn-icon">⚙️</span>
            {{ t('hostsList.moreFilters') }}
          </el-button>

          <el-button class="ghost-btn" @click="openTikTok">
            <span class="btn-icon">🎵</span>
            {{ t('hostsList.openTikTok') }}
          </el-button>
        </div>

        <!-- 状态信息 -->
        <div class="status-info">
          <div class="info-pill">
            <span class="info-label">{{ t('hostsList.currentNetwork') }}:</span>
            <span class="info-value highlight">{{ countryData }}</span>
          </div>



        </div>
      </div>
    </div>

    <!-- 表格区域 - 卡片设计 -->
    <div class="table-container glass-card cyber-table">
      <div class="table-wrapper">
        <el-table ref="multipleTableRef" :data="tableData" stripe v-loading="loading" height="100%"
          @cell-dblclick="handleCellDbClick" @selection-change="handleSelectionChange">
          <el-table-column fixed prop="displayId" :label="t('hostsList.id')" min-width="120">
            <template #default="scope">
              <div class="link-text" @click="openHTML(scope.row.displayId)">
                {{ scope.row.displayId }}
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="hostDisplayId" :label="t('hostsList.hostId')" min-width="120">
            <template #default="scope">
              <div class="link-text" @click.ctrl.exact="handleLongPress(scope.row.hostDisplayId)">
                {{ scope.row.hostDisplayId }}
              </div>
            </template>
          </el-table-column>

          <el-table-column v-for="label in labelList" :key="label.paramCode" :prop="label.paramCode"
            :label="label.paramCodeMeaning" min-width="100">
            <template v-if="label.paramCode != 'createDt'" #default="scope">
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页区域 -->
      <div class="table-footer cyber-pagination">
        <div class="footer-left">
          <!-- <el-button class="ghost-btn-sm" @click="Resetss">
            <span class="btn-icon">🗑️</span>
            {{ t('hostsList.reset') }}
          </el-button> -->
        </div>
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" background
          layout="sizes, prev, pager, next" :total="total" :page-sizes="[10, 20, 50, 100, 500, 1000]"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- 更多筛选弹窗 -->
    <el-dialog v-model="filterdialogVisible" width="800px" :before-close="handleClose" class="cyber-dialog">
      <el-row :gutter="20">
        <el-col :span="4">
          <div style="height: 100%; padding-top: 10px" class="center-justify">
            {{ t('hostsList.time') }}
          </div>
        </el-col>
        <el-col :span="10">
          <div>
            <label>
              {{ t('hostsList.startTime') }}/{{ t('hostsList.endTime') }}
            </label>
          </div>

          <el-date-picker v-model="createTimes" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
            :placeholder="t('hostsList.selectTime')" size="large" style="width: 600px; margin-top: 10px" />
        </el-col>
      </el-row>

      <el-row v-for="(field, index) in fields" :key="index" :gutter="20" style="margin-bottom: 10px">
        <el-col :span="4">
          <div style="height: 100%" class="center-justify">
            {{ field.label }}
          </div>
        </el-col>
        <el-col :span="10">
          <div>
            <label>{{ t('hostsList.minValue') }}</label>
          </div>
          <el-input type="number" :oninput="'if(value.length>9)value=value.slice(0,9)'"
            v-model.number="searchForm[field.minModel]" :placeholder="t('hostsList.enterMinValue')" />
        </el-col>
        <el-col :span="10">
          <div>
            <label>{{ t('hostsList.maxValue') }}</label>
          </div>
          <el-input type="number" :oninput="'if(value.length>9)value=value.slice(0,9)'"
            v-model.number="searchForm[field.maxModel]" :placeholder="t('hostsList.enterMaxValue')" />
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="4">
          <div style="height: 100%; padding-top: 10px" class="center-justify">
            {{ t('hostsList.sort') }}
          </div>
        </el-col>
        <el-col :span="10">
          <div>
            <label>{{ t('hostsList.sortType') }}</label>
          </div>

          <el-select v-model="sortData.sortName" filterable :placeholder="t('hostsList.pleaseSelect')"
            style="width: 240px">
            <el-option v-for="item in sortNameOptions" :key="item.type" :label="item.label" :value="item.type" />
          </el-select>
        </el-col>
        <el-col :span="10">
          <div>
            <label>{{ t('hostsList.sortOrder') }}</label>
          </div>

          <el-select v-model="sortData.sort" filterable :placeholder="t('hostsList.pleaseSelect')" style="width: 240px">
            <el-option v-for="item in [
              { label: t('hostsList.ascending'), value: 'asc' },
              { label: t('hostsList.descending'), value: 'desc' },
            ]" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-col>
      </el-row>

      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="reset">
            {{ t('hostsList.reset') }}
          </el-button>
          <el-button type="primary" @click="handelClick">
            {{ t('hostsList.confirm') }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 指定直播间弹窗 -->
    <el-dialog v-model="streamdialogVisible" width="800px" :before-close="handleClose" class="cyber-dialog">
      <div class="specify-dialog">
        <el-input v-model="textarea" style="width: 100%" :rows="15" type="textarea"
          :placeholder="t('hostsList.enterRoomIds')" @input="handleInput" />
        <div v-if="maxSpecifyLines != 5000" class="specify-count-hint">
          {{ t('hostsList.currentCount') }} {{ currentLineCount }} {{ t('hostsList.countSeparator') }} {{
            maxSpecifyLines }}
          {{ t('hostsList.countUnit') }}
        </div>
        <div class="specify-footer">
          <el-button class="ghost-btn" @click="specifyCancel">
            {{ t('hostsList.cancelSpecify') }}
          </el-button>
          <el-button class="ghost-btn" @click="specifyreset">
            {{ t('hostsList.specifyReset') }}
          </el-button>
          <el-button type="primary" @click="specifyClick">
            {{ t('hostsList.specifyConfirm') }}
          </el-button>
          <el-button type="primary" @click="specifyClickStart">
            {{ t('hostsList.specifyStart') }}
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 网络不可访问弹窗 -->
    <el-dialog v-model="Inaccessible" width="800px" :before-close="handleClose" class="cyber-dialog">
      <div class="inaccessible-dialog">
        <img class="inaccessible-img" src="@/assets/wifi.png" />
      </div>
      <div class="inaccessible-dialog">
        {{ t('hostsList.networkFailed') }}
      </div>
    </el-dialog>
  </div>
</template>


<script setup>
// import { getToken, setToken, removeToken } from '@/utils/storage'
import { useI18n } from 'vue-i18n';
import {
  tkhostdata,
  dicts,
  tkhostdetail,
  downList,
  getStaffList,
  managerhosts,
  upholdinfo,
  getCountryinfo,
  tokenVerification,
  accountName,
} from "@/api/account";
import { usePythonBridge } from "@/utils/pythonBridge";
import { getUser, setSerch, getSerch } from "@/utils/storage";
import { getTenantLimit } from "@/utils/tenantConfig";
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
const hourstuo = ref(0);
const minutestuo = ref(0);
const secondstuo = ref(0);
import EChartsComponent from "@/components/EChartsComponent.vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { color } from "echarts";
import { getCountryName } from "@/utils/countryUtil";
import { ElLoading } from "element-plus";

const { t } = useI18n();

const Inaccessible = ref(false);

// 网络检测
const checkVPN = async () => {
  try {
    const timeout = new Promise(
      (_, reject) => setTimeout(() => reject(new Error("请求超时")), 10000)
    );

    const response = await Promise.race([
      fetch("https://www.google.com", { method: "HEAD", mode: "no-cors" }),
      timeout,
    ]);

    if (response && response.type === "opaque") {
      Inaccessible.value = false;
    } else {
      Inaccessible.value = true;
    }
  } catch (error) {
    Inaccessible.value = true;
  }
};

// 长按进入直播间
function handleLongPress(event) {
  openAnchorIdRooms(event);
}

// 复制单元格内容
function handleCellDbClick(row, column, cell, event) {
  const text = cell?.textContent?.trim();
  if (!text) {
    ElMessage({
      type: "warning",
      message: t("hostsList.noContentToCopy"),
    });
    return;
  }
  copyToClipboard(text);
}

async function copyToClipboard(text) {
  setClipboards(text)
    .then((res) => {
      ElMessage({
        type: "success",
        message: t("hostsList.copySuccess"),
      });
    })
    .catch((err) => {
      ElMessage({
        type: "error",
        message: t("hostsList.copyFailed"),
      });
    });
}

// ip 国家
let countryData = ref("");
// 获取屏幕宽度
const screenWidth = ref(window.innerWidth / 11);
// 获取国家
const getIpInfo = async () => {
  try {
    const response = await fetch("https://ipapi.co/json/");
    if (!response.ok) {
      throw new Error("请求失败");
    }
    const data = await response.json();
    console.log("IP信息:", data.country);

    countryData.value = getCountryName(data.country);
  } catch (error) {
    console.error("请求出错:", error);
    ElMessageBox.prompt(
      t("hostsList.pleaseEnterCountryName"),
      t("hostsList.getCountryFailed"),
      {
        confirmButtonText: t("hostsList.confirm"),
        cancelButtonText: t("hostsList.cancel"),
        showClose: false,
        closeOnClickModal: false,
        showCancelButton: false,
      }
    ).then(({ value }) => {
      countryData.value = value;
    });
  }
};

// 打开 TikTok 登录
function openTikTok() {
  loginTikTok();
}

// 重置
function Resetss() {
  queryFormData.value = {};
}

// 大哥 climb
const queryFormData = ref({
  coinMin: "", //打赏的金币最小值
  coinMax: "", //打赏的金币最大值
  levelMin: "", //等级最小值
  levelMax: "", //等级最大值
  isFilter: false, //是否筛选
  isRunning: true, //是否在运行
  anchor_ids: [], //指定直播间id
});

// 时间
const timerId = ref(null);
const getBrotherInfodata = ref({
  total: 0,
  valid: 0,
});

// 结束爬取
function BigBrotherstop() {
  const loading = ElLoading.service({
    lock: true,
    text: t("hostsList.stopping"),
    background: "rgba(0, 0, 0, 0.7)",
  });
  stopTimerfun();
  isRunnings.value = false;
  queryFormData.value.tenantId = userInfo.value.tenantId;
  queryFormData.value.region = countryData.value;

  controlTask(JSON.stringify(queryFormData.value)).then((res) => {
    queryFormData.value.isRunning = true;
    clearInterval(timerId.value);
    timerId.value = null;
    loading.close();
  });
  Specifystreaming(JSON.stringify(queryFormData.value)).then((res) => {
    queryFormData.value.isRunning = true;
    clearInterval(timerId.value);
    timerId.value = null;
    loading.close();
  });
}

// 指定直播间开始
function specifyClickStart() {
  if (textarea.value == "") {
    ElMessage({
      type: "error",
      message: t("hostsList.enterRoomId"),
    });
    return;
  }
  queryFormData.value.anchor_ids = textarea.value.split("\n");
  streamdialogVisible.value = false;
  streamdialogVisibletext.value = true;

  getBigBrother();
}

function specifyClick() {
  if (
    textarea.value == "" ||
    textarea.value == null ||
    textarea.value == undefined ||
    textarea.value.length == 0
  ) {
    streamdialogVisibletext.value = false;
    streamdialogVisible.value = false;
    queryFormData.value.anchor_ids = [];
  } else {
    streamdialogVisibletext.value = true;
    streamdialogVisible.value = false;
    queryFormData.value = {
      ...queryFormData.value,
      anchor_ids: textarea.value.split("\n").filter((id) => id.trim() !== ""),
    };
  }
}

// 指定直播间重置
function specifyreset() {
  textarea.value = "";
  streamdialogVisibletext.value = false;
  queryFormData.value.anchor_ids = [];
}
// 指定直播间取消
function specifyCancel() {
  streamdialogVisible.value = false;
  streamdialogVisibletext.value = false;
  queryFormData.value.anchor_ids = [];
}
// 输入框 input
import { computed } from "vue";

// 动态计算最大行数限制
const maxSpecifyLines = computed(() => {
  return getTenantLimit(userInfo.value.tenantId);
});

// 当前行数
const currentLineCount = computed(() => {
  if (!textarea.value || textarea.value.trim() === "") {
    return 0;
  }
  return textarea.value.split("\n").filter(line => line.trim() !== "").length;
});

function handleInput(value) {
  streamdialogVisibletext.value = false;
  if (typeof value !== "string") {
    return;
  }
  const lines = value.split("\n");
  if (lines.length > maxSpecifyLines.value) {
    textarea.value = lines.slice(0, maxSpecifyLines.value).join("\n");
  }
}

// 获取主播列表 - 开始爬取
function getBigBrother() {
  const loading = ElLoading.service({
    lock: true,
    text: t("hostsList.starting"),
    background: "rgba(0, 0, 0, 0.7)",
  });
  const storageobject = ref({
    key: "UserSettings",
    data: queryFormData.value,
  });
  storageSetInfos(storageobject.value).then((res) => { });
  queryFormData.value.tenantId = userInfo.value.tenantId;
  queryFormData.value.region = countryData.value;
  startTimerfun();
  isRunnings.value = true;
  if (
    queryFormData.value.anchor_ids == [] ||
    queryFormData.value.anchor_ids == null ||
    queryFormData.value.anchor_ids == undefined ||
    queryFormData.value.anchor_ids.length == ""
  ) {
    controlTask(JSON.stringify(queryFormData.value)).then((res) => {
      queryFormData.value.isRunning = false;
      timerId.value = setInterval(() => {
        getBrotherInfo().then((res) => {
          loading.close();
          getBrotherInfodata.value = res;
        });
      }, 1000);
    });
  } else {
    Specifystreaming(JSON.stringify(queryFormData.value)).then((res) => {
      queryFormData.value.isRunning = false;
      timerId.value = setInterval(() => {
        getBrotherInfo().then((res) => {
          loading.close();
          getBrotherInfodata.value = res;
        });
      }, 1000);
    });
  }
}

const loading = ref(false);
// py 方法
const {
  givePyAnchorId,
  exportToExcel,
  loginTikTok,
  controlTask,
  getBrotherInfo,
  Specifystreaming,
  setStorageStreamId,
  getStorageStreamId,
  openAnchorIdRooms,
  storageSetInfos,
  readSetInfos,
  setClipboards,
} = usePythonBridge();

let num = ref(0);
// 账号信息
const userInfo = ref({});
// 主播列表 DOM
const multipleTableRef = ref(null);
let labelList = ref([
  { paramCode: "userIdStr", paramCodeMeaning: t("hostsList.userId") },
  { paramCode: "level", paramCodeMeaning: t("hostsList.level") },
  { paramCode: "fansLevel", paramCodeMeaning: t("hostsList.fansLevel") },
  { paramCode: "hostcoins", paramCodeMeaning: t("hostsList.coins") },
  { paramCode: "region", paramCodeMeaning: t("hostsList.region") },
  { paramCode: "followerCount", paramCodeMeaning: t("hostsList.followerCount") },
  { paramCode: "followingCount", paramCodeMeaning: t("hostsList.followingCount") },
  { paramCode: "createTime", paramCodeMeaning: t("hostsList.createTime") },
  { paramCode: "totalGiftCoins", paramCodeMeaning: t("hostsList.totalGiftCoins") },
]);

const tableData = ref([]);
// 主播列表传参
const searchForm = ref({});
const createTimes = ref([]);
// 分页
const page = ref(1);
const pageSize = ref(10);
const fields = [
  { label: t("hostsList.level"), minModel: "levelMin", maxModel: "levelMax" },
];
// 排序
let sortData = ref({ sortName: "createTime", sort: "desc" });

// 排序类型
let sortNameOptions = ref([
  { label: t("hostsList.createTime"), type: "createTime" },
  { label: t("hostsList.coins"), type: "hostsCoins" },
  { label: t("hostsList.totalGiftCoins"), type: "totalGiftCoins" },
  { label: t("hostsList.level"), type: "level" },
]);
// 是否在运行
let isRunnings = ref(false);
// 是否指定直播间
let streamdialogVisibletext = ref(false);
// 指定直播间弹窗
let streamdialogVisible = ref(false);
// 指定直播间 id
let textarea = ref("");
// 计时器
let startTime = ref(null);
// 筛选弹窗
let filterdialogVisible = ref(false);
// 分配的员工
let staffId = ref({});
// 备注信息
let commentInfo = ref("");
// 备注信息主播
let commentHost = ref("");
// 分页
let total = ref(0);
// 是否渲染
const isPopoverVisible = reactive({});

let options = ref([]);

let version = ref("0.0.0");

const lastVisibleTime = ref(null);

function tokenVerificationfun(params) {
  tokenVerification(params)
    .then((res) => { })
    .catch((err) => { });
}

onMounted(() => {
  window.addEventListener("resize", handleResize);
  window.addEventListener("visibilitychange", handleVisibilityChange);
  setTimeout(() => {
    getUserdata();
    readSetInfos("UserSettings").then((res) => {
      const storageData = (queryFormData.value =
        res == ""
          ? {
            coinMin: "",
            coinMax: "",
            levelMin: "",
            levelMax: "",
            isFilter: false,
            isRunning: true,
            anchor_ids: [],
          }
          : JSON.parse(res));

      if (
        storageData.anchor_ids == "" ||
        storageData.anchor_ids == null ||
        storageData.anchor_ids == undefined ||
        storageData.anchor_ids.length == 0
      ) {
        streamdialogVisibletext.value = false;
        textarea.value = "";
      } else {
        streamdialogVisibletext.value = true;
        textarea.value = storageData.anchor_ids.join("\n");
      }
    });
  }, 500);
  setInterval(() => {
    checkVPN();
    tokenVerificationfun();
  }, 10000);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  window.removeEventListener("visibilitychange", handleVisibilityChange);
});

function handleVisibilityChange() {
  if (isRunnings.value) {
    if (document.hidden) {
      lastVisibleTime.value = Date.now();
      stopTimerfun();
    } else {
      if (lastVisibleTime.value) {
        const hiddenDuration = Math.floor(
          (Date.now() - lastVisibleTime.value) / 1000
        );
        secondstuo.value += hiddenDuration % 60;
        minutestuo.value += Math.floor(hiddenDuration / 60) % 60;
        hourstuo.value += Math.floor(hiddenDuration / 3600);
      }

      startTimerfun();
    }
  }
}

// 启动计时器
function startTimerfun() {
  startTime.value = setInterval(() => {
    secondstuo.value++;
    if (secondstuo.value >= 60) {
      secondstuo.value = 0;
      minutestuo.value++;
      if (minutestuo.value >= 60) {
        minutestuo.value = 0;
        hourstuo.value++;
      }
    }
  }, 1000);
}

// 停止计时器
function stopTimerfun() {
  clearInterval(startTime.value);
}

// 表格单元格长度判断
function handleResize() {
  screenWidth.value = window.innerWidth / 11;
}

async function getUserdata() {
  const User = await getUser();
  userInfo.value = User;
  getCountry(); //获取国家
  getlist(); //获取主播列表
  getIpInfo();
}

function serch() {
  page.value = 1;
  getlist();
}

function exportList() {
  exportToExcel(requestParams.value);
}

// 分页每页条数
function handleSizeChange(val) {
  console.log(`${val} items per page`);
  getlist();
}
// 分页页数
function handleCurrentChange(val) {
  console.log(`current page: ${val}`);
  getlist();
}
// 选择行
function handleSelectionChange(data) {
  console.log(data);
  selectHostList.value = [];
  data.forEach((item) => {
    selectHostList.value.push(item.hostId);
  });
}

// 时间格式化
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 获取主播列表
let requestParams = ref({});
const getlist = () => {
  loading.value = true;
  tkhostdata({
    tenantId: Number(userInfo.value.tenantId),
    sort: sortData.value.sort,
    sortName: sortData.value.sortName,
    current: page.value,
    pageSize: pageSize.value,
    createTimeStart: createTimes.value[0],
    createTimeEnd: createTimes.value[1],
    ...searchForm.value,
  }).then((res) => {
    loading.value = false;
    if (res) {
      requestParams.value = res.records;
      total.value = Number(res.total);
      tableData.value = res.records.map((item) => ({
        level: item.level,
        fansLevel: item.fansLevel,
        createTime: formatDate(new Date(item.createTime)),
        followerCount: item.followerCount,
        followingCount: item.followingCount,
        hostDisplayId: item.hostDisplayId,
        hostcoins: item.hostcoins,
        region: item.region,
        totalGiftCoins: item.totalGiftCoins,
        userIdStr: item.userIdStr,
        displayId: item.displayId,
      }));
    }
  });
};

function handelClick() {
  filterdialogVisible.value = false;
}

function reset() {
  searchForm.value = {};
  sortData.value = { sortName: "createTime", sort: "desc" };
  createTimes.value = [];
}

function handleClose(done) {
  console.log("关闭");
  done();
}

function filterTag(value, row) {
  console.log(row.useable, value);
  return row.useable === value;
}

const { locale } = useI18n();
// 获取国家
function getCountry() {
  getCountryinfo({})
    .then((res) => {
      res.forEach((item) => {
        if (item.countryGroupName) {
          if (locale.value === 'en-US') {
            options.value.push({
              value: item.countryGroupName,
              label: item.countryNameEnglish,
            });
          } else if (locale.value === 'zh-CN') {
            options.value.push({
              value: item.countryGroupName,
              label: item.countryGroupName,
            });
          }
        }
      });
    })
    .catch((err) => {
      console.log("getCountry", err);
    });
}

function openPopover(hostId, paramCode) {
  isPopoverVisible[`${hostId}-${paramCode}`] = true;
}

function closePopover(hostId, paramCode) {
  // isPopoverVisible[`${hostId}-${paramCode}`] = false;
}

function openHTML(id) {
  console.log(id);
  givePyAnchorId(id);
}
function openhostDisplayId(hostDisplayId) {
  givePyAnchorId(hostDisplayId);
}
</script>


<style lang="less">
@import "@/static/css/cyber-design.less";

.hostList {
  box-sizing: border-box;
  padding: 24px 28px;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 20px;

  /* 页面无法选中 */
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

// ================================
// 玻璃态头部区域 - 简化版（移除 backdrop-filter 提升性能）
// ================================
.filter-header.glass-header {
  background: #ffffff;
  border: 1px solid #e8ecf0;
  border-radius: 24px;
  padding: 24px 28px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.filter-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-group {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.filter-divider {
  width: 100%;
  height: 1px;
  background: linear-gradient(to right, transparent, rgba(226, 232, 240, 0.6), transparent);
  margin: 20px 0;
}

// ================================
// 输入框组样式
// ================================
.input-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.input-label {
  font-size: 11px;
  font-weight: 700;
  color: #94a3b8;
  text-transform: uppercase;
  letter-spacing: 0.05em;
  display: flex;
  align-items: center;
  gap: 6px;

  .label-icon {
    font-size: 12px;
  }
}

.input-pair {
  display: flex;
  align-items: center;
  gap: 8px;

  .el-input {
    width: 120px;
  }
}

.input-divider {
  color: #cbd5e1;
  font-weight: 300;
}

.input-prefix-icon {
  color: #94a3b8;
  font-weight: 600;
}

// ================================
// 按钮样式 - 简化版（移除 transform 动画提升性能）
// ================================
.cyber-btn-primary {
  background: linear-gradient(135deg, #00D2FF 0%, #0052CC 100%) !important;
  border: none !important;
  border-radius: 16px !important;
  font-weight: 600 !important;
  padding: 0 20px !important;
  height: 42px !important;
  box-shadow: 0 2px 8px rgba(0, 82, 204, 0.2) !important;

  .btn-icon {
    margin-right: 6px;
  }

  &:hover {
    filter: brightness(1.05);
  }
}

.cyber-btn-success {
  background: linear-gradient(135deg, #10B981 0%, #059669 100%) !important;
  border: none !important;
  border-radius: 16px !important;
  font-weight: 600 !important;
  padding: 0 24px !important;
  height: 42px !important;
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.2) !important;

  &:hover {
    filter: brightness(1.05);
  }
}

.cyber-btn-danger {
  background: linear-gradient(135deg, #EF4444 0%, #DC2626 100%) !important;
  border: none !important;
  border-radius: 16px !important;
  font-weight: 600 !important;
  padding: 0 24px !important;
  height: 42px !important;
  box-shadow: 0 2px 8px rgba(239, 68, 68, 0.2) !important;

  &:hover {
    filter: brightness(1.05);
  }
}

.ghost-btn {
  background: #ffffff !important;
  border: 1px solid #e2e8f0 !important;
  border-radius: 14px !important;
  color: #475569 !important;
  font-weight: 600 !important;
  padding: 0 16px !important;
  height: 40px !important;
  display: inline-flex !important;
  align-items: center !important;
  gap: 6px !important;

  .btn-icon {
    font-size: 14px;
  }

  &:hover {
    background: #f8fafc !important;
    border-color: #cbd5e1 !important;
  }

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
}

.ghost-btn-sm {
  background: transparent !important;
  border: 1px solid #e2e8f0 !important;
  border-radius: 12px !important;
  color: #64748b !important;
  font-weight: 500 !important;
  font-size: 12px !important;
  padding: 0 12px !important;
  height: 32px !important;

  .btn-icon {
    font-size: 12px;
  }

  &:hover {
    background: #f1f5f9 !important;
  }
}

// ================================
// 状态信息胶囊
// ================================
.status-info {
  .info-pill {
    display: inline-flex;
    align-items: center;
    gap: 16px;
    background: rgba(255, 255, 255, 0.6);
    padding: 10px 20px;
    border-radius: 20px;
    border: 1px solid rgba(255, 255, 255, 0.8);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    font-size: 13px;

    .info-label {
      color: #94a3b8;
      font-weight: 500;

    }

    .info-value {
      color: #334155;
      font-weight: 600;

      &.highlight {
        color: #0052CC;
        background: rgba(0, 82, 204, 0.08);
        padding: 2px 10px;
        border-radius: 12px;
      }

      &.mono {
        font-family: 'SF Mono', Monaco, monospace;
      }

      &.primary {
        color: #0052CC;
      }
    }

    .info-divider {
      width: 1px;
      height: 16px;
      background: #e2e8f0;
    }
  }
}

// ================================
// 表格容器
// ================================
.table-container.glass-card {
  flex: 1;
  min-height: 0; // 关键：让 flex 子元素能够正确收缩
  background: #ffffff;
  border-radius: 24px;
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.04), 0 8px 10px -6px rgba(0, 0, 0, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.table-wrapper {
  flex: 1;
  min-height: 0; // 关键：让 flex 子元素能够正确收缩
  padding: 20px 24px 0;
  overflow: hidden;

  .el-table {
    height: 100% !important;
  }
}

.table-footer {
  padding: 16px 24px;
  background: rgba(248, 250, 252, 0.5);
  border-top: 1px solid #f1f5f9;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .footer-left {
    display: flex;
    align-items: center;
    gap: 16px;
  }
}

// ================================
// 表格样式覆盖
// ================================
.cyber-table {
  .el-table {
    background: transparent !important;
    --el-table-border-color: transparent;
    --el-table-header-bg-color: transparent;
    --el-table-row-hover-bg-color: rgba(248, 250, 252, 0.8);

    &::before {
      display: none;
    }

    th.el-table__cell {
      background: transparent !important;
      font-size: 11px !important;
      font-weight: 700 !important;
      color: #94a3b8 !important;
      text-transform: uppercase !important;
      letter-spacing: 0.05em !important;
      padding: 14px 12px 18px !important;
      border-bottom: 1px solid #f1f5f9 !important;

      .cell {
        padding: 0 8px;
      }
    }

    td.el-table__cell {
      padding: 14px 12px !important;
      font-size: 14px !important;
      color: #475569 !important;
      border-bottom: 1px solid transparent !important;

      .cell {
        padding: 0 8px;
      }
    }

    .el-table__row {
      transition: background 0.15s ease;

      &:hover>td.el-table__cell {
        background: #f8fafc !important;
      }
    }

    // 斑马纹
    .el-table__row--striped td.el-table__cell {
      background: rgba(248, 250, 252, 0.4) !important;
    }
  }

  .link-text {
    color: #0052CC;
    font-weight: 600;
    text-decoration: underline;
    text-decoration-color: rgba(0, 82, 204, 0.2);
    text-underline-offset: 3px;
    cursor: pointer;
    transition: all 0.2s ease;

    &:hover {
      text-decoration-color: #0052CC;
    }
  }
}

// ================================
// 分页样式覆盖
// ================================
.cyber-pagination {
  .el-pagination {
    --el-pagination-bg-color: transparent;
    --el-pagination-hover-color: #0052CC;

    .el-pager li {
      min-width: 34px;
      height: 34px;
      line-height: 34px;
      border-radius: 10px;
      font-weight: 600;
      font-size: 12px;
      margin: 0 2px;
      background: transparent;
      transition: all 0.2s ease;

      &:hover {
        background: #ffffff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      }

      &.is-active {
        background: #0f172a !important;
        color: #ffffff !important;
        box-shadow: 0 4px 12px rgba(15, 23, 42, 0.2);
      }
    }

    .btn-prev,
    .btn-next {
      background: transparent;
      border-radius: 10px;
      transition: all 0.2s ease;

      &:hover {
        background: #ffffff;
        color: #0052CC;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
      }
    }

    .el-select__wrapper {
      background: #ffffff !important;
      border: 1px solid #e2e8f0 !important;
      border-radius: 10px !important;
    }
  }
}

// ================================
// 复选框样式
// ================================
.cyber-checkbox {
  height: 40px;
  padding: 0 16px;
  background: #ffffff;
  border: 1px solid rgba(226, 232, 240, 0.6);
  border-radius: 14px;
  transition: all 0.2s ease;
  margin-right: 0 !important;
  margin-top: 22px !important;

  &:hover {
    border-color: #cbd5e1;
  }

  .el-checkbox__input.is-checked .el-checkbox__inner {
    background-color: #0052CC;
    border-color: #0052CC;
  }

  .el-checkbox__label {
    font-weight: 600;
    color: #475569;
    font-size: 13px;
  }
}

// ================================
// 选择器样式
// ================================
.cyber-select {
  width: 160px;

  .el-select__wrapper {
    background: #ffffff !important;
    border: 1px solid rgba(226, 232, 240, 0.6) !important;
    border-radius: 14px !important;
    box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.03) !important;
    height: 40px !important;
  }
}

.cyber-input-search {
  width: 180px;

  .el-input__wrapper {
    background: #ffffff !important;
    border: 1px solid rgba(226, 232, 240, 0.6) !important;
    border-radius: 14px !important;
    box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.03) !important;
    height: 40px !important;
  }
}

// ================================
// 弹窗样式
// ================================
.cyber-dialog {
  .el-dialog {
    border-radius: 24px !important;
    overflow: hidden;
  }

  .el-dialog__header {
    padding: 20px 24px;
    border-bottom: 1px solid #f1f5f9;
  }

  .el-dialog__body {
    padding: 24px;
  }

  .el-dialog__footer {
    padding: 16px 24px;
    border-top: 1px solid #f1f5f9;
  }
}

.specify-dialog {
  min-height: 350px;
}

.specify-count-hint {
  margin-top: 10px;
  padding: 8px 12px;
  background: linear-gradient(135deg, rgba(0, 210, 255, 0.08) 0%, rgba(0, 82, 204, 0.08) 100%);
  border-radius: 8px;
  color: #475569;
  font-size: 13px;
  font-weight: 500;
  text-align: right;
}

.specify-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
}

.inaccessible-dialog {
  width: 100%;
  min-height: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  color: #64748b;
  text-align: center;
}

.inaccessible-img {
  width: 120px;
  height: 120px;
  opacity: 0.6;
}

// ================================
// Element Plus 输入框覆盖
// ================================
.el-input__wrapper {
  background: #ffffff !important;
  border: 1px solid rgba(226, 232, 240, 0.6) !important;
  border-radius: 12px !important;
  box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.03) !important;
  transition: all 0.2s ease !important;

  &:hover {
    border-color: #cbd5e1 !important;
  }

  &.is-focus {
    border-color: rgba(0, 82, 204, 0.3) !important;
    box-shadow: 0 0 0 3px rgba(0, 82, 204, 0.08) !important;
  }
}

.el-input--large .el-input__wrapper {
  height: 40px !important;
  padding: 0 12px !important;
}

.el-select__wrapper {
  background: #ffffff !important;
  border: 1px solid rgba(226, 232, 240, 0.6) !important;
  border-radius: 12px !important;
  box-shadow: inset 0 2px 4px 0 rgba(0, 0, 0, 0.03) !important;
  min-height: 40px !important;
}

// ================================
// 工具类
// ================================
.flex-start {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.gap-3 {
  gap: 12px;
}

.gap-4 {
  gap: 16px;
}

.center-justify {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
