<template>
	<Dialog
		:options="{
			title: '添加新Webhook',
			actions: [
				{
					label: '添加Webhook',
					variant: 'solid',
					onClick: addWebhook,
					loading: $resources?.addWebhook?.loading
				}
			]
		}"
	>
		<template #body-content>
			<div class="space-y-4">
				<FormControl label="端点" v-model="endpoint" />
				<div>
					<FormControl label="密钥" v-model="secret">
						<template #suffix>
							<FeatherIcon
								class="w-4 cursor-pointer"
								name="refresh-ccw"
								@click="generateRandomSecret"
							/>
						</template>
					</FormControl>
					<p class="mt-2 text-sm text-gray-700">
						<strong>注意：</strong> 密钥是可选的。查看
						<a href="https://jingrow.com/docs/webhook-introduction" class="underline" target="_blank"
							>文档</a
						>
						了解更多
					</p>
				</div>
				<p class="text-base font-medium text-gray-900">
					选择Webhook事件
				</p>
				<div
					class="text-center text-sm leading-10 text-gray-500"
					v-if="$resources.events.loading"
				>
					加载中...
				</div>
				<div class="mt-6 flex flex-col gap-4" v-else>
					<Switch
						v-for="event in localizedEvents"
						:key="event.name"
						:label="event.title || event.name"
						:description="event.description"
						:modelValue="isEventSelected(event.name)"
						@update:modelValue="selectEvent(event.name)"
						size="sm"
					/>
				</div>
				<ErrorMessage :message="errorMessage || $resources.addWebhook.error" />
			</div>
		</template>
	</Dialog>
</template>

<script>
import { toast } from 'vue-sonner';

export default {
	emits: ['success'],
	data() {
		return {
			endpoint: '',
			secret: '',
			selectedEvents: [],
			errorMessage: ''
		};
	},
	mounted() {
		if (this.selectedEvents.length) {
			this.selectedEvents = this.selectedEvents.map(event => event.name);
		}
	},
	resources: {
		events() {
			return {
				url: 'jcloud.api.webhook.available_events',
				inititalData: [],
				auto: true
			};
		},
		addWebhook() {
			return {
				url: 'jcloud.api.webhook.add',
				params: {
					endpoint: this.endpoint,
					secret: this.secret,
					events: this.selectedEvents
				},
				onSuccess() {
					toast.success('Webhook添加成功');
					this.$emit('success');
				}
			};
		}
	},
	computed: {
		localizedEvents() {
			if (!this.$resources.events.data) return [];
			
			return this.$resources.events.data.map(event => {
				// 如果后端已返回title和description字段，则直接使用
				// 否则根据事件名称进行本地化翻译
				if (!event.title) {
					if (event.name === 'Site Status Update') {
						event.title = '站点状态更新';
					} else if (event.name === 'Site Plan Change') {
						event.title = '站点套餐变更';
					}
				}
				
				if (!event.description || event.description.includes('Pending') || event.description.includes('Get notified')) {
					if (event.name === 'Site Status Update') {
						event.description = '等待中、安装中、更新中、活跃、不活跃、异常、已归档、已暂停';
					} else if (event.name === 'Site Plan Change') {
						event.description = '获取站点套餐变更的通知';
					}
				}
				
				return event;
			});
		}
	},
	methods: {
		generateRandomSecret() {
			this.secret = Array(30)
				.fill(0)
				.map(
					() =>
						'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'[
							Math.floor(Math.random() * 62)
						]
				)
				.join('');
		},
		selectEvent(event) {
			if (this.selectedEvents.includes(event)) {
				this.selectedEvents = this.selectedEvents.filter(e => e !== event);
			} else {
				this.selectedEvents.push(event);
			}
		},
		isEventSelected(event) {
			return this.selectedEvents.includes(event);
		},
		addWebhook() {
			if (!this.endpoint) {
				this.errorMessage = '请提供有效的Webhook端点';
				return;
			}
			if (!this.selectedEvents.length) {
				this.errorMessage = '请启用至少一个事件';
				return;
			}
			this.errorMessage = '';
			this.$resources.addWebhook.submit();
		}
	}
};
</script>