<template>
	<Dialog
		:options="{
			title: '更改区域',
			actions: [
				{
					label: '更改区域',
					loading: $resources.changeRegion.loading,
					variant: 'solid',
					disabled: !selectedRegion,
					onClick: changeRegion
				}
			]
		}"
		v-model="show"
		@close="resetValues"
	>
		<template #body-content>
			<LoadingIndicator
				class="mx-auto h-4 w-4"
				v-if="$resources.changeRegionOptions.loading"
			/>
			<div v-else class="space-y-4">
				<FormControl
					variant="outline"
					type="autocomplete"
					label="选择区域"
					v-model="selectedRegion"
					:options="
						$resources.changeRegionOptions.data.regions.map(r => ({
							label: r.title || r.name,
							value: r.name,
							image: r.image
						}))
					"
				>
					<template #prefix>
						<img :src="selectedRegion?.image" class="mr-2 h-4" />
					</template>
					<template #item-prefix="{ active, selected, option }">
						<img v-if="option?.image" :src="option.image" class="mr-2 h-4" />
					</template>
				</FormControl>
				<div
					class="space-y-4"
					v-if="
						$resources.changeRegionOptions.data?.regions?.length > 0 &&
						selectedRegion
					"
				>
					<DateTimeControl v-model="targetDateTime" label="计划时间" />
					<FormControl
						label="跳过失败的补丁"
						type="checkbox"
						v-model="skipFailingPatches"
					/>
				</div>
				<p
					v-else-if="!$site.pg.group_public"
					class="mt-4 text-sm text-gray-600"
				>
					如果您要找的区域不可用，请从 Bench Group 仪表板添加。
				</p>
				<div
					class="rounded border border-gray-200 bg-gray-100 p-2"
					v-if="$resources.ARecords.data?.length == 0"
				>
					<p class="text-sm text-gray-700">
						<strong>注意</strong>: 此站点似乎有自定义域名的
						<strong>A 记录</strong>。请在迁移后更新以避免停机。了解更多，请参阅
						<a
							href="https://jingrow.com/docs/sites/custom-domains"
							target="_blank"
							class="underline"
							>文档。</a
						>
					</p>
				</div>
			</div>
			<ErrorMessage class="mt-3" :message="$resources.changeRegion.error" />
		</template>
	</Dialog>
</template>

<script>
import { getCachedDocumentResource } from 'jingrow-ui';
import { toast } from 'vue-sonner';
import DateTimeControl from '../DateTimeControl.vue';

export default {
	props: ['site'],
	data() {
		return {
			show: true,
			targetDateTime: null,
			selectedRegion: null,
			skipFailingPatches: false
		};
	},
	components: {
		DateTimeControl
	},
	computed: {
		datetimeInIST() {
			if (!this.targetDateTime) return null;
			const datetimeInIST = this.$dayjs(this.targetDateTime)
				.tz('Asia/Kolkata')
				.format('YYYY-MM-DDTHH:mm');

			return datetimeInIST;
		},
		$site() {
			return getCachedDocumentResource('Site', this.site);
		}
	},
	resources: {
		ARecords() {
			return {
				type: 'list',
				pagetype: 'Site Domain',
				filters: {
					site: this.site,
					dns_type: 'A',
					domain: ['!=', this.site]
				},
				limit: 1,
				auto: true
			};
		},
		changeRegionOptions() {
			return {
				url: 'jcloud.api.site.change_region_options',
				params: {
					name: this.site
				},
				auto: true
			};
		},
		changeRegion() {
			return {
				url: 'jcloud.api.site.change_region'
			};
		}
	},
	methods: {
		changeRegion() {
			toast.promise(
				this.$resources.changeRegion.submit({
					name: this.site,
					cluster: this.selectedRegion?.value,
					scheduled_datetime: this.datetimeInIST,
					skip_failing_patches: this.skipFailingPatches
				}),
				{
					success: () => {
						this.show = false;
return `站点计划迁移到 ${this.selectedRegion?.label}`;
					},
					loading: `正在安排站点迁移到 ${this.selectedRegion?.label}...`,
					error: error =>
						error.messages?.length
							? error.messages.join('\n')
							: error.message || '安排站点迁移失败'
				}
			);
		},
		resetValues() {
			this.selectedRegion = null;
			this.targetDateTime = null;
		}
	}
};
</script>