<template>
	<SiteAppPlanSelectorDialog
		v-model="showDialog"
		:app="app"
		:currentPlan="currentPlan"
		@plan-select="handlePlanSelect"
	/>
</template>

<script>
import { getToastErrorMessage } from '../../utils/toast';
import SiteAppPlanSelectorDialog from './SiteAppPlanSelectorDialog.vue';
import { toast } from 'vue-sonner';

export default {
	components: {
		SiteAppPlanSelectorDialog
	},
	props: ['app', 'currentPlan'],
	emits: ['plan-changed', 'plan-selected', 'onPlanSelected'],
	data() {
		return {
			showDialog: true
		};
	},
	resources: {
		changeAppPlan: {
			url: 'jcloud.api.marketplace.change_app_plan'
		}
	},
	methods: {
		handlePlanSelect(plan) {
			if (this.currentPlan) {
				// 更改现有计划
				toast.promise(
					this.$resources.changeAppPlan.submit({
						subscription: this.app.subscription.name,
						new_plan: plan.name
					}),
					{
						loading: '正在更改计划...',
						success: () => {
							this.$emit('plan-changed', plan);
							return '计划更改成功';
						},
						error: e => getToastErrorMessage(e)
					}
				);
			} else {
				this.$emit('plan-selected', plan);
				this.$emit('onPlanSelected', plan);
				this.showDialog = false;
			}
		}
	}
};
</script>