<template>
	<Dialog
		v-model="show"
		@close="resetValues"
		:options="{ title: '升级站点版本' }"
	>
		<template #body-content>
			<div class="space-y-4">
				<p v-if="$site.pg?.group_public && nextVersion" class="text-base">
					站点 <b>{{ $site.pg.host_name }}</b> 将被升级到
					<b>{{ nextVersion }}</b>
				</p>
				<FormControl
					v-else-if="privateReleaseGroups.length > 0 && nextVersion"
					variant="outline"
					:label="`请选择一个 ${nextVersion} 的站点分组来将您的站点从 ${$site.pg.version} 升级`"
					class="w-full"
					type="autocomplete"
					:options="privateReleaseGroups"
					v-model="privateReleaseGroup"
				/>
				<DateTimeControl
					v-if="($site.pg.group_public && nextVersion) || benchHasCommonServer"
					v-model="targetDateTime"
					label="计划时间"
				/>
				<FormControl
					v-if="($site.pg.group_public && nextVersion) || benchHasCommonServer"
					label="跳过失败的补丁（如果有）"
					type="checkbox"
					v-model="skipFailingPatches"
				/>
				<FormControl
					v-if="($site.pg.group_public && nextVersion) || benchHasCommonServer"
					label="跳过备份"
					type="checkbox"
					v-model="skipBackups"
					class="ml-4"
				/>
				<div
					v-if="skipBackups"
					class="flex items-center rounded bg-gray-50 p-4 text-sm text-gray-700"
				>
					<i-lucide-info class="mr-2 h-4 w-8" />
					在升级过程中将不会进行备份，如果出现任何故障，将无法回滚。
				</div>
				<p v-if="message && !errorMessage" class="text-sm text-gray-700">
					{{ message }}
				</p>
				<ErrorMessage :message="errorMessage" />
			</div>
		</template>
		<template
			v-if="$site.pg?.group_public || privateReleaseGroups.length"
			#actions
		>
			<Button
				v-if="!$site.pg.group_public"
				class="mb-2 w-full"
				:disabled="
					benchHasCommonServer || !privateReleaseGroup.value || !nextVersion
				"
				label="将服务器添加到站点分组"
				@click="$resources.addServerToReleaseGroup.submit()"
				:loading="
					$resources.addServerToReleaseGroup.loading ||
					$resources.validateGroupforUpgrade.loading
				"
			/>
			<Button
				class="w-full"
				variant="solid"
				label="升级"
				:disabled="
					((!benchHasCommonServer || !privateReleaseGroup.value) &&
						!$site.pg.group_public) ||
					!nextVersion
				"
				:loading="
					$resources.versionUpgrade.loading ||
					$resources.validateGroupforUpgrade.loading
				"
				@click="$resources.versionUpgrade.submit()"
			/>
		</template>
	</Dialog>
</template>

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

export default {
	name: 'SiteVersionUpgradeDialog',
	props: ['site'],
	components: { DateTimeControl },
	data() {
		return {
			show: true,
			targetDateTime: null,
			privateReleaseGroup: {
				value: '',
				label: ''
			},
			skipBackups: false,
			skipFailingPatches: false,
			benchHasCommonServer: false
		};
	},
	watch: {
		privateReleaseGroup: {
			handler(privateReleaseGroup) {
				if (privateReleaseGroup?.value) {
					this.$resources.validateGroupforUpgrade.submit({
						name: this.site,
						group_name: privateReleaseGroup.value
					});
				}
			}
		}
	},
	computed: {
		nextVersion() {
			const nextNumber = Number(this.$site.pg?.version.split(' ')[1]);
			if (
				isNaN(nextNumber) ||
				this.$site.pg?.version === this.$site.pg?.latest_jingrow_version
			)
				return null;

			return `Version ${nextNumber + 1}`;
		},
		privateReleaseGroups() {
			return this.$resources.getPrivateGroups.data;
		},
		message() {
			if (this.$site.pg?.version === this.$site.pg?.latest_jingrow_version) {
				return '此站点已经是最新版本。';
} else if (this.$site.pg?.version === 'Nightly') {
				return "此站点处于夜间版本，无需升级。";
			} else if (
				!this.$site.pg?.group_public &&
				this.privateReleaseGroups.length === 0
			)
				return `您的团队没有任何可用的私有站点分组来将此站点升级到 ${this.nextVersion}。`;
			else if (!this.privateReleaseGroup?.value) {
				return '';
			} else if (!this.$site.pg?.group_public && !this.benchHasCommonServer)
				return `所选站点分组和您的站点没有共同的服务器。请将站点的服务器添加到站点分组中。`;
			else if (!this.$site.pg?.group_public && this.benchHasCommonServer)
				return `所选站点分组和您的站点有共同的服务器。您可以继续升级到 ${this.nextVersion}。`;
			else return '';
		},
		datetimeInIST() {
			if (!this.targetDateTime) return null;
			const datetimeInIST = this.$dayjs(this.targetDateTime).format(
				'YYYY-MM-DDTHH:mm'
			);

			return datetimeInIST;
		},
		errorMessage() {
			return (
				this.$resources.versionUpgrade.error ||
				this.$resources.validateGroupforUpgrade.error ||
				this.$resources.addServerToReleaseGroup.error ||
				this.$resources.getPrivateGroups.error
			);
		},
		$site() {
			return getCachedDocumentResource('Site', this.site);
		}
	},
	resources: {
		versionUpgrade() {
			return {
				url: 'jcloud.api.site.version_upgrade',
				params: {
					name: this.site,
					destination_group: this.privateReleaseGroup.value,
					skip_failing_patches: this.skipFailingPatches,
					skip_backups: this.skipBackups,
					scheduled_datetime: this.datetimeInIST
				},
				onSuccess() {
					toast.success("站点版本升级已安排。");
					this.show = false;
				}
			};
		},
		getPrivateGroups() {
			return {
				url: 'jcloud.api.site.get_private_groups_for_upgrade',
				params: {
					name: this.site,
					version: this.$site.pg?.version
				},
				auto:
					this.$site.pg?.version &&
					!this.$site.pg?.group_public &&
					this.$site.pg?.version !== 'Nightly',
				transform(data) {
					return data.map(group => ({
						label: group.title || group.name,
						description: group.name,
						value: group.name
					}));
				},
				initialData: []
			};
		},
		addServerToReleaseGroup() {
			return {
				url: 'jcloud.api.site.add_server_to_release_group',
				params: {
					name: this.site,
					group_name: this.privateReleaseGroup.value
				},
				onSuccess(data) {
					toast.success('服务器已添加到站点分组', {
						description: `已将服务器添加到 ${this.privateReleaseGroup.value} 站点分组。请等待部署完成。`
					});
					this.$router.push({
						name: 'Release Group Job',
						params: {
							name: this.privateReleaseGroup.value,
							id: data
						}
					});
					this.resetValues();
					this.show = false;
				}
			};
		},
		validateGroupforUpgrade() {
			return {
				url: 'jcloud.api.site.validate_group_for_upgrade',
				onSuccess(data) {
					this.benchHasCommonServer = data;
				}
			};
		}
	},
	methods: {
		resetValues() {
			this.targetDateTime = null;
			this.privateReleaseGroup = {
				label: '',
				value: ''
			};
			this.benchHasCommonServer = false;
			this.$resources.getPrivateGroups.reset();
		}
	}
};
</script>