<template>
	<Dialog
		:options="{
			title: '编辑Webhook',
			actions: [
				{
					label: '保存更改',
					variant: 'solid',
					onClick: updateWebhook,
					loading: this.$resources.updateWebhook.loading
				}
			]
		}"
	>
		<template #body-content>
			<div class="space-y-4">
				<div>
					<FormControl label="端点" v-model="endpoint" />
					<p class="mt-1.5 text-sm text-gray-700">
						如果您更改了端点，请确保重新激活webhook。
					</p>
				</div>
				<div v-if="!updateSecret">
					<p class="block text-xs text-gray-600">密钥</p>
					<div
						class="mt-1 flex items-center justify-between text-base text-gray-700"
					>
						<p>想要更改密钥吗？</p>
						<Button @click="updateSecret = true">编辑密钥</Button>
					</div>
				</div>
				<div v-else>
					<FormControl label="密钥" v-model="secret">
						<template #suffix>
							<FeatherIcon
								class="w-4 cursor-pointer"
								name="refresh-ccw"
								@click="generateRandomSecret"
							/>
						</template>
					</FormControl>
					<p class="mt-1.5 text-sm text-gray-700">
						<secret>注意：</secret> 密钥是可选的。查看
						<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-3" v-else>
					<Switch
						v-for="event in $resources.events.data"
						:key="event.name"
						:label="event.name"
						:description="event.description"
						:modelValue="isEventSelected(event.name)"
						@update:modelValue="selectEvent(event.name)"
						size="sm"
					/>
				</div>
				<ErrorMessage
					:message="errorMessage || $resources.updateWebhook.error"
				/>
			</div>
		</template>
	</Dialog>
</template>

<script>
import { toast } from 'vue-sonner';
import { getToastErrorMessage } from '../../utils/toast';

export default {
	emits: ['success'],
	props: ['webhook'],
	data() {
		return {
			endpoint: '',
			secret: '',
			updateSecret: false,
			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
			};
		},
		fetchWebhookInfo() {
			return {
				url: 'jcloud.api.client.get',
				params: {
					pagetype: 'Jcloud Webhook',
					name: this.webhook.name
				},
				auto: true,
				onSuccess: pg => {
					this.endpoint = pg.endpoint;
					this.selectedEvents = pg.events.map(event => event.event);
				}
			};
		},
		updateWebhook() {
			return {
				url: 'jcloud.api.webhook.update',
				validate: () => {
					if (!this.selectedEvents) {
						return '请至少启用一个事件';
					}
				},
				makeParams: () => {
					return {
						name: this.webhook.name,
						endpoint: this.endpoint,
						secret: this.updateSecret ? this.secret : '',
						events: this.selectedEvents
					};
				},
				onSuccess: () => {
					toast.success('Webhook更新成功');
					const activationRequired = this.webhook.endpoint !== this.endpoint;
					this.$emit('success', activationRequired);
				},
				onError: e => {
					toast.error(
						getToastErrorMessage(
							e,
							'更新webhook失败，请重试'
						)
					);
				}
			};
		}
	},
	computed: {},
	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);
		},
		updateWebhook() {
			if (this.selectedEvents.length === 0) {
				this.errorMessage = '请至少选择一个事件来添加';
				return;
			}
			this.errorMessage = '';
			this.$resources.updateWebhook.submit();
		}
	}
};
</script>