大哥 主播 即时消息 三合一

This commit is contained in:
2026-02-04 19:56:19 +08:00
parent 85e5d1ccb7
commit 791560af2e
52 changed files with 8324 additions and 4611 deletions

180
src/views/YoloBrowser.vue Normal file
View File

@@ -0,0 +1,180 @@
<template>
<div class="flex h-full w-full bg-gradient-to-br from-gray-50 to-gray-100 animate-fadeIn">
<!-- 侧边栏 -->
<Sidebar :tabs="tabs" :current-tab="currentTab" @tab-switch="handleTabSwitch" @go-back="handleGoToConfig"
@stop-all="handleStopAll" :is-loading="isLoading" :account-groups="accountGroups"
:rotation-status="rotationStatus" :greeting-stats="greetingStats" :automation-logs="automationLogs" />
<!-- 内容区域 -->
<main class="flex-1 flex flex-col relative">
<!-- 顶部视图切换栏 -->
<div class="h-12 bg-white border-b border-gray-200 flex items-center px-4 gap-2 shadow-sm">
<span class="text-gray-500 text-sm mr-2">视图:</span>
<button v-for="viewId in currentTabConfig.viewIds" :key="viewId" @click="handleViewSwitch(viewId)"
:class="[
'px-3 py-1.5 rounded-lg text-sm font-medium transition-all',
(selectedViewId || currentTabConfig.viewIds[0]) === viewId
? 'bg-blue-500 text-white shadow-md'
: 'bg-gray-100 text-gray-600 hover:bg-gray-200 border border-gray-200'
]">
视图 {{ viewId }}
<span v-if="viewAccountMap[viewId]" class="ml-1.5 text-xs opacity-70">
({{ viewAccountMap[viewId].email.split('@')[0] }})
</span>
</button>
<div class="flex-1" />
<!-- 状态指示 -->
<span v-if="automationStatus[selectedViewId || currentTabConfig.viewIds[0]]"
class="text-xs text-gray-500 bg-gray-100 px-2 py-1 rounded border border-gray-200">
{{ automationStatus[selectedViewId || currentTabConfig.viewIds[0]] }}
</span>
</div>
<!-- 单个视图显示区域 -->
<div class="flex-1 relative">
<ViewPlaceholder class="absolute inset-0" />
</div>
<div v-if="isLoading" class="absolute inset-0 bg-slate-900/80 flex items-center justify-center z-50">
<div class="flex flex-col items-center gap-3">
<div class="w-10 h-10 border-3 border-t-primary-400 border-slate-600 rounded-full animate-spin" />
<span class="text-slate-400 text-sm">切换中...</span>
</div>
</div>
</main>
<!-- 更新通知 -->
<div style="display: none;">
<!-- Hack to keep UpdateNotification if needed, or move it to layout -->
</div>
</div>
</template>
<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { isElectron } from '@/utils/electronBridge'
import Sidebar from '@/components/Sidebar.vue'
import ViewPlaceholder from '@/components/ViewPlaceholder.vue'
// Props passed from parent (App.vue or Layout) can replace some local state if we want to lift state up.
// For now, I'll keep local state to minimize refactor risk, assuming this component is mounted once and kept alive.
// BUT, App.vue passed some props like `accountGroups` etc.
// Wait, in App.vue these were local state. I needs to move the logic here or keep it in App.vue and pass via props.
// To keep valid functionality, I will copy the logic 1:1 here.
const props = defineProps(['accountGroups', 'rotationStatus', 'greetingStats', 'automationLogs'])
const emit = defineEmits(['go-back', 'stop-all', 'request-config-load'])
// Constants
const USER_KEY = 'user_data'
const CONFIG_KEY = 'autoDm_runConfig'
// State
const currentTab = ref('A')
const isLoading = ref(false)
const automationStatus = ref({})
const selectedViewId = ref(null)
const viewAccountMap = ref({})
// We use props for these now? Or still load config here?
// The original App.vue loaded config.
// Let's use the props if provided, otherwise load locally?
// Actually App.vue code showed `loadConfig` was called on mounted.
// Since `accountGroups` is passed as prop in my new design (implied by previous thought), I should use it.
// BUT, to be safe and independent:
const internalAccountGroups = ref([])
// use props if available, else local
const effectiveAccountGroups = computed(() => props.accountGroups || internalAccountGroups.value)
// Computed
const tabs = computed(() => [
{ id: 'A', label: effectiveAccountGroups.value[0]?.name || 'Tab A', viewIds: [1, 2, 3] },
{ id: 'B', label: effectiveAccountGroups.value[1]?.name || 'Tab B', viewIds: [4, 5, 6] },
{ id: 'C', label: effectiveAccountGroups.value[2]?.name || 'Tab C', viewIds: [7, 8, 9] }
])
const currentTabConfig = computed(() => tabs.value.find(t => t.id === currentTab.value) || tabs.value[0])
// Lifecycle
onMounted(() => {
// If props are not provided (standalone usage), load config
if (!props.accountGroups) {
loadConfig()
} else {
// Build viewAccountMap from props
buildViewMap(props.accountGroups)
}
// Listeners specific to browser view
// ...
})
// Original loadConfig logic
const loadConfig = () => {
try {
const savedConfig = localStorage.getItem(CONFIG_KEY)
if (savedConfig) {
const config = JSON.parse(savedConfig)
internalAccountGroups.value = config.accountGroups || []
buildViewMap(config.accountGroups)
}
} catch { }
}
const buildViewMap = (groups) => {
const map = {}
if (!groups) return
groups.forEach((group, groupIndex) => {
const viewsPerGroup = 3
group.accounts.forEach((account, accIndex) => {
const viewId = groupIndex * viewsPerGroup + accIndex + 1
if (viewId <= 9 && account.email && account.pwd) {
map[viewId] = { ...account, group: group.name }
}
})
})
viewAccountMap.value = map
}
watch(() => props.accountGroups, (newVal) => {
if (newVal) buildViewMap(newVal)
})
// Actions
const handleTabSwitch = async (tab) => {
if (tab === currentTab.value) return
if (isElectron()) {
try {
const result = await window.electronAPI.switchTab(tab)
if (result.success) {
currentTab.value = tab
selectedViewId.value = null
}
} catch (error) {
console.error('切换标签失败:', error)
}
} else {
currentTab.value = tab
selectedViewId.value = null
}
}
const handleViewSwitch = async (viewId) => {
selectedViewId.value = viewId
if (isElectron()) {
await window.electronAPI.switchToView(viewId)
}
}
const handleGoToConfig = async () => {
emit('go-back')
}
const handleStopAll = async () => {
emit('stop-all')
}
</script>

View File

@@ -0,0 +1,560 @@
<template>
<div class="h-full w-full overflow-y-auto bg-gray-50 p-6">
<div class="bg-white dark:bg-slate-900 rounded-3xl shadow-sm border border-slate-100 dark:border-slate-800 p-6 h-full flex flex-col">
<!-- 顶部筛选区域 -->
<div class="mb-6 space-y-4">
<!-- 第一行主要筛选条件 -->
<div class="flex flex-wrap items-center justify-between gap-4">
<div class="flex items-center flex-wrap gap-4">
<el-checkbox v-model="queryFormData.isFilter" :label="$t('hostsList.filterPrivateUsers') || '过滤私密账号'" size="large"
class="!mr-0" />
<!-- Coins Input -->
<div class="flex flex-col gap-1">
<label class="text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1">
<span>💰</span> {{ $t('hostsList.coins') || '金币' }}
</label>
<div class="flex items-center gap-2">
<el-input v-model="queryFormData.coinMin" :placeholder="$t('hostsList.minCoins') || '最小'" style="width: 100px"
type="number" :disabled="streamdialogVisibletext || isRunnings" />
<span class="text-slate-300">/</span>
<el-input v-model="queryFormData.coinMax" :placeholder="$t('hostsList.maxCoins') || '最大'" style="width: 100px"
type="number" :disabled="streamdialogVisibletext || isRunnings" />
</div>
</div>
<!-- Level Input -->
<div class="flex flex-col gap-1">
<label class="text-xs font-bold text-slate-400 uppercase tracking-wider flex items-center gap-1">
<span>📊</span> {{ $t('hostsList.level') || '等级' }}
</label>
<div class="flex items-center gap-2">
<el-input v-model="queryFormData.levelMin" :placeholder="$t('hostsList.minLevel') || '最小'" style="width: 100px"
type="number" :disabled="streamdialogVisibletext || isRunnings" />
<span class="text-slate-300">/</span>
<el-input v-model="queryFormData.levelMax" :placeholder="$t('hostsList.maxLevel') || '最大'" style="width: 100px"
type="number" :disabled="streamdialogVisibletext || isRunnings" />
</div>
</div>
</div>
<!-- Info Pill -->
<div class="bg-white/60 border border-slate-200 rounded-full px-5 py-2 flex items-center gap-4 text-sm shadow-sm">
<span class="font-medium text-slate-500">{{ $t('hostsList.runningTime') || '运行时间' }}:</span>
<span class="font-mono font-bold text-slate-700">
{{ String(hourstuo).padStart(2, '0') }}:{{ String(minutestuo).padStart(2, '0') }}:{{ String(secondstuo).padStart(2, '0') }}
</span>
<div class="w-px h-4 bg-slate-200"></div>
<span class="font-medium text-slate-500">{{ $t('hostsList.total') || '总数' }}:</span>
<span class="font-bold text-slate-700">{{ getBrotherInfodata.total }}</span>
<div class="w-px h-4 bg-slate-200"></div>
<span class="font-medium text-slate-500">{{ $t('hostsList.valid') || '有效' }}:</span>
<span class="font-bold text-primary">{{ getBrotherInfodata.valid }}</span>
</div>
<!-- Right Action Buttons -->
<div class="flex items-center gap-3">
<el-button @click="streamdialogVisible = true" :disabled="isRunnings" type="primary"
class="!rounded-xl !font-semibold shadow-lg shadow-blue-500/20">
<span class="mr-1">📍</span>
{{ streamdialogVisibletext ? ($t('hostsList.specifiedRooms') || '已指定') : ($t('hostsList.specifyRooms') || '指定直播间') }}
</el-button>
<el-button v-show="!isRunnings" type="success" @click="getBigBrother"
class="!rounded-xl !font-semibold shadow-lg shadow-emerald-500/20">
{{ $t('hostsList.start') || '开始' }}
</el-button>
<el-button v-show="isRunnings" type="danger" @click="BigBrotherstop"
class="!rounded-xl !font-semibold shadow-lg shadow-red-500/20">
{{ $t('hostsList.end') || '结束' }}
</el-button>
</div>
</div>
<div class="h-px bg-slate-100 w-full"></div>
<!-- 第二行搜索和操作 -->
<div class="flex flex-wrap items-center justify-between gap-4">
<div class="flex items-center gap-4">
<el-select v-model="searchForm.region" filterable :placeholder="$t('hostsList.selectCountry') || '选择国家'" style="width: 160px">
<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') || '大哥ID'" style="width: 180px" clearable>
<template #prefix>
<span class="font-semibold text-slate-400">@</span>
</template>
</el-input>
<el-button @click="serch">
<span class="mr-1">🔍</span> {{ $t('hostsList.search') || '搜索' }}
</el-button>
<el-button @click="reset">
<span class="mr-1">🔄</span> {{ $t('hostsList.reset') || '重置' }}
</el-button>
<el-button :disabled="tableData.length == 0" @click="exportList">
<span class="mr-1">📥</span> {{ $t('hostsList.exportExcel') || '导出' }}
</el-button>
<el-button @click="filterdialogVisible = true">
<span class="mr-1"></span> {{ $t('hostsList.moreFilters') || '更多筛选' }}
</el-button>
<el-button @click="openTikTok">
<span class="mr-1">🎵</span> {{ $t('hostsList.openTikTok') || '打开TK' }}
</el-button>
</div>
<!-- Status Info -->
<div class="bg-slate-50 px-4 py-2 rounded-xl border border-slate-100 text-sm">
<span class="text-slate-500">{{ $t('hostsList.currentNetwork') || '当前网络' }}:</span>
<span class="ml-2 font-bold text-primary">{{ countryData }}</span>
</div>
</div>
</div>
<!-- 表格区域 -->
<div class="flex-1 overflow-hidden border border-slate-100 rounded-xl">
<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') || 'ID'" min-width="120">
<template #default="scope">
<div class="text-primary font-semibold cursor-pointer hover:underline" @click="openHTML(scope.row.displayId)">
{{ scope.row.displayId }}
</div>
</template>
</el-table-column>
<el-table-column prop="hostDisplayId" :label="$t('hostsList.hostId') || '主播ID'" min-width="120">
<template #default="scope">
<div class="text-primary font-semibold cursor-pointer hover:underline" @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="120">
</el-table-column>
</el-table>
</div>
<!-- 分页区域 -->
<div class="mt-4 flex justify-between items-center">
<div></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" :title="$t('hostsList.moreFilters') || '更多筛选'" width="700px">
<div class="space-y-4">
<div class="grid grid-cols-12 gap-4 items-center">
<div class="col-span-3 text-right text-gray-600">{{ $t('hostsList.time') || '时间' }}</div>
<div class="col-span-9">
<el-date-picker v-model="createTimes" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
:placeholder="$t('hostsList.selectTime') || '选择时间'" class="w-full" />
</div>
</div>
<div v-for="(field, index) in fields" :key="index" class="grid grid-cols-12 gap-4 items-center">
<div class="col-span-3 text-right text-gray-600">{{ field.label }}</div>
<div class="col-span-9 flex gap-2 items-center">
<el-input type="number" v-model.number="searchForm[field.minModel]" :placeholder="$t('hostsList.minValue') || '最小值'" />
<span>-</span>
<el-input type="number" v-model.number="searchForm[field.maxModel]" :placeholder="$t('hostsList.maxValue') || '最大值'" />
</div>
</div>
<div class="grid grid-cols-12 gap-4 items-center">
<div class="col-span-3 text-right text-gray-600">{{ $t('hostsList.sort') || '排序' }}</div>
<div class="col-span-9 flex gap-4">
<el-select v-model="sortData.sortName" class="w-full">
<el-option v-for="item in sortNameOptions" :key="item.type" :label="item.label" :value="item.type" />
</el-select>
<el-select v-model="sortData.sort" class="w-full">
<el-option :label="$t('hostsList.ascending') || '升序'" value="asc" />
<el-option :label="$t('hostsList.descending') || '降序'" value="desc" />
</el-select>
</div>
</div>
</div>
<template #footer>
<span class="dialog-footer">
<el-button @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" :title="$t('hostsList.specifyRooms') || '指定直播间'" width="600px">
<el-input v-model="textarea" :rows="10" type="textarea"
:placeholder="$t('hostsList.enterRoomIds') || '请输入房间ID每行一个'" @input="handleInput" />
<template #footer>
<div class="flex justify-end gap-2">
<el-button @click="specifyCancel">{{ $t('hostsList.cancelSpecify') || '取消指定' }}</el-button>
<el-button @click="specifyreset">{{ $t('hostsList.specifyReset') || '重置' }}</el-button>
<el-button type="primary" @click="specifyClick">{{ $t('hostsList.specifyConfirm') || '确认' }}</el-button>
<el-button type="success" @click="specifyClickStart">{{ $t('hostsList.specifyStart') || '确认并开始' }}</el-button>
</div>
</template>
</el-dialog>
</div>
</template>
<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { usePythonBridge } from "@/utils/pythonBridge";
import { getUser } from "@/utils/storage";
import { getCountryName } from "@/utils/countryUtil";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { useI18n } from 'vue-i18n';
// Mock API calls if not present
// Ideally we should import these from api file, but for simplicity I will mock them or use empty callbacks
// if the user hasn't provided the api file content.
// Based on hostsList.vue reading, it uses `tkhostdata` from `@/api/account`.
// I will attempt to import, but if it fails I might need to create it.
// Assuming verify step will catch missing API functions.
import { tkhostdata, getCountryinfo } from "@/api/account";
const { t, locale } = useI18n();
// Component State
const queryFormData = ref({
coinMin: "",
coinMax: "",
levelMin: "",
levelMax: "",
isFilter: false,
isRunning: false,
anchor_ids: [],
});
const searchForm = ref({});
const createTimes = ref([]);
const page = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref([]);
const loading = ref(false);
const sortData = ref({ sortName: "createTime", sort: "desc" });
const hourstuo = ref(0);
const minutestuo = ref(0);
const secondstuo = ref(0);
const startTime = ref(null);
const getBrotherInfodata = ref({
total: 0,
valid: 0,
});
const streamdialogVisible = ref(false);
const streamdialogVisibletext = ref(false);
const filterdialogVisible = ref(false);
const textarea = ref("");
const countryData = ref("");
const userInfo = ref({});
const options = ref([]);
const labelList = ref([
{ paramCode: "userIdStr", paramCodeMeaning: t("hostsList.userId") || "用户ID" },
{ 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 fields = [
{ label: t("hostsList.level") || "等级", minModel: "levelMin", maxModel: "levelMax" },
];
const 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" },
]);
// Bridge
const {
givePyAnchorId,
exportToExcel,
loginTikTok,
controlTask,
getBrotherInfo,
Specifystreaming,
readSetInfos,
storageSetInfos,
openAnchorIdRooms,
setClipboards,
} = usePythonBridge();
const isRunnings = ref(false);
const timerId = ref(null);
// Lifecycle
onMounted(async () => {
userInfo.value = getUser() || { tenantId: 0, id: 0 };
getIpInfo();
getCountry();
getlist();
const savedSettings = await readSetInfos({ key: "UserSettings" });
if (savedSettings) {
try {
// savedSettings might be object already if backend returned object, or string
const data = typeof savedSettings === 'string' ? JSON.parse(savedSettings) : savedSettings;
queryFormData.value = data;
if (data.anchor_ids && data.anchor_ids.length > 0) {
streamdialogVisibletext.value = true;
textarea.value = data.anchor_ids.join("\n");
}
} catch(e) { console.error("Error parsing settings", e); }
}
});
onBeforeUnmount(() => {
stopTimerfun();
if (timerId.value) clearInterval(timerId.value);
});
// Methods
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}`;
}
const getlist = () => {
loading.value = true;
// Use API if available, else mock
if (typeof tkhostdata === 'function') {
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 && res.records) {
total.value = Number(res.total);
tableData.value = res.records.map((item) => ({
...item,
createTime: formatDate(new Date(item.createTime)),
}));
}
}).catch(e => {
console.log("Mocking data due to error", e);
loading.value = false;
// Mock data
tableData.value = [];
});
} else {
console.warn("tkhostdata API not found");
loading.value = false;
}
};
function getBigBrother() {
const settingData = { ...queryFormData.value, tenantId: userInfo.value.tenantId, region: countryData.value };
// Save settings
storageSetInfos({ key: "UserSettings", data: settingData });
controlTask(JSON.stringify(settingData)).then(() => {
isRunnings.value = true;
queryFormData.value.isRunning = true;
startTimerfun();
// Start polling stats
timerId.value = setInterval(() => {
getBrotherInfo().then(res => {
getBrotherInfodata.value = res;
});
}, 1000);
});
}
function BigBrotherstop() {
stopTimerfun();
isRunnings.value = false;
queryFormData.value.isRunning = false;
if (timerId.value) {
clearInterval(timerId.value);
timerId.value = null;
}
// Send stop command (logic in controlTask might handle toggle or we need stop logic)
// Original uses controlTask to START, but maybe stop logic is handled by setting isRunning=false in payload?
// Original code calls controlTask with payload again.
const settingData = { ...queryFormData.value, tenantId: userInfo.value.tenantId, region: countryData.value, isRunning: false };
controlTask(JSON.stringify(settingData));
}
function startTimerfun() {
stopTimerfun();
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() {
if (startTime.value) clearInterval(startTime.value);
}
// Specify Room Logic
const MAX_SPECIFY_LINES = 50;
function handleInput(value) {
if (typeof value !== "string") return;
const lines = value.split("\n");
if (lines.length > MAX_SPECIFY_LINES) {
textarea.value = lines.slice(0, MAX_SPECIFY_LINES).join("\n");
}
}
function specifyClickStart() {
if (!textarea.value.trim()) {
ElMessage.error(t('hostsList.enterRoomId') || "请输入房间ID");
return;
}
queryFormData.value.anchor_ids = textarea.value.split("\n").filter(id => id.trim());
streamdialogVisible.value = false;
streamdialogVisibletext.value = true;
getBigBrother();
}
function specifyClick() {
if (!textarea.value.trim()) {
streamdialogVisibletext.value = false;
queryFormData.value.anchor_ids = [];
} else {
streamdialogVisibletext.value = true;
queryFormData.value.anchor_ids = textarea.value.split("\n").filter(id => id.trim());
}
streamdialogVisible.value = false;
}
function specifyCancel() {
streamdialogVisible.value = false;
streamdialogVisibletext.value = false;
queryFormData.value.anchor_ids = [];
textarea.value = "";
}
function specifyreset() {
textarea.value = "";
}
// Table / Filter Logic
function serch() {
page.value = 1;
getlist();
}
function reset() {
searchForm.value = {};
createTimes.value = [];
sortData.value = { sortName: "createTime", sort: "desc" };
getlist();
}
function handelClick() {
filterdialogVisible.value = false;
getlist();
}
function handleSizeChange(val) {
pageSize.value = val;
getlist();
}
function handleCurrentChange(val) {
page.value = val;
getlist();
}
function handleSelectionChange(val) {
//
}
function openHTML(id) {
givePyAnchorId(id);
}
function handleLongPress(id) {
openAnchorIdRooms(id);
}
function handleCellDbClick(row, column, cell) {
const text = cell?.textContent?.trim();
if (text) {
setClipboards(text).then(() => ElMessage.success("Copied"));
}
}
function exportList() {
exportToExcel(tableData.value);
}
function openTikTok() {
loginTikTok();
}
// IP / Country
const getIpInfo = async () => {
try {
const response = await fetch("https://ipapi.co/json/");
if (response.ok) {
const data = await response.json();
countryData.value = getCountryName(data.country);
}
} catch {}
};
function getCountry() {
if (typeof getCountryinfo === 'function') {
getCountryinfo({})
.then((res) => {
res.forEach((item) => {
if (item.countryGroupName) {
options.value.push({ value: item.countryGroupName, label: item.countryGroupName });
}
});
})
.catch(() => {});
}
}
</script>

500
src/views/tk/HostsList.vue Normal file
View File

@@ -0,0 +1,500 @@
<template>
<div class="bg-white dark:bg-slate-50 rounded-3xl shadow-2xl flex flex-col overflow-hidden h-full">
<!-- Header -->
<header class="px-8 py-6 border-b border-slate-100 dark:border-slate-200/60 bg-white">
<div class="flex flex-wrap items-center gap-4">
<div class="relative flex-1 min-w-[200px]">
<select v-model="searchForm.country"
class="w-full bg-slate-50 border-none rounded-xl py-3 pl-4 pr-10 text-sm text-slate-600 appearance-none focus:ring-2 focus:ring-primary/20 shadow-soft-inner outline-none">
<option value="">{{ $t('hostList.selectAll') }}</option>
<option v-for="item in options" :key="item.value" :value="item.value">{{ item.label }}</option>
</select>
<span
class="material-icons-round absolute right-3 top-1/2 -translate-y-1/2 text-slate-400 pointer-events-none">expand_more</span>
</div>
<div class="relative flex-1 min-w-[200px]">
<span
class="material-icons-round absolute left-3 top-1/2 -translate-y-1/2 text-slate-400 text-sm pointer-events-none">calendar_today</span>
<input ref="dateInput" v-model="searchForm.createTime" type="date" @click="openDatePicker"
class="w-full bg-slate-50 border-none rounded-xl py-3 pl-10 pr-4 text-sm text-slate-600 focus:ring-2 focus:ring-primary/20 shadow-soft-inner outline-none cursor-pointer" />
</div>
<div class="relative flex-[1.5] min-w-[240px]">
<input v-model="searchForm.hostsId"
class="w-full bg-slate-50 border-none rounded-xl py-3 px-4 text-sm text-slate-600 focus:ring-2 focus:ring-primary/20 shadow-soft-inner outline-none"
:placeholder="$t('hostList.placeHostId')" />
</div>
<div class="flex items-center gap-2 ml-auto">
<button @click="serch"
class="bg-blue-600 hover:bg-blue-700 text-white px-8 py-3 rounded-xl font-medium text-sm transition-all shadow-lg shadow-primary/20 flex items-center gap-2">
<span class="material-icons-round text-sm">search</span>
{{ $t('hostList.query') }}
</button>
<button @click="filterdialogVisible = true"
class="bg-slate-100 hover:bg-slate-200 text-slate-600 p-3 rounded-xl transition-all">
<span class="material-icons-round">tune</span>
</button>
</div>
</div>
</header>
<!-- Table -->
<div class="flex-1 flex flex-col overflow-hidden relative" style="padding-left: 20px;">
<div v-if="loading" class="absolute inset-0 bg-white/50 z-30 flex items-center justify-center">
<span class="material-icons-round animate-spin text-primary text-4xl">sync</span>
</div>
<!-- Table with Fixed Layout -->
<div class="flex-1 overflow-auto">
<table class="w-full text-left" style="table-layout: fixed; min-width: 1000px;">
<colgroup>
<col style="width: 12%;">
<col style="width: 5%;">
<col style="width: 8%;">
<col style="width: 8%;">
<col style="width: 6%;">
<col style="width: 10%;">
<col style="width: 8%;">
<col style="width: 8%;">
<col style="width: 7%;">
<col style="width: 7%;">
<col style="width: 7%;">
<col style="width: 7%;">
</colgroup>
<thead class="bg-white sticky top-0 z-10">
<tr class="text-slate-400 text-xs font-semibold uppercase tracking-wider border-b border-slate-100">
<th class="py-3 px-2 font-semibold bg-white">{{ $t('hostList.hostId') }}</th>
<th class="py-3 px-2 font-semibold bg-white">{{ $t('hostList.grade') }}</th>
<th class="py-3 px-2 font-semibold bg-white">{{ $t('hostList.invitationType') }}</th>
<th class="py-3 px-2 font-semibold bg-white">{{ $t('hostList.liveSessions') }}</th>
<th class="py-3 px-2 font-semibold bg-white">{{ $t('hostList.country') }}</th>
<th class="py-3 px-2 font-semibold bg-white">{{ $t('hostList.creationTime') }}</th>
<th class="py-3 px-2 font-semibold bg-white">{{ $t('hostList.anchorcoins') }}</th>
<th class="py-3 px-2 font-semibold bg-white">{{ $t('hostList.yesterdayGoldCoins') }}</th>
<th class="py-3 px-2 font-semibold bg-white">{{ $t('hostList.fansNum') }}</th>
<th class="py-3 px-2 font-semibold bg-white">{{ $t('hostList.followersNum') }}</th>
<th class="py-3 px-2 font-semibold bg-white">{{ $t('hostList.onlineFans') }}</th>
<th class="py-3 px-2 font-semibold bg-white">{{ $t('hostList.anchorType') }}</th>
</tr>
</thead>
<tbody class="text-sm text-slate-600">
<tr v-if="tableData.length === 0" class="text-center">
<td colspan="14" class="py-10 text-slate-400">暂无数据</td>
</tr>
<tr v-for="row in tableData" :key="row.hostId" class="group hover:bg-slate-50/80 transition-colors">
<!-- Host ID -->
<td class="py-4 px-2 border-b border-slate-50 group-last:border-none">
<span @click="openHTML(row.hostId)"
class="font-medium text-slate-900 border-b border-transparent group-hover:border-primary/30 transition-all cursor-pointer hover:text-blue-600">
{{ row.hostId }}
</span>
</td>
<!-- Level -->
<td class="py-4 px-2 border-b border-slate-50 group-last:border-none">
{{ row.hostlevel }}
</td>
<!-- Invitation Type -->
<td class="py-4 px-2 border-b border-slate-50 group-last:border-none">
<span class="px-3 py-1 text-[10px] font-bold uppercase rounded-full"
:class="row.invitationType == 1 ? 'bg-green-50 text-green-600' : 'bg-amber-50 text-amber-600'">
{{ row.invitationType == 1 ? $t('hostList.invitationType1') : $t('hostList.invitationType2') }}
</span>
</td>
<!-- Data Buttons -->
<td class="py-4 px-2 border-b border-slate-50 group-last:border-none">
<div class="flex gap-2">
<button
@click="getliveHost(row.hostId)"
class="px-3 py-1.5 bg-blue-50 text-blue-600 hover:bg-blue-600 hover:text-white rounded-lg text-xs font-medium transition-all"
>
{{ $t('hostList.viewSessions') }}
</button>
</div>
</td>
<!-- Country -->
<td class="py-4 px-2 border-b border-slate-50 group-last:border-none">
{{ row.country }}
</td>
<!-- Time -->
<td class="py-4 px-2 border-b border-slate-50 group-last:border-none">
<div class="flex flex-col">
<span>{{ formatTimeOnlyDate(row.createTime) }}</span>
<span class="text-[10px] text-slate-400">{{ formatTimeOnlyTime(row.createTime) }}</span>
</div>
</td>
<!-- Coins -->
<td class="py-4 px-2 border-b border-slate-50 group-last:border-none font-semibold text-slate-900">
{{ row.hostsCoins }}
</td>
<!-- Yesterday Coins -->
<td class="py-4 px-2 border-b border-slate-50 group-last:border-none">
{{ row.yesterdayCoins }}
</td>
<!-- Fans -->
<td class="py-4 px-2 border-b border-slate-50 group-last:border-none">
{{ row.fans }}
</td>
<!-- Followers -->
<td class="py-4 px-2 border-b border-slate-50 group-last:border-none">
{{ row.fllowernum }}
</td>
<!-- Online Fans -->
<td class="py-4 px-2 border-b border-slate-50 group-last:border-none">
{{ row.onlineFans }}
</td>
<!-- Host Kind -->
<td class="py-4 px-2 border-b border-slate-50 group-last:border-none">
{{ row.hostsKind }}
</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- Footer / Pagination -->
<footer
class="px-8 py-6 border-t border-slate-100 dark:border-slate-200/60 bg-white flex flex-wrap items-center justify-between gap-4">
<div class="flex items-center gap-4">
<div class="relative">
<select v-model="pageSize" @change="handleSizeChange"
class="bg-slate-50 border-none rounded-lg py-2 pl-4 pr-10 text-sm text-slate-600 appearance-none focus:ring-2 focus:ring-primary/20 shadow-soft-inner outline-none">
<option :value="10">10/page</option>
<option :value="20">20/page</option>
<option :value="50">50/page</option>
<option :value="100">100/page</option>
</select>
<span
class="material-icons-round absolute right-2 top-1/2 -translate-y-1/2 text-slate-400 text-sm pointer-events-none">expand_more</span>
</div>
<span class="text-xs text-slate-400 font-medium">总条数: <span class="text-blue-600">{{ total }}</span></span>
</div>
<div class="flex items-center gap-1">
<button @click="changePage(page - 1)" :disabled="page <= 1"
class="p-2 text-slate-400 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-50">
<span class="material-icons-round text-lg">chevron_left</span>
</button>
<!-- Page Numbers -->
<template v-for="(p, index) in paginationPages" :key="index">
<span v-if="p === '...'" class="w-8 h-8 flex items-center justify-center text-slate-400 text-sm">...</span>
<button v-else @click="changePage(p)" class="w-8 h-8 rounded-lg text-xs font-bold transition-all"
:class="p === page ? 'bg-slate-900 text-white shadow-md' : 'text-slate-600 hover:bg-slate-100'">
{{ p }}
</button>
</template>
<button @click="changePage(page + 1)" :disabled="page >= totalPages"
class="p-2 text-slate-400 hover:bg-slate-100 rounded-lg transition-colors disabled:opacity-50">
<span class="material-icons-round text-lg">chevron_right</span>
</button>
</div>
</footer>
<!-- Filter Dialog (Preserved Element Plus) -->
<el-dialog v-model="filterdialogVisible" width="800px" :before-close="handleClose">
<el-row v-for="(field, index) in fields" :key="index" :gutter="20" style="margin-bottom: 10px">
<el-col :span="4">
<div style="height: 100%; padding-top: 10px" class="flex items-center justify-center">
{{ field.label }}
</div>
</el-col>
<el-col :span="10">
<div><label class="text-sm text-slate-500 mb-1 block">{{ $t('hostList.min') }}</label></div>
<el-input type="number" :oninput="'if(value.length>9)value=value.slice(0,9)'"
v-model.number="searchForm[field.minModel]" :placeholder="$t('hostList.placeMin')" />
</el-col>
<el-col :span="10">
<div><label class="text-sm text-slate-500 mb-1 block">{{ $t('hostList.max') }}</label></div>
<el-input type="number" :oninput="'if(value.length>9)value=value.slice(0,9)'"
v-model.number="searchForm[field.maxModel]" :placeholder="$t('hostList.placeMax')" />
</el-col>
</el-row>
<el-row :gutter="20" class="mt-4">
<el-col :span="4">
<div style="height: 100%;padding-top: 10px;" class="flex items-center justify-center">
{{ $t('hostList.sort') }}
</div>
</el-col>
<el-col :span="10">
<div><label class="text-sm text-slate-500 mb-1 block">{{ $t('hostList.sortType') }}</label></div>
<el-select v-model="sortData.sortType" filterable :placeholder="$t('hostList.selectPlaceholder')"
class="w-full">
<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 class="text-sm text-slate-500 mb-1 block">{{ $t('hostList.ascending') }}/{{
$t('hostList.descending')
}}</label></div>
<el-select v-model="sortData.sortForm" filterable :placeholder="$t('hostList.selectPlaceholder')"
class="w-full">
<el-option
v-for="item in [{ label: $t('hostList.ascending'), value: 'asc' }, { label: $t('hostList.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 @click="reset">
{{ $t('hostList.reset') }}
</el-button>
<el-button type="primary" @click="handelClick" class="bg-blue-600">
{{ $t('hostList.sure') }}
</el-button>
</span>
</template>
</el-dialog>
<!-- Dialogs -->
<LiveRecordDialog v-model:modelValue="liveDetailDialogVisible" :rows="liveDetailRecords"
@select="handleLiveSelect" />
</div>
</template>
<script setup>
import { tkhostdata, getCountryinfo, liveHostDetail } from '@/api/account';
import { usePythonBridge } from '@/utils/pythonBridge'
import { getUser } from '@/utils/storage'
import { ref, reactive, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n'
import LiveRecordDialog from '@/components/LiveRecordDialog.vue'
const { t } = useI18n()
const loading = ref(false)
const dateInput = ref(null)
const { givePyAnchorId, exportToExcel } = usePythonBridge();
const userInfo = ref(getUser())
const tableData = ref([])
const searchForm = ref({
country: '',
createTime: '',
hostsId: '',
fansMin: null, fansMax: null,
onlineFansMin: null, onlineFansMax: null,
hostsCoinsMin: null, hostsCoinsMax: null,
fllowernumMin: null, fllowernumMax: null
})
const fields = [
{ label: t('hostList.fansNum'), minModel: 'fansMin', maxModel: 'fansMax' },
{ label: t('hostList.onlineFans'), minModel: 'onlineFansMin', maxModel: 'onlineFansMax' },
{ label: t('hostList.anchorcoins'), minModel: 'hostsCoinsMin', maxModel: 'hostsCoinsMax' },
{ label: t('hostList.followersNum'), minModel: 'fllowernumMin', maxModel: 'fllowernumMax' },
]
let sortData = ref({ sortForm: 'desc', sortType: "createTime" })
let sortNameOptions = ref([
{ label: t('hostList.creationTime'), type: 'createTime' },
{ label: t('hostList.anchorcoins'), type: 'hostsCoins' },
{ label: t('hostList.fansNum'), type: 'fans' },
{ label: t('hostList.yesterdayGoldCoins'), type: 'yesterdayCoins' },
{ label: t('hostList.onlineFans'), type: 'onlineFans' },
{ label: t('hostList.followersNum'), type: 'fllowernum' },
])
let filterdialogVisible = ref(false)
let liveDetailDialogVisible = ref(false)
let liveDetailRecords = ref([])
let pageSize = ref(10)
let page = ref(1)
let total = ref(0)
let options = ref([])
onMounted(() => {
getCountry();
getlist();
})
function serch() {
page.value = 1
getlist();
}
// 手动打开日期选择器
function openDatePicker(event) {
const input = event.target;
if (input && typeof input.showPicker === 'function') {
try {
input.showPicker();
} catch (e) {
input.focus();
}
}
}
function handleSizeChange() {
page.value = 1
getlist();
}
function changePage(newPage) {
if (newPage < 1 || (newPage - 1) * pageSize.value >= total.value) return
page.value = newPage
getlist()
}
// 计算总页数
const totalPages = computed(() => Math.ceil(total.value / pageSize.value))
// 生成分页页码数组
const paginationPages = computed(() => {
const current = page.value
const totalP = totalPages.value
const pages = []
if (totalP <= 7) {
for (let i = 1; i <= totalP; i++) {
pages.push(i)
}
} else {
pages.push(1)
if (current > 4) {
pages.push('...')
}
let start = Math.max(2, current - 2)
let end = Math.min(totalP - 1, current + 2)
if (current <= 4) end = Math.min(5, totalP - 1)
if (current >= totalP - 3) start = Math.max(totalP - 4, 2)
for (let i = start; i <= end; i++) {
pages.push(i)
}
if (current < totalP - 3) {
pages.push('...')
}
if (totalP > 1) {
pages.push(totalP)
}
}
return pages
})
const getlist = () => {
loading.value = true
// Fix: Check if userInfo is valid before call
const tenantId = userInfo.value ? Number(userInfo.value.tenantId) : 0
tkhostdata({
tenantId: tenantId,
sort: sortData.value.sortForm,
sortName: sortData.value.sortType,
"current": page.value,
"pageSize": pageSize.value,
...searchForm.value,
}).then(res => {
loading.value = false
if (res) {
console.log('主播列表', res)
total.value = Number(res.total)
tableData.value = res.records.map(item => ({
hostId: item.hostsId,
hostlevel: item.hostsLevel,
country: item.country,
createTime: item.createTime,
fans: item.fans,
fllowernum: item.fllowernum,
hostsCoins: item.hostsCoins,
hostsKind: item.hostsKind,
onlineFans: item.onlineFans,
yesterdayCoins: item.yesterdayCoins,
belongBy: item.belongBy,
useable: item.useable,
invitationType: item.invitationType,
}));
}
}).catch(() => {
loading.value = false
})
}
function handelClick() {
filterdialogVisible.value = false
getlist()
}
function reset() {
searchForm.value.fansMin = null
searchForm.value.fansMax = null
searchForm.value.onlineFansMin = null
searchForm.value.onlineFansMax = null
searchForm.value.hostsCoinsMin = null
searchForm.value.hostsCoinsMax = null
searchForm.value.fllowernumMin = null
searchForm.value.fllowernumMax = null
}
function handleClose(done) {
done()
}
function getliveHost(hostId) {
liveHostDetail({
"hostsId": hostId,
"tenantId": userInfo.value?.tenantId
}).then(res => {
const detailList = Array.isArray(res) ? res : (res?.records || [])
liveDetailRecords.value = detailList
liveDetailDialogVisible.value = true
})
}
function handleLiveSelect(row) {
liveDetailDialogVisible.value = false
}
function openHTML(id) {
givePyAnchorId(id)
}
function getCountry() {
getCountryinfo({}).then(res => {
if(res) {
res.forEach(item => {
if (item.countryGroupName) {
options.value.push({ value: item.countryGroupName, label: item.countryGroupName })
}
})
}
})
}
function formatTimeOnlyDate(val) {
if (!val) return ''
return val.split(' ')[0] || val
}
function formatTimeOnlyTime(val) {
if (!val) return ''
return val.split(' ')[1] || ''
}
</script>
<style scoped>
/* Scoped styles mainly for Element Plus overrides if needed */
</style>

View File

@@ -0,0 +1,787 @@
<template>
<div class="h-full w-full overflow-y-auto bg-gray-50 p-6">
<div class="container mx-auto">
<div class="grid grid-cols-1 lg:grid-cols-12 gap-4 mb-4">
<!-- Stat Cards -->
<!-- 总数量 (较小) -->
<div
class="lg:col-span-2 bg-white dark:bg-slate-900 p-4 rounded-xl shadow-sm border border-slate-100 dark:border-slate-800">
<div class="flex items-center justify-between mb-1">
<span class="text-xs font-medium text-slate-500">{{ $t('workbenches.totalnumber') }}</span>
<span class="material-icons-round text-primary/40 text-lg">analytics</span>
</div>
<div class="text-xl font-bold text-slate-900 dark:text-white">{{ hostData.totalCount }}</div>
</div>
<!-- 新建主播 (较小) -->
<div
class="lg:col-span-2 bg-white dark:bg-slate-900 p-4 rounded-xl shadow-sm border border-slate-100 dark:border-slate-800">
<div class="flex items-center justify-between mb-1">
<span class="text-xs font-medium text-slate-500">{{ $t('workbenches.createHost') }}</span>
<span class="material-icons-round text-secondary/40 text-lg">person_add</span>
</div>
<div class="text-xl font-bold text-slate-900 dark:text-white">{{ hostData.validAnchorsCount }}</div>
</div>
<!-- 查询 (较小) -->
<div
class="lg:col-span-2 bg-white dark:bg-slate-900 p-4 rounded-xl shadow-sm border border-slate-100 dark:border-slate-800">
<div class="flex items-center justify-between mb-1">
<span class="text-xs font-medium text-slate-500">{{ $t('workbenches.query') }}</span>
<span class="material-icons-round text-amber-400/60 text-lg">search</span>
</div>
<div class="text-xl font-bold text-slate-900 dark:text-white">{{ hostData.checkedDataCount }}</div>
</div>
<!-- 邀请 (较大突出显示) -->
<div
class="lg:col-span-3 bg-gradient-to-br from-blue-600 to-blue-500 p-5 rounded-xl shadow-lg shadow-blue-500/20 text-white relative overflow-hidden">
<div class="absolute top-0 right-0 w-24 h-24 bg-white/10 rounded-full -translate-y-1/2 translate-x-1/2">
</div>
<div class="flex items-center justify-between mb-2 relative z-10">
<span class="text-sm font-medium text-white/80">{{ $t('workbenches.invite') }}</span>
<span class="material-icons-round text-white/60">mail_outline</span>
</div>
<div class="text-3xl font-bold text-white relative z-10">{{ hostData.canInvitationCount }}</div>
<div class="text-xs text-white/60 mt-1">可邀请主播</div>
</div>
<!-- 运行时间 (较大) -->
<div
class="lg:col-span-3 bg-white dark:bg-slate-900 p-5 rounded-xl shadow-sm border border-slate-100 dark:border-slate-800 flex flex-col justify-center">
<div class="flex items-center justify-between">
<div>
<span class="text-xs font-semibold text-slate-400 uppercase tracking-wider block mb-1">{{
$t('workbenches.runTime') }}</span>
<div class="text-2xl font-mono font-bold text-blue-600">{{ formattedTime }}</div>
</div>
<div class="flex items-center gap-2">
<span class="w-4 h-4 rounded-full" :class="isTkLoggedIn ? 'bg-emerald-500' : 'bg-red-500'"></span>
<button @click="openTK"
class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg text-sm font-semibold shadow-lg shadow-blue-600/25">
{{ $t('workbenches.openTK') }}
</button>
</div>
</div>
</div>
</div>
<!-- Guild Accounts -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-4">
<div v-for="(item, index) in 2" :key="index"
class="bg-white border border-slate-100 p-5 rounded-xl shadow-sm">
<div class="flex justify-between items-center mb-6">
<div class="flex items-center gap-2">
<span class="w-4 h-4 rounded-full"
:class="tkData[index].code == 1 ? 'bg-emerald-500' : 'bg-red-500'"></span>
<h3 class="font-bold text-slate-800 dark:text-white">{{ $t('workbenches.guildAccount') }} {{ index === 0
? 'A'
: 'B' }}</h3>
</div>
<span class=" text-slate-500" style="font-size: 17px;">{{ $t('workbenches.queriedNum') }}: {{
tkData[index].num }}</span>
</div>
<div class="space-y-4">
<div class="grid grid-cols-2 gap-4">
<div>
<label class="text-xs font-semibold text-slate-500 mb-1 block">{{ $t('workbenches.guildAccount')
}}</label>
<el-input v-model="tkData[index].account" :placeholder="$t('workbenches.guildAccountPlace')"
:disabled="!(tkData[index].code == 0 && !isLogin[index])" class="el-input-custom" />
</div>
<div>
<label class="text-xs font-semibold text-slate-500 mb-1 block">{{ $t('workbenches.guildPass') }}</label>
<el-input v-model="tkData[index].password" type="password" show-password
:placeholder="$t('workbenches.guildPassPlace')"
:disabled="!(tkData[index].code == 0 && !isLogin[index])" class="el-input-custom" />
</div>
</div>
<button @click="loginTK(index)" :disabled="!(tkData[index].code == 0 && !isLogin[index])"
class="w-full bg-slate-900 dark:bg-slate-700 hover:bg-black text-white py-2.5 rounded-lg font-medium transition-all disabled:opacity-50 disabled:cursor-not-allowed">
{{ $t('workbenches.loginBackend') }}
</button>
</div>
</div>
</div>
<!-- Configuration Panel -->
<div
class="bg-white dark:bg-slate-900 rounded-2xl shadow-sm border border-slate-100 dark:border-slate-800 overflow-hidden">
<div class="p-6 border-b border-slate-100 dark:border-slate-800 flex justify-between items-center">
<div class="flex items-center gap-3">
<div class="w-8 h-8 bg-slate-100 dark:bg-slate-800 rounded-lg flex items-center justify-center">
<span class="material-icons-round text-slate-600 dark:text-slate-400 text-lg">settings</span>
</div>
<h2 class="font-bold text-slate-800 dark:text-white">{{ $t('workbenchesSetup.workbenches') }}</h2>
</div>
<div class="flex items-center gap-4 text-sm">
<div class="text-slate-500">{{ $t('workbenchesSetup.network') }}: <span class="text-blue-600 font-bold">{{
locale
== 'zh' ? countryData : countryDataEN }}</span></div>
<div class="flex items-center gap-2">
<span class="text-slate-500">指定国家:</span>
<select v-model="country_info"
class="bg-slate-50 dark:bg-slate-800 border-none rounded-lg text-xs font-medium focus:ring-0">
<option value="全部">全部</option>
<option v-for="(item, index) in country_Lst" :key="index" :value="item">{{ item }}</option>
</select>
</div>
</div>
</div>
<div class="p-6">
<div class="grid grid-cols-1 lg:grid-cols-4 gap-6 mb-6">
<!-- Coins -->
<div>
<h4 class="text-sm font-bold text-slate-800 dark:text-white mb-4 flex items-center gap-2">
<span class="w-1 h-4 bg-blue-600 rounded-full"></span>
{{ $t('workbenchesSetup.setCoinsNum') }}
</h4>
<div class="space-y-3">
<div class="flex shadow-sm rounded-lg overflow-hidden border border-slate-200 dark:border-slate-700">
<span
class="bg-slate-50 dark:bg-slate-800 px-3 py-2 text-xs font-medium text-slate-500 w-28 flex items-center border-r border-slate-200 dark:border-slate-700">{{
$t('workbenchesSetup.minCoinsNum') }}</span>
<input
class="flex-1 px-4 py-2 text-sm bg-white dark:bg-slate-900 border-none outline-none focus:ring-0 disabled:bg-slate-100"
type="number" v-model="pyData.gold.min" :disabled="!pyData.isStart" />
</div>
<div class="flex shadow-sm rounded-lg overflow-hidden border border-slate-200 dark:border-slate-700">
<span
class="bg-slate-50 dark:bg-slate-800 px-3 py-2 text-xs font-medium text-slate-500 w-28 flex items-center border-r border-slate-200 dark:border-slate-700">{{
$t('workbenchesSetup.maxCoinsNum') }}</span>
<input
class="flex-1 px-4 py-2 text-sm bg-white dark:bg-slate-900 border-none outline-none focus:ring-0 disabled:bg-slate-100"
type="number" v-model="pyData.gold.max" :disabled="!pyData.isStart" />
</div>
</div>
</div>
<!-- Fans -->
<div>
<h4 class="text-sm font-bold text-slate-800 dark:text-white mb-4 flex items-center gap-2">
<span class="w-1 h-4 bg-secondary rounded-full"></span>
{{ $t('workbenchesSetup.setFansNum') }}
</h4>
<div class="space-y-3">
<div class="flex shadow-sm rounded-lg overflow-hidden border border-slate-200 dark:border-slate-700">
<span
class="bg-slate-50 dark:bg-slate-800 px-3 py-2 text-xs font-medium text-slate-500 w-28 flex items-center border-r border-slate-200 dark:border-slate-700">{{
$t('workbenchesSetup.minFansNum') }}</span>
<input
class="flex-1 px-4 py-2 text-sm bg-white dark:bg-slate-900 border-none outline-none focus:ring-0 disabled:bg-slate-100"
type="number" v-model="pyData.fans.min" :disabled="!pyData.isStart" />
</div>
<div class="flex shadow-sm rounded-lg overflow-hidden border border-slate-200 dark:border-slate-700">
<span
class="bg-slate-50 dark:bg-slate-800 px-3 py-2 text-xs font-medium text-slate-500 w-28 flex items-center border-r border-slate-200 dark:border-slate-700">{{
$t('workbenchesSetup.maxFansNum') }}</span>
<input
class="flex-1 px-4 py-2 text-sm bg-white dark:bg-slate-900 border-none outline-none focus:ring-0 disabled:bg-slate-100"
type="number" v-model="pyData.fans.max" :disabled="!pyData.isStart" />
</div>
</div>
</div>
<!-- Frequency -->
<div>
<h4 class="text-sm font-bold text-slate-800 dark:text-white mb-4 flex items-center gap-2">
<span class="w-1 h-4 bg-emerald-500 rounded-full"></span>
{{ $t('workbenchesSetup.setQuery') }}
</h4>
<div class="space-y-3">
<div class="flex shadow-sm rounded-lg overflow-hidden border border-slate-200 dark:border-slate-700">
<input
class="flex-1 px-4 py-2 text-sm bg-white dark:bg-slate-900 border-none outline-none focus:ring-0 disabled:bg-slate-100"
type="number" v-model="pyData.frequency.hour" :disabled="!pyData.isStart" />
<span
class="bg-slate-100 dark:bg-slate-800 px-3 py-2 text-xs font-medium text-slate-500 w-24 flex items-center justify-center border-l border-slate-200 dark:border-slate-700">{{
$t('workbenchesSetup.hour') }}</span>
</div>
<div class="flex shadow-sm rounded-lg overflow-hidden border border-slate-200 dark:border-slate-700">
<input
class="flex-1 px-4 py-2 text-sm bg-white dark:bg-slate-900 border-none outline-none focus:ring-0 disabled:bg-slate-100"
type="number" v-model="pyData.frequency.day" :disabled="!pyData.isStart" />
<span
class="bg-slate-100 dark:bg-slate-800 px-3 py-2 text-xs font-medium text-slate-500 w-24 flex items-center justify-center border-l border-slate-200 dark:border-slate-700">{{
$t('workbenchesSetup.hour24') }}</span>
</div>
</div>
</div>
<!-- Quantity Limit -->
<div>
<h4 class="text-sm font-bold text-slate-800 dark:text-white mb-4 flex items-center gap-2">
<span class="w-1 h-4 bg-orange-400 rounded-full"></span>
{{ $t('workbenchesSetup.setNum') }}
<span class="text-[10px] text-slate-400 font-normal ml-1">({{ $t('workbenchesSetup.prompt') }})</span>
</h4>
<div class="space-y-3">
<div class="flex gap-2">
<button @click="isLimit = true" :disabled="!pyData.isStart"
class="flex-1 px-3 py-2 text-xs font-semibold rounded-md border transition-colors"
:class="isLimit ? 'bg-blue-600 text-white border-blue-600' : 'bg-white text-slate-600 border-slate-200 hover:border-blue-600/50'">
{{ $t('workbenchesSetup.setHostNum') }}
</button>
<button @click="isLimit = false" :disabled="!pyData.isStart"
class="flex-1 px-3 py-2 text-xs font-semibold rounded-md border transition-colors"
:class="!isLimit ? 'bg-slate-500 text-white border-slate-500' : 'bg-white text-slate-600 border-slate-200 hover:border-slate-400'">
{{ $t('workbenchesSetup.unlimitedQuantity') }}
</button>
</div>
<div v-if="isLimit"
class="flex shadow-sm rounded-lg overflow-hidden border border-slate-200 dark:border-slate-700">
<input
class="flex-1 px-4 py-2 text-sm bg-white dark:bg-slate-900 border-none outline-none focus:ring-0 disabled:bg-slate-100"
type="number" v-model="hostNum" :disabled="!pyData.isStart" />
<span
class="bg-slate-100 dark:bg-slate-800 px-3 py-2 text-xs font-medium text-slate-500 w-16 flex items-center justify-center border-l border-slate-200 dark:border-slate-700">{{
$t('workbenchesSetup.num') }}</span>
</div>
</div>
</div>
</div>
<div
class="flex flex-col lg:flex-row items-center justify-between gap-6 pt-4 border-t border-slate-100 dark:border-slate-800">
<div class="flex items-center gap-6">
<div class="flex items-center gap-2 cursor-pointer group" @click="toggleFilter('filterGame')">
<span class="w-4 h-4 rounded border-2 flex items-center justify-center transition-all"
:class="pyData.filterGame ? 'bg-blue-600 border-blue-600' : 'bg-white border-slate-300'">
<span v-if="pyData.filterGame" class="material-icons-round text-white text-xs">check</span>
</span>
<span
class="text-sm text-slate-600 dark:text-slate-400 group-hover:text-blue-600 transition-colors">过滤游戏主播</span>
</div>
<div class="flex items-center gap-2 cursor-pointer group" @click="toggleFilter('filterSelling')">
<span class="w-4 h-4 rounded border-2 flex items-center justify-center transition-all"
:class="pyData.filterSelling ? 'bg-blue-600 border-blue-600' : 'bg-white border-slate-300'">
<span v-if="pyData.filterSelling" class="material-icons-round text-white text-xs">check</span>
</span>
<span
class="text-sm text-slate-600 dark:text-slate-400 group-hover:text-blue-600 transition-colors">过滤带货主播</span>
</div>
<div class="flex items-center gap-2 cursor-pointer group" @click="toggleFilter('rankingList')">
<span class="w-4 h-4 rounded border-2 flex items-center justify-center transition-all"
:class="pyData.rankingList ? 'bg-blue-600 border-blue-600' : 'bg-white border-slate-300'">
<span v-if="pyData.rankingList" class="material-icons-round text-white text-xs">check</span>
</span>
<span
class="text-sm text-slate-600 dark:text-slate-400 group-hover:text-blue-600 transition-colors">过滤排行榜单</span>
</div>
</div>
</div>
<div class="mt-6 text-center">
<button v-if="pyData.isStart" @click="submit"
class="bg-slate-900 dark:bg-blue-600 hover:scale-[1.02] active:scale-[0.98] text-white px-10 py-3 rounded-xl font-bold text-lg shadow-xl shadow-slate-900/10 dark:shadow-blue-600/20 transition-all flex items-center gap-2 mx-auto">
<span class="material-icons-round">bolt</span>
{{ $t('workbenchesSetup.start') }}
</button>
<button v-else @click="unsubmit"
class="bg-red-500 hover:bg-red-600 hover:scale-[1.02] active:scale-[0.98] text-white px-12 py-4 rounded-xl font-bold text-lg shadow-xl shadow-red-500/20 transition-all flex items-center gap-3 mx-auto">
<span class="material-icons-round">stop</span>
{{ $t('workbenchesSetup.stop') }}
</button>
<p class="mt-4 text-xs font-medium text-emerald-600 dark:text-emerald-400">
到期时间: {{ timestampToTime(expiredTime) }}
</p>
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue';
import { usePythonBridge, } from '@/utils/pythonBridge'
import { setNumData, getNumData, getUser, setTkUser, getTkUser } from '@/utils/storage'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCountryName } from '@/utils/countryUtil'
import { tkaccountuseinfo, getExpiredTime } from '@/api/account'
import { useI18n } from 'vue-i18n'
const { locale } = useI18n()
//导入python交互方法
const { fetchDataConfig, fetchDataCount, loginBackStage, loginTikTok, backStageloginStatus, backStageloginStatusCopy, getTkLoginStatus } = usePythonBridge();
//ip国家
let countryData = ref('');
//英文国家
let countryDataEN = ref('');
let country_info = ref('全部');
let country_Lst = ref();
//获取主播数量的定时器
let getHostTimer = ref(null);
//获取查询次数定时器
let getNumTimer = ref(null);
//获取的主播信息
let hostData = ref({
totalCount: 0,
validAnchorsCount: 0,
canInvitationCount: 0,
checkedDataCount: 0,
});
//是否开启tk
// let isTk = ref(true);
//账号是否登陆中
let isLogin = ref([false, false]);
//TK登录状态
let isTkLoggedIn = ref(false);
//TK状态轮询定时器
let tkStatusTimer = ref(null);
//设置状态轮询定时器
let statusTimer = ref(null);
let statusTimerCopy = ref(null);
//设置次数最大值
let maxCount = ref([
{
hourMax: 50,
dayMax: 300,
},
{
hourMax: 100,
dayMax: 600,
},
]);
//tk账号信息
let tkData = ref([
{
account: '',
password: '',
index: 1,
code: 0,
num: 0
},
{
account: '',
password: '',
index: 2,
code: 0,
num: 0
},
]);
//python需要的数据
let pyData = ref({
gold: { min: 0, max: 0 },
fans: { min: 0, max: 0 },
frequency: { hour: 0, day: 0 },
isStart: true,
country: countryData.value,
filterSelling: false,
filterGame: false,
rankingList: false,
tenantId: getUser()?.tenantId || '',
userId: getUser()?.userId || '',
});
//是否限制查询数量
let isLimit = ref(false);
//需要查询的主播数
let hostNum = ref(0);
//按钮提交状态
let submitting = ref(true);
let expiredTime = ref(null);
onMounted(async () => {
//从缓存获取数据
if (getNumData()) {
pyData.value = getNumData();
}
if (getTkUser()) {
tkData.value = getTkUser();
tkData.value[0].code = 0;
tkData.value[1].code = 0;
}
tkaccountuse(tkData.value[0].account, 0)
tkaccountuse(tkData.value[1].account, 1)
getIpInfo()
setTimeout(() => {
// Check if user exists before calling getExpiredTime
if (getUser()?.tenantId) {
getExpiredTime(getUser().tenantId).then((res) => {
console.log('time:', res);
expiredTime.value = res.expiredTime
})
}
}, 1000);
checkVPN()
setInterval(async () => {
await checkVPN()
}, 1000 * 20)
})
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);
countryDataEN.value = data.country_name
countryData.value = getCountryName(data.country);
const url = `https://datasave.api.yolozs.com/api/save_data/country_info?countryName=${countryData.value}`;
const res = await fetch(url);
const countryres = await res.json();
country_Lst.value = countryres.data
} catch (error) {
console.error('请求出错:', error);
// Optional: Re-enable if needed, but alert can be annoying
// ElMessageBox.prompt('请输入将要获取国家的中文名', '获取国家失败', { ... })
}
};
//提交数据到py
const submit = () => {
pyData.value.country = countryData.value;
console.log('提交的区间值:', pyData.value);
if (((Number(pyData.value.gold.min) > Number(pyData.value.gold.max)) || (Number(pyData.value.fans.min) > Number(pyData.value.fans.max)))) {
ElMessage.error('请输入正确的区间值');
return;
}
if ((Number(pyData.value.gold.max) <= 0 || Number(pyData.value.fans.max <= 0)) || pyData.value.gold.max == '' || pyData.value.fans.max == '') {
ElMessage.error('请输入正确的区间值');
return;
}
if (Number(pyData.value.frequency.hour) <= 0 || Number(pyData.value.frequency.day) <= 0 || pyData.value.frequency.hour == '' || pyData.value.frequency.day == '') {
ElMessage.error('请输入正确的频率区间值');
return;
}
//是否限制爬取数量
if (isLimit.value) {
if (hostNum.value <= 0) {
ElMessage.error('请输入正确的可邀请数量');
return;
}
}
ElMessageBox.confirm(
'确认开始爬取数据?',
'开始',
{
confirmButtonText: '开始',
cancelButtonText: '取消',
type: 'success',
}
)
.then(() => {
// console.log('提交的区间值:', pyData.value.gold, pyData.value.fans, pyData.value.frequency);
//开始按钮的状态 改为禁用
submitting.value = true;
setNumData(pyData.value);
console.error('提交的区间值:', JSON.stringify(pyData.value));
fetchDataConfig(JSON.stringify({
gold: pyData.value.gold,
fans: pyData.value.fans,
frequency: pyData.value.frequency,
isStart: true,
filterSelling: pyData.value.filterSelling,
filterGame: pyData.value.filterGame,
rankingList: !pyData.value.rankingList,
country: countryData.value,
tenantId: getUser().tenantId,
userId: getUser().id,
crawl_single_nation: country_info.value == '全部' ? '' : country_info.value
})).then((res) => {
//开始计时器
startTimer();
//开启查询次数
getHostTimer.value = setInterval(() => {
fetchDataCount().then((res) => {
hostData.value = JSON.parse(res);
if (isLimit.value) {
if (hostData.value.canInvitationCount >= hostNum.value) {
unsubmit();
alert('爬取完毕')
}
}
})
}, 1000);
getNumTimer.value = setInterval(() => {
tkaccountuse(tkData.value[0].account, 0)
tkaccountuse(tkData.value[1].account, 1)
}, 5000);
}).finally(() => {
setTimeout(() => {
pyData.value.isStart = false;
submitting.value = false;
}, 2000)
})
})
.catch(() => {
})
};
//停止
const unsubmit = () => {
fetchDataConfig(JSON.stringify({
gold: pyData.value.gold,
fans: pyData.value.fans,
frequency: pyData.value.frequency,
isStart: false,
filterSelling: pyData.value.filterSelling,
filterGame: pyData.value.filterGame,
rankingList: !pyData.value.rankingList,
country: countryData.value,
tenantId: getUser().tenantId,
userId: getUser().id,
crawl_single_nation: country_info.value == '全部' ? '' : country_info.value
})).then((res) => {
pauseTimer();
pyData.value.isStart = true;
clearInterval(getHostTimer.value);
getHostTimer.value = null;
clearInterval(getNumTimer.value);
getNumTimer.value = null;
// ElMessage.sussec('已停止')
}).catch((err) => {
// ElMessage.error('停止失败')
})
};
// 重置 (Unused but kept for port completeness)
// const reset = () => {
// pyData.value.gold = { min: 0, max: 0 };
// pyData.value.fans = { min: 0, max: 0 };
// pyData.value.frequency = { hour: 0, day: 0 };
// };
// 切换过滤选项 (用于Electron环境下的即时响应)
const toggleFilter = (filterName) => {
if (!pyData.value.isStart) return; // 如果已启动则不允许修改
pyData.value[filterName] = !pyData.value[filterName];
};
const loginTK = (index) => {
setTkUser(tkData.value)
loginBackStage({
account: tkData.value[index].account,
password: tkData.value[index].password,
index: index
})
if (index == 0) {
isLogin.value[1] = true;
statusTimer = setInterval(() => {
getloginStatus();
}, 2000)
} else if (index == 1) {
isLogin.value[0] = true;
statusTimerCopy = setInterval(() => {
getloginStatusCopy();
}, 2000)
}
}
const openTK = () => {
loginTikTok();
// 开始轮询TK登录状态
if (tkStatusTimer.value) {
clearInterval(tkStatusTimer.value);
}
tkStatusTimer.value = setInterval(() => {
checkTkLoginStatus();
}, 3000);
}
// 检查TK登录状态
const checkTkLoginStatus = () => {
getTkLoginStatus().then((res) => {
isTkLoggedIn.value = res === true || res === 'true';
}).catch(() => {
isTkLoggedIn.value = false;
});
}
function getloginStatus() {
backStageloginStatus().then((res) => {
const data = JSON.parse(res);
tkData.value[data.index].code = data.code
if (data.code == 1) {
clearInterval(statusTimer);
statusTimer = null;
submitting.value = false
isLogin.value[1] = false;
}
})
}
function getloginStatusCopy() {
backStageloginStatusCopy().then((res) => {
const data = JSON.parse(res);
tkData.value[data.index].code = data.code
if (data.code == 1) {
clearInterval(statusTimer);
statusTimer = null;
submitting.value = false
isLogin.value[0] = false;
}
})
}
function tkaccountuse(id, index) {
let num = 0;
console.log(id, index, "查询次数")
if (!id || id == '') {
return
}
tkaccountuseinfo(id).then((res) => {
console.log("查询返回", res)
num = res
tkData.value[index].num = num
setTkUser(tkData.value)
console.log('账号使用次数', tkData.value[index].num)
}).catch((err) => {
console.log('账号使用次数', err)
})
}
const isRunning = ref(false);
const totalSeconds = ref(0);
//定时器
let timerCrawl = null;
const startTimedata = ref(null);
//清空时间 并开始运行
const startTimer = () => {
resetTimer();
if (isRunning.value) return;
isRunning.value = true;
startTimedata.value = Date.now();
timerCrawl = setInterval(() => {
totalSeconds.value = Math.floor((Date.now() - startTimedata.value) / 1000);
}, 1000);
};
//结束运行 暂停
const pauseTimer = () => {
isRunning.value = false;
clearInterval(timerCrawl);
};
//清空时间
const resetTimer = () => {
isRunning.value = false;
clearInterval(timerCrawl);
totalSeconds.value = 0;
};
// 格式化时间为 HH:MM:SS
const formattedTime = computed(() => {
const hours = Math.floor(totalSeconds.value / 3600);
const minutes = Math.floor((totalSeconds.value % 3600) / 60);
const seconds = totalSeconds.value % 60;
return [
hours.toString().padStart(2, '0'),
minutes.toString().padStart(2, '0'),
seconds.toString().padStart(2, '0')
].join(':');
});
function timestampToTime(timestamp_ms) {
const date = new Date(timestamp_ms);
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');
// const milliseconds = date.getMilliseconds().toString().padStart(3, '0');
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
let isWifi = ref(false);
const checkVPN = async () => {
try {
// 设置超时 5 秒钟
const timeout = new Promise((_, reject) =>
setTimeout(() => reject(new Error('请求超时')), 10000) // 10秒超时
);
// 使用 Promise.race 来进行超时控制
const response = await Promise.race([
fetch('https://www.google.com', { method: 'HEAD', mode: 'no-cors' }),
timeout
]);
// 判断 fetch 请求是否成功
if (response && response.type === 'opaque') {
// ElMessage.success('VPN连接正常');
isWifi.value = false;
} else {
ElMessage.error('VPN连接失败无法访问网络。');
isWifi.value = true;
}
} catch (error) {
// 捕获超时错误或其他错误
ElMessage.error('VPN连接失败无法访问网络。');
isWifi.value = true;
}
};
</script>
<style scoped>
/* Element Plus 输入框统一样式 */
.el-input-custom :deep(.el-input__wrapper) {
background-color: white;
border: 1px solid rgb(226, 232, 240);
border-radius: 0.5rem;
padding: 0.5rem 1rem;
box-shadow: none;
transition: all 0.15s ease;
}
.el-input-custom :deep(.el-input__wrapper:hover) {
border-color: rgb(203, 213, 225);
}
.el-input-custom :deep(.el-input__wrapper.is-focus) {
border-color: var(--el-color-primary);
box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.2);
}
.el-input-custom :deep(.el-input__inner) {
font-size: 0.875rem;
}
.el-input-custom :deep(.el-input__wrapper.is-disabled) {
opacity: 0.5;
}
/* 暗色模式支持 */
.dark .el-input-custom :deep(.el-input__wrapper) {
background-color: rgb(30, 41, 59);
border-color: rgb(51, 65, 85);
}
.dark .el-input-custom :deep(.el-input__wrapper:hover) {
border-color: rgb(71, 85, 105);
}
</style>