<template>
	<Dialog
		:options="{
			title: showSetupSubscription ? '设置订阅' : '更改计划',
			size: step === 'site-plans' ? '3xl' : '3xl',
		}"
		v-model="show"
	>
		<template #body-content>
			<!-- 步骤适用于未添加支付方式的用户，
		 否则用户只需通过初始步骤来更改计划 -->

			<div v-if="step === 'site-plans'">
				<!-- 由于某种原因，进度条在移动到新步骤时不会重新渲染，所以做了这个奇怪的事情 -->
				<!-- TODO: 在jingrow-ui中修复它 -->
				<Progress
					v-if="showSetupSubscription"
					class="my-8"
					size="md"
					:label="progressLabel"
					:interval-count="3"
					:intervals="true"
					:value="32"
				/>
				<SitePlansCards
					v-model="plan"
					:isPrivateBenchSite="!$site.pg.group_public"
					:isDedicatedServerSite="$site.pg.is_dedicated_server"
				/>
				<div class="mt-4 text-xs text-gray-700">
					<div
						class="flex items-center rounded bg-gray-50 p-2 text-p-base font-medium text-gray-800"
					>
						<i-lucide-badge-check class="mr-2 h-5 w-12 text-gray-600" />
						<span>
							安装使用 Jingrow 系统遇到任何问题请提交支持工单或联系在线客服。
						</span>
					</div>
				</div>
				<ErrorMessage class="mt-2" :message="$site.setPlan.error" />
			</div>

			<div v-else-if="step === 'billing-details'">
				<Progress
					class="my-8"
					size="md"
					:label="progressLabel"
					:interval-count="3"
					:intervals="true"
					:value="65"
				/>
				<div class="mb-5 inline-flex gap-1.5 text-base text-gray-700">
					<FeatherIcon class="h-4" name="info" />
					<span> 在继续之前，请将账单信息添加到您的账户。</span>
				</div>
				<BillingDetails ref="billingRef" @success="step = 'add-payment-mode'" />
			</div>

			<div v-else-if="step === 'add-payment-mode'">
				<Progress
					class="my-8"
					:label="progressLabel"
					size="md"
					:interval-count="3"
					:intervals="true"
					:value="99"
				/>
				<div
					class="mb-5 flex w-full flex-row gap-2 rounded-md border p-1 text-p-base text-gray-800"
				>
					<div
						class="w-1/2 cursor-pointer rounded-[7px] py-1.5 text-center transition-all"
						:class="{
							'bg-gray-100': isAutomatedBilling,
						}"
						@click="isAutomatedBilling = true"
					>
						添加卡片
					</div>
					<div
						class="w-1/2 cursor-pointer rounded-sm py-1.5 text-center transition-all"
						:class="{
							'bg-gray-100': !isAutomatedBilling,
						}"
						@click="isAutomatedBilling = false"
					>
						添加预付款
					</div>
				</div>

				<div>
					<div
						v-if="isAutomatedBilling"
						class="mb-5 flex items-center gap-2 text-sm text-gray-700"
					>
						<FeatherIcon class="h-4" name="info" />
						<span>
							添加卡片将为您的账户启用自动计费。您将在计费周期结束时自动扣款。
						</span>
					</div>
					<div
						v-else
						class="mb-5 flex items-center gap-2 text-sm text-gray-700"
					>
						<FeatherIcon class="h-4" name="info" />
						<span>
							添加预付款将允许您手动充值账户余额。您可以使用此余额支付您的计划费用。
						</span>
					</div>
				</div>

				<CardForm
					v-if="isAutomatedBilling"
					@success="paymentModeAdded"
					:showAddressForm="false"
				/>
				<BuyPrepaidCreditsForm
					v-else
					:minimumAmount="
						$team.pg?.currency === 'CNY' ? plan.price_cny : plan.price_usd
					"
					@success="paymentModeAdded"
				/>
			</div>
		</template>
		<template #actions v-if="step === 'site-plans'">
			<Button
				variant="solid"
				:disabled="!plan || ($site?.pg && plan === $site.pg.plan)"
				@click="handleNext()"
				class="w-full"
			>
				{{
					!$team.pg.payment_mode ||
					!$team.pg.billing_details ||
					!Object.keys(this.$team.pg.billing_details).length
						? '下一步'
						: $site.pg?.current_plan?.is_trial_plan
							? '升级计划'
							: '更改计划'
				}}
			</Button>
		</template>
	</Dialog>
</template>
<script>
import { getCachedDocumentResource, Progress } from 'jingrow-ui';
import SitePlansCards from './SitePlansCards.vue';
import { getPlans, getPlan } from '../data/plans';
import CardForm from './billing/CardForm.vue';
import BillingDetails from './billing/BillingDetails.vue';
import BuyPrepaidCreditsForm from './BuyPrepaidCreditsForm.vue';

export default {
	name: 'ManageSitePlansDialog',
	components: {
		CardForm,
		Progress,
		SitePlansCards,
		BillingDetails,
		BuyPrepaidCreditsForm,
	},
	props: {
		site: {
			type: String,
			required: true,
		},
	},
	data() {
		return {
			show: true,
			plan: null,
			step: 'site-plans',
			isAutomatedBilling: true,
			showAddPaymentModeDialog: false,
			showBillingDetailsDialog: false,
		};
	},
	watch: {
		site: {
			immediate: true,
			handler(siteName) {
				if (siteName) {
					if (this.$site?.pg?.plan) {
						this.plan = getPlan(this.$site.pg.plan);
					}
				}
			},
		},
	},
	methods: {
		handleNext() {
			if (
				!this.$team.pg.billing_details ||
				!Object.keys(this.$team.pg.billing_details).length
			) {
				this.step = 'billing-details';
				this.$team.reload();
			} else if (!this.$team.pg.payment_mode) {
				this.step = 'add-payment-mode';
			} else {
				this.changePlan();
			}
		},
		changePlan() {
			return this.$site.setPlan.submit(
				{ plan: this.plan.name },
				{
					onSuccess: () => {
						this.show = false;
						let plan = getPlans().find(
							(plan) => plan.name === this.$site.pg.plan,
						);
						let formattedPlan = plan
							? `${this.$format.planTitle(plan)}/月`
							: this.$site.pg.plan;
						this.$toast.success(`计划已更改为 ${formattedPlan}`);
					},
				},
			);
		},
		paymentModeAdded() {
			this.$team.reload();
			this.show = false;
			this.$toast.success(
				'支付方式已添加，计划已成功更改',
			);
			this.changePlan();
		},
	},
	computed: {
		$site() {
			return getCachedDocumentResource('Site', this.site);
		},
		showSetupSubscription() {
			return (
				!this.$team.pg.payment_mode ||
				!this.$team.pg.billing_details ||
				!Object.keys(this.$team.pg.billing_details).length
			);
		},
		progressLabel() {
			if (this.step === 'site-plans') {
				return '选择计划';
			} else if (this.step === 'billing-details') {
				return '添加账单详情';
			} else if (this.step === 'add-payment-mode') {
				return '添加支付方式';
			}
		},
	},
};
</script>