<template>
	<Dialog
		:options="{
			title: '恢复',
			actions: [
				{
					label: '恢复',
					variant: 'solid',
					theme: 'red',
					loading: $resources.restoreBackup.loading,
					onClick: () => {
						$resources.restoreBackup.submit();
						showRestoreDialog = false;
					}
				}
			]
		}"
		v-model="showRestoreDialog"
	>
		<template v-slot:body-content>
			<div class="space-y-4">
				<p class="text-base">使用之前的备份恢复您的数据库。</p>
				<div
					class="flex items-center rounded border border-gray-200 bg-gray-100 p-4 text-sm text-gray-600"
				>
					<i-lucide-alert-triangle class="mr-4 inline-block h-6 w-6" />
					<div>
						此操作将用备份中的<b>数据</b>和<b>应用</b>替换您站点中的所有内容
					</div>
				</div>
				<BackupFilesUploader v-model:backupFiles="selectedFiles" />
			</div>
			<div class="mt-3">
				<!-- 跳过失败复选框 -->
				<input
					id="skip-failing"
					type="checkbox"
					class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500"
					v-model="skipFailingPatches"
				/>
				<label for="skip-failing" class="ml-2 text-sm text-gray-900">
					跳过失败的补丁（如果有任何补丁失败）
				</label>
			</div>
			<ErrorMessage class="mt-2" :message="$resources.restoreBackup.error" />
		</template>
	</Dialog>
</template>
<script>
import { DashboardError } from '../utils/error';

export default {
	name: 'SiteDatabaseRestoreDialog',
	props: {
		site: {
			type: String,
			required: true
		}
	},
	data() {
		return {
			showRestoreDialog: true,
			selectedFiles: {
				database: null,
				public: null,
				private: null,
				config: null
			},
			skipFailingPatches: false
		};
	},
	resources: {
		restoreBackup() {
			return {
				url: 'jcloud.api.site.restore',
				params: {
					name: this.site,
					files: this.selectedFiles,
					skip_failing_patches: this.skipFailingPatches
				},
				validate() {
					if (!this.filesUploaded) {
						throw new DashboardError(
							'请上传数据库、公共和私有文件以进行恢复。'
						);
					}
				},
				onSuccess() {
					this.selectedFiles = {};
					this.$router.push({
						name: 'Site Jobs',
						params: { name: this.site }
					});
				}
			};
		}
	},
	computed: {
		filesUploaded() {
			return this.selectedFiles.database;
		}
	}
};
</script>