<template>
	<Dialog
		:options="{
			title: '告诉我们您离开的原因',
			actions: [
				{
					label: '提交',
					variant: 'solid',
					loading: $resources.submitFeedback.loading,
					onClick: () => {
						$resources.submitFeedback.submit({
							feedback: this.feedback
						});
					}
				}
			]
		}"
		v-model="show"
	>
		<template v-slot:body-content>
			<p class="mb-5 text-sm text-gray-800">
				通过分享您的想法，帮助我们改善您的体验。
			</p>
			<div class="mt-3">
				<span class="mb-2 block text-sm leading-4 text-gray-600">
					请评价您的体验
				</span>
				<StarRatingInput v-model="rating" />
			</div>
			<FormControl
				class="mt-4"
				type="select"
				:options="options"
				size="md"
				variant="outline"
				placeholder="选择一个原因"
				v-model="feedback"
				required
			/>
			<FormControl
				class="mt-4"
				type="textarea"
				variant="outline"
				placeholder="我离开 Jingrow 的原因是..."
				size="md"
				v-model="note"
			/>
			<ErrorMessage class="mt-2" :message="$resources.submitFeedback.error" />
		</template>
	</Dialog>
</template>

<script>
import FormControl from 'jingrow-ui/src/components/FormControl.vue';
import StarRatingInput from './StarRatingInput.vue';
import { DashboardError } from '../utils/error';

export default {
	name: 'ChurnFeedbackDialog',
	emits: ['updated'],
	props: ['team'],
	components: {
		StarRatingInput
	},
	data() {
		return {
			feedback: '',
			route: '',
			note: '',
			show: true,
			rating: 0
		};
	},
	resources: {
		submitFeedback() {
			return {
				url: 'jcloud.api.account.feedback',
				makeParams() {
					return {
						team: this.team,
						message: this.feedback,
						route: this.$route?.name,
						note: this.note,
						rating: this.rating
					};
				},
				validate() {
					if (!this.feedback) {
						throw new DashboardError('请选择一个原因');
					}

					if (this.rating == 0) {
						throw new DashboardError('请评价您的体验');
					}

					if (
						[
							'支付问题',
							'缺少功能',
							'我的原因不在此列表中'
						].includes(this.feedback) &&
						!this.note
					) {
						throw new DashboardError('请简要说明原因');
					}
				},
				onSuccess() {
					this.show = false;
					this.$emit('updated');

					setTimeout(() => {
						window.location.href = '/dashboard';
					}, 1000);
				}
			};
		}
	},
	computed: {
		options() {
			return [
				'我要迁移到其他产品',
				'我只是在探索这个产品',
				'我更喜欢自己托管实例',
				'已将站点迁移到另一个Jingrow账户',
				'我不喜欢Jingrow的体验',
				'Jingrow对我来说太贵了',
				'支付问题',
				'缺少功能',
				'我的原因不在此列表中'
			];
		}
	}
};
</script>