<template>
	<div class="trade-operation-setting-live-account">
		<el-card shadow="never" class="search-card">
			<el-form :inline="true" :model="searchForm" class="mb20">
				<el-form-item label="平台">
					<el-select v-model="searchForm.platform" placeholder="请选择平台" clearable style="width: 120px">
						<el-option label="抖音" :value="'抖音'" />
						<el-option label="快手" :value="'快手'" />
						<el-option label="视频号" :value="'视频号'" />
					</el-select>
				</el-form-item>
				<el-form-item label="账号名称">
					<el-input v-model="searchForm.accountName" placeholder="请输入账号名称" clearable style="width: 180px" />
				</el-form-item>
				<el-form-item label="账号ID">
					<el-input v-model="searchForm.accountId" placeholder="请输入账号ID" clearable style="width: 180px" />
				</el-form-item>
				<el-form-item label="状态">
					<el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px">
						<el-option label="正常" :value="1" />
						<el-option label="停用" :value="0" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSearch" :loading="tableData.loading" class="mr10">
						<el-icon><Search /></el-icon>
						查询
					</el-button>
					<el-button @click="handleReset" :disabled="tableData.loading" class="mr10">
						<el-icon><Refresh /></el-icon>
						重置
					</el-button>
					<el-button type="success" @click="onOpenAdd">
						<el-icon><Plus /></el-icon>
						新增
					</el-button>
				</el-form-item>
			</el-form>
		</el-card>

		<el-card shadow="never" class="mt20">
			<el-table v-loading="tableData.loading" :data="tableData.data" style="width: 100%" stripe border empty-text="暂无直播账号数据">
				<el-table-column prop="id" label="ID" width="200" align="center" />
				<el-table-column prop="platform" label="平台" min-width="100" />
				<el-table-column prop="accountName" label="账号名称" min-width="150" />
				<el-table-column prop="accountId" label="账号ID" min-width="150" />
				<el-table-column prop="statusName" label="状态" width="100" align="center">
					<template #default="{ row }">
						<el-tag :type="row.status === 1 ? 'success' : 'info'">
							{{ row.statusName }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="remark" label="备注" min-width="150" show-overflow-tooltip />
				<el-table-column prop="createdAt" label="创建时间" width="180" align="center">
					<template #default="{ row }">
						{{ formatTimestamp(row.createdAt) }}
					</template>
				</el-table-column>
				<el-table-column prop="updatedAt" label="更新时间" width="180" align="center">
					<template #default="{ row }">
						{{ formatTimestamp(row.updatedAt) }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="180" fixed="right" align="center">
					<template #default="{ row }">
						<el-button size="small" type="primary" text @click="onOpenEdit(row)" class="mr5">
							<el-icon><EditPen /></el-icon>修改
						</el-button>
						<el-button size="small" type="danger" text @click="handleDelete(row)">
							<el-icon><Delete /></el-icon>删除
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<el-pagination
				v-model:current-page="tableData.param.pageNum"
				v-model:page-size="tableData.param.pageSize"
				:page-sizes="[10, 20, 30, 50]"
				layout="total, sizes, prev, pager, next, jumper"
				:total="tableData.total"
				@size-change="handleSizeChange"
				@current-change="handleCurrentChange"
				class="mt20 flex justify-end"
			/>
		</el-card>

		<EditLiveAccount ref="editLiveAccountRef" @refresh="getList" />
	</div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search, Refresh, Plus, EditPen, Delete } from '@element-plus/icons-vue';
import { deleteLiveAccount, getLiveAccountList } from '/@/api/trade/operation/setting/live-account';
import EditLiveAccount from './component/editLiveAccount.vue';

interface LiveAccountItem {
	id: string;
	platform: string;
	accountName: string;
	accountId: string;
	status: number;
	statusName: string;
	remark: string;
	createdAt: number;
	updatedAt: number;
}

const editLiveAccountRef = ref<InstanceType<typeof EditLiveAccount>>();

const searchForm = reactive({
	platform: '',
	accountName: '',
	accountId: '',
	status: undefined as number | undefined,
});

const tableData = reactive({
	loading: false,
	data: [] as LiveAccountItem[],
	total: 0,
	param: {
		pageNum: 1,
		pageSize: 10,
	},
});

const getList = async () => {
	try {
		tableData.loading = true;
		// 列表失败文案由当前页面决定，避免和全局请求报错同时出现。
		const res = await getLiveAccountList(
			{
				...tableData.param,
				platform: searchForm.platform || undefined,
				accountName: searchForm.accountName || undefined,
				accountId: searchForm.accountId || undefined,
				status: searchForm.status,
			},
			{ errorMode: 'page' }
		);
		if (res && res.data) {
			tableData.data = (res.data.list || []).map((item: any) => ({
				...item,
				id: String(item.id),
			}));
			tableData.total = res.data.total || 0;
		}
	} catch (error) {
		ElMessage.error('获取直播账号列表失败');
	} finally {
		tableData.loading = false;
	}
};

const handleSearch = () => {
	tableData.param.pageNum = 1;
	getList();
};

const handleReset = () => {
	searchForm.platform = '';
	searchForm.accountName = '';
	searchForm.accountId = '';
	searchForm.status = undefined;
	tableData.param.pageNum = 1;
	getList();
};

const handleSizeChange = (size: number) => {
	tableData.param.pageSize = size;
	getList();
};

const handleCurrentChange = (current: number) => {
	tableData.param.pageNum = current;
	getList();
};

const onOpenAdd = () => {
	editLiveAccountRef.value?.openDialog();
};

const onOpenEdit = (row: LiveAccountItem) => {
	editLiveAccountRef.value?.openDialog(row);
};

const handleDelete = async (row: LiveAccountItem) => {
	try {
		await ElMessageBox.confirm(`确定要删除直播账号「${row.accountName}」吗？`, '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning',
		});
		await deleteLiveAccount({ id: row.id }, { errorMode: 'page' });
		ElMessage.success('删除成功');
		getList();
	} catch (error) {
		if (error !== 'cancel') {
			ElMessage.error('删除失败');
		}
	}
};

const formatTimestamp = (timestamp: number) => {
	if (!timestamp) return '';
	const date = new Date(timestamp * 1000);
	return date.toLocaleString('zh-CN');
};

onMounted(() => {
	getList();
});
</script>

<style scoped lang="scss">
.trade-operation-setting-live-account {
	padding: 20px;
}

.mb20 {
	margin-bottom: 20px;
}

.mt20 {
	margin-top: 20px;
}

.mr10 {
	margin-right: 10px;
}

.mr5 {
	margin-right: 5px;
}

.flex {
	display: flex;
}

.justify-end {
	justify-content: flex-end;
}

.search-card {
	padding: 20px;
}
</style>
