<template>
	<div class="dingtalk-sync-container">
		<el-card>
			<template #header>
				<div class="card-header">
					<span>钉钉同步管理</span>
				</div>
			</template>

			<!-- 同步状态卡片 -->
			<el-row :gutter="20" style="margin-bottom: 20px">
				<el-col :span="24">
					<div class="sync-status-card">
						<div class="status-item">
							<div class="label">当前状态</div>
							<div class="value">
								<el-tag
									:type="syncStatus.isSyncing ? 'warning' : 'success'"
									size="large"
								>
									{{ syncStatus.isSyncing ? '同步中' : '空闲' }}
								</el-tag>
							</div>
						</div>
						<div class="status-item" v-if="syncStatus.lastSyncTime">
							<div class="label">上次同步</div>
							<div class="value">{{ syncStatus.lastSyncTime }}</div>
						</div>
						<div class="status-item" v-if="syncStatus.nextSyncTime">
							<div class="label">下次同步</div>
							<div class="value">{{ syncStatus.nextSyncTime }}</div>
						</div>
					</div>
				</el-col>
			</el-row>

			<!-- 同步操作 -->
			<el-row :gutter="20" style="margin-bottom: 20px">
				<el-col :span="24">
					<el-button
						type="primary"
						:loading="syncing"
						:disabled="syncStatus.isSyncing"
						@click="triggerSync"
						size="large"
					>
						{{ syncing ? '同步进行中...' : '立即同步' }}
					</el-button>
					<el-button @click="refreshStatus" size="large">刷新状态</el-button>
					<span class="sync-tip" v-if="syncStatus.isSyncing">
						同步任务正在后台执行，请稍后查看同步日志...
					</span>
				</el-col>
			</el-row>

			<!-- 同步结果统计 -->
			<el-row :gutter="20" v-if="latestLog">
				<el-col :span="24">
					<div class="sync-result-card">
						<div class="result-title">最近一次同步结果</div>
						<el-row :gutter="20">
							<el-col :span="6">
								<div class="result-item">
									<div class="result-label">同步时间</div>
									<div class="result-value">{{ latestLog.createTime }}</div>
								</div>
							</el-col>
							<el-col :span="6">
								<div class="result-item">
									<div class="result-label">同步类型</div>
									<div class="result-value">
										<el-tag :type="latestLog.syncType === 0 ? 'primary' : 'info'">
											{{ latestLog.syncType === 0 ? '手动' : '自动' }}
										</el-tag>
									</div>
								</div>
							</el-col>
							<el-col :span="6">
								<div class="result-item">
									<div class="result-label">同步状态</div>
									<div class="result-value">
										<el-tag
											:type="
												latestLog.syncStatus === 1
													? 'success'
													: latestLog.syncStatus === 2
														? 'warning'
														: 'danger'
											"
										>
											{{
												latestLog.syncStatus === 1
													? '成功'
													: latestLog.syncStatus === 2
														? '部分成功'
														: '失败'
											}}
										</el-tag>
									</div>
								</div>
							</el-col>
							<el-col :span="6">
								<div class="result-item">
									<div class="result-label">耗时</div>
									<div class="result-value">{{ latestLog.costTime }}ms</div>
								</div>
							</el-col>
						</el-row>
						<el-row :gutter="20" style="margin-top: 10px">
							<el-col :span="6">
								<div class="result-item success">
									<div class="result-label">部门同步成功</div>
									<div class="result-value">{{ latestLog.deptSuccessCount }}</div>
								</div>
							</el-col>
							<el-col :span="6">
								<div class="result-item error">
									<div class="result-label">部门同步失败</div>
									<div class="result-value">{{ latestLog.deptFailCount }}</div>
								</div>
							</el-col>
							<el-col :span="6">
								<div class="result-item success">
									<div class="result-label">用户同步成功</div>
									<div class="result-value">{{ latestLog.userSuccessCount }}</div>
								</div>
							</el-col>
							<el-col :span="6">
								<div class="result-item error">
									<div class="result-label">用户同步失败</div>
									<div class="result-value">{{ latestLog.userFailCount }}</div>
								</div>
							</el-col>
						</el-row>
						<el-row v-if="latestLog.errorMsg" style="margin-top: 10px">
							<el-col :span="24">
								<div class="error-msg">
									<div class="error-label">错误信息：</div>
									<div class="error-content">{{ latestLog.errorMsg }}</div>
								</div>
							</el-col>
						</el-row>
					</div>
				</el-col>
			</el-row>
		</el-card>
	</div>
</template>

<script lang="ts" setup>
defineOptions({
	name: 'dingtalk-sync'
});

import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import { useCool } from '/@/cool';
import { ElMessage } from 'element-plus';

const { service } = useCool();

// 同步中状态
const syncing = ref(false);

// 同步状态信息
const syncStatus = reactive({
	isSyncing: false,
	lastSyncTime: '',
	nextSyncTime: ''
});

// 最新同步日志
const latestLog = ref<any>(null);

// 定时刷新定时器
let refreshTimer: any = null;

// 触发同步
async function triggerSync() {
	try {
		syncing.value = true;
		await service.dingtalk.sync.trigger();
		ElMessage.success('同步任务已启动，请稍后查看同步日志');

		// 立即刷新一次状态
		await refreshStatus();

		// 开始轮询状态
		startPolling();
	} catch (err: any) {
		ElMessage.error(err.message || '触发同步失败');
	} finally {
		syncing.value = false;
	}
}

// 刷新状态
async function refreshStatus() {
	try {
		const res = await service.dingtalk.sync.getStatus();
		if (res) {
			const wasSyncing = syncStatus.isSyncing;
			syncStatus.isSyncing = res.isSyncing || false;
			syncStatus.lastSyncTime = res.lastSyncTime || '';
			syncStatus.nextSyncTime = res.nextSyncTime || '';
			latestLog.value = res.latestLog || null;

			// 如果之前正在同步，现在完成了，停止轮询
			if (wasSyncing && !syncStatus.isSyncing) {
				stopPolling();
				ElMessage.success('同步已完成');
			}
		}
	} catch (err: any) {
		console.error('刷新状态失败:', err);
	}
}

// 开始轮询
function startPolling() {
	if (refreshTimer) {
		clearInterval(refreshTimer);
	}

	// 每5秒刷新一次状态
	refreshTimer = setInterval(() => {
		refreshStatus();
	}, 5000);
}

// 停止轮询
function stopPolling() {
	if (refreshTimer) {
		clearInterval(refreshTimer);
		refreshTimer = null;
	}
}

// 组件挂载
onMounted(() => {
	refreshStatus();
	// 如果正在同步，开始轮询
	if (syncStatus.isSyncing) {
		startPolling();
	}
});

// 组件卸载前清理定时器
onBeforeUnmount(() => {
	stopPolling();
});
</script>

<style lang="scss" scoped>
.dingtalk-sync-container {
	padding: 20px;

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.sync-status-card {
		display: flex;
		gap: 40px;
		padding: 20px;
		background: #f5f7fa;
		border-radius: 4px;

		.status-item {
			.label {
				font-size: 14px;
				color: #909399;
				margin-bottom: 8px;
			}

			.value {
				font-size: 16px;
				font-weight: bold;
				color: #303133;
			}
		}
	}

	.sync-tip {
		margin-left: 20px;
		color: #e6a23c;
		font-size: 14px;
	}

	.sync-result-card {
		padding: 20px;
		background: #f5f7fa;
		border-radius: 4px;
		margin-top: 20px;

		.result-title {
			font-size: 16px;
			font-weight: bold;
			color: #303133;
			margin-bottom: 15px;
		}

		.result-item {
			padding: 10px;
			background: white;
			border-radius: 4px;

			.result-label {
				font-size: 12px;
				color: #909399;
				margin-bottom: 5px;
			}

			.result-value {
				font-size: 16px;
				font-weight: bold;
				color: #303133;
			}

			&.success .result-value {
				color: #67c23a;
			}

			&.error .result-value {
				color: #f56c6c;
			}
		}

		.error-msg {
			padding: 10px;
			background: #fef0f0;
			border-radius: 4px;
			border-left: 3px solid #f56c6c;

			.error-label {
				font-size: 12px;
				color: #f56c6c;
				font-weight: bold;
				margin-bottom: 5px;
			}

			.error-content {
				font-size: 13px;
				color: #606266;
				line-height: 1.6;
			}
		}
	}
}
</style>
