<template>
	<Dialog
		:options="{
			title: '更改计划',
			size: '5xl',
			actions: [
				{
					label: '更改计划',
					variant: 'solid',
					onClick: changePlan,
					disabled: !plan || plan === $server?.pg.plan
				}
			]
		}"
		v-model="show"
	>
		<template #body-content>
			<div class="mb-4 mt-2 w-full space-y-2">
				<div class="grid grid-cols-2 gap-3">
					<button
						v-for="c in [
							{
								name: '标准版',
								description: '包含标准支持和SLA'
							},
							{
								name: '高级版',
								description: '包含企业级支持和SLA'
							}
						]"
						:key="c.name"
						@click="planType = c.name"
						:class="[
							planType === c.name
								? 'border-gray-900 ring-1 ring-gray-900 hover:bg-gray-100'
								: 'border-gray-400 bg-white text-gray-900 ring-gray-200 hover:bg-gray-50',
							'flex w-full items-center rounded border p-3 text-left text-base text-gray-900'
						]"
					>
						<div class="flex w-full items-center justify-between space-x-2">
							<span class="text-sm font-medium">
								{{ c.name }}
							</span>
							<Tooltip :text="c.description">
								<i-lucide-info class="h-4 w-4 text-gray-500" />
							</Tooltip>
						</div>
					</button>
				</div>
			</div>
			<ServerPlansCards
				v-model="plan"
				:plans="
					planType === '高级版'
						? $resources.serverPlans.data.filter(p => p.premium === 1)
						: $resources.serverPlans.data.filter(p => p.premium === 0)
				"
			/>
			<ErrorMessage class="mt-2" :message="$server.changePlan.error" />
		</template>
	</Dialog>
</template>
<script>
import { getCachedDocumentResource } from 'jingrow-ui';
import ServerPlansCards from './ServerPlansCards.vue';

export default {
	components: { ServerPlansCards },
	props: {
		server: {
			type: String,
			required: true
		},
		serverType: {
			type: String,
			required: true
		}
	},
	data() {
		return {
			show: true,
			plan: null,
			planType: '标准版'
		};
	},
	watch: {
		server: {
			immediate: true,
			handler(serverName) {
				if (serverName) {
					if (this.$server?.pg?.plan) {
						this.plan = this.$server.pg.current_plan;
					}
				}
			}
		}
	},
	resources: {
		serverPlans() {
			return {
				url: 'jcloud.api.server.plans',
				params: {
					name: this.serverType,
					cluster: this.$server.pg.cluster,
					platform: this.$server.pg.current_plan.platform
				},
				auto: true,
				initialData: []
			};
		}
	},
	methods: {
		changePlan() {
			return this.$server.changePlan.submit(
				{ plan: this.plan.name },
				{
					onSuccess: () => {
						this.show = false;

						const plan = this.$resources.serverPlans.data.find(
							plan => plan.name === this.$server.pg.plan
						);

						const formattedPlan = plan
							? `${this.$format.planTitle(plan)}/月`
							: this.$server.pg.plan;

						this.$toast.success(`计划已更改为 ${formattedPlan}`);
					}
				}
			);
		}
	},
	computed: {
		$server() {
			return getCachedDocumentResource(this.serverType, this.server);
		}
	}
};
</script>