<template>
	<Dialog
		:options="{
			title: selectedWebhookAttemptId
				? `Webhook 尝试 - ${selectedWebhookAttemptId}`
				: 'Webhook 尝试',
			size: '4xl'
		}"
	>
		<template #body-content>
			<p class="text-sm mb-2 text-gray-700" v-if="!selectedWebhookAttemptId">
				<strong>注意：</strong> 您只能查看过去24小时的日志
			</p>
			<ObjectList :options="listOptions" v-if="!selectedWebhookAttemptId" />
			<Button
				class="mb-2"
				iconLeft="arrow-left"
				v-if="selectedWebhookAttemptId"
				@click="selectedWebhookAttemptId = null"
			>
				返回
			</Button>
			<WebhookAttemptDetails
				:id="selectedWebhookAttemptId"
				v-if="selectedWebhookAttemptId"
			/>
		</template>
	</Dialog>
</template>
<script>
import { Breadcrumbs, Badge } from 'jingrow-ui';
import Header from '../Header.vue';
import ObjectList from '../ObjectList.vue';
import { h } from 'vue';
import WebhookAttemptDetails from './WebhookAttemptDetails.vue';

export default {
	name: 'WebhookAttempts',
	props: ['name'],
	components: {
		Header,
		Breadcrumbs,
		ObjectList,
		WebhookAttemptDetails
	},
	data() {
		return {
			selectedWebhookAttemptId: null
		};
	},
	resources: {
		attempts() {
			return {
				url: 'jcloud.api.webhook.attempts',
				params: {
					webhook: this.$props.name
				},
				inititalData: [],
				auto: true
			};
		}
	},
	computed: {
		listOptions() {
			return {
				data: () => this.$resources?.attempts?.data || [],
				columns: [
					{
						label: '事件',
						fieldname: 'event',
						width: 0.25
					},
					{
						label: '端点',
						fieldname: 'endpoint',
						width: 0.5,
						format: value => value.substring(0, 50)
					},
					{
						label: '状态',
						fieldname: 'status',
						width: 0.1,
						type: 'Component',
						component({ row }) {
							return row.status === 'Sent'
								? h(Badge, {
										label: row.status,
										theme: 'green'
								  })
								: h(Badge, {
										label: row.status,
										theme: 'red'
								  });
						}
					},
					{
						label: '代码',
						fieldname: 'response_status_code',
						width: 0.1,
						format: val => {
							if (!val || parseInt(val) === 0) return '-';
							return val;
						},
						align: 'center'
					},
					{
						label: '时间戳',
						fieldname: 'timestamp',
						width: 0.3,
						format(value) {
							return new Date(value).toLocaleString();
						}
					}
				],
				onRowClick: row => {
					this.selectedWebhookAttemptId = row.name;
				}
			};
		}
	}
};
</script>