<template>
	<div class="trade-operation-setting-scheduling">
		<el-card shadow="never" class="search-card">
			<el-form :inline="true" :model="searchForm" class="mb20">
				<el-form-item label="主播名">
					<el-input v-model="searchForm.anchorName" placeholder="请输入主播名" clearable style="width: 160px" />
				</el-form-item>
				<el-form-item label="直播账号名">
					<el-input v-model="searchForm.accountName" placeholder="请输入直播账号名" clearable style="width: 160px" />
				</el-form-item>
				<el-form-item label="状态">
					<el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 140px">
						<el-option label="待直播" :value="0" />
						<el-option label="直播中" :value="1" />
						<el-option label="已结束" :value="2" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleSearch" :loading="tableData.loading">
						<el-icon><Search /></el-icon>
						查询
					</el-button>
					<el-button @click="handleReset" :disabled="tableData.loading">
						<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>
				<el-table-column label="排序" width="80" align="center">
					<template #default="scope">
						{{ (tableData.param.pageNum - 1) * tableData.param.pageSize + scope.$index + 1 }}
					</template>
				</el-table-column>
				<el-table-column prop="anchorName" label="主播名" min-width="140" />
				<el-table-column prop="accountName" label="直播账号名" min-width="160" />
				<el-table-column prop="startTime" label="开始时间" width="180">
					<template #default="{ row }">
						{{ formatTimestamp(row.startTime) }}
					</template>
				</el-table-column>
				<el-table-column prop="endTime" label="结束时间" width="180">
					<template #default="{ row }">
						{{ formatTimestamp(row.endTime) }}
					</template>
				</el-table-column>
				<el-table-column prop="statusName" label="状态" width="100" align="center">
					<template #default="{ row }">
						<el-tag :type="getStatusTagType(row.status)">{{ row.statusName }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="remark" label="备注" min-width="180" show-overflow-tooltip />
				<el-table-column prop="createdAt" label="创建时间" width="180">
					<template #default="{ row }">
						{{ formatTimestamp(row.createdAt) }}
					</template>
				</el-table-column>
				<el-table-column label="操作" width="150">
					<template #default="{ row }">
						<el-button size="small" type="primary" text @click="onOpenEdit(row)">
							<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"
			/>
		</el-card>

		<EditSchedule ref="editScheduleRef" @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 { deleteSchedule, getScheduleList } from '/@/api/trade/operation/setting/scheduling';
import EditSchedule from './component/editSchedule.vue';

interface ScheduleItem {
	id: string;
	anchorId: string;
	anchorName: string;
	accountId: string;
	accountName: string;
	startTime: number;
	endTime: number;
	status: number;
	statusName: string;
	remark: string;
	createdAt: number;
	updatedAt: number;
}

const editScheduleRef = ref<InstanceType<typeof EditSchedule>>();

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

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

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

const getStatusTagType = (status: number): 'success' | 'info' | 'warning' => {
	if (status === 1) return 'success';
	if (status === 2) return 'info';
	return 'warning';
};

const getList = async () => {
	try {
		tableData.loading = true;
		// 列表失败文案由当前页面决定，避免和 request.ts 的全局错误提示重复。
		const res = await getScheduleList(
			{
				...tableData.param,
				anchorName: searchForm.anchorName || undefined,
				accountName: searchForm.accountName || undefined,
				status: searchForm.status,
			} as any,
			{ errorMode: 'page' }
		);
		const scheduleData = res?.data;
		if (scheduleData) {
			tableData.data = (scheduleData.list || []).map((item: any) => ({
				...item,
				id: String(item.id),
				anchorId: String(item.anchorId),
				anchorName: item.anchorName || '',
				accountId: String(item.accountId),
				accountName: item.accountName || '',
			}));
			tableData.total = scheduleData.total || 0;
		}
	} catch (error) {
		ElMessage.error('获取排班列表失败');
	} finally {
		tableData.loading = false;
	}
};

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

const handleReset = () => {
	searchForm.anchorName = '';
	searchForm.accountName = '';
	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 = () => {
	editScheduleRef.value?.openDialog();
};

const onOpenEdit = (row: ScheduleItem) => {
	editScheduleRef.value?.openDialog(row);
};

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

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

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

.mb20 {
	margin-bottom: 20px;
}

.mt20 {
	margin-top: 20px;
}
</style>
