<template>
	<Card
		v-if="!$team.pg?.jerp_partner"
		title="Jingrow 合作伙伴"
		subtitle="与您的账户关联的 Jingrow 合作伙伴"
		class="mx-auto max-w-3xl"
	>
		<template #actions>
			<Button
				v-if="!$team.pg?.partner_email"
				icon-left="edit"
				@click="showAddPartnerCodeDialog = true"
			>
				添加合作伙伴代码
			</Button>
			<Button
				v-else
				icon-left="trash-2"
				@click="showRemovePartnerDialog = true"
			>
				取消关联合作伙伴
			</Button>
		</template>
		<div class="py-4">
			<span
				class="text-base font-medium text-gray-700"
				v-if="!$team.pg?.partner_email"
			>
				有 Jingrow 合作伙伴推荐代码吗？点击
				<strong>添加合作伙伴代码</strong> 以与您的合作伙伴团队关联。
			</span>
			<ListItem
				v-else
				:title="partner_billing_name"
				:subtitle="$team.pg?.partner_email"
			/>
		</div>
		<Dialog
			:options="{
				title: '关联合作伙伴账户',
				actions: [
					{
						label: '提交',
						variant: 'solid',
						onClick: () => $resources.addPartnerCode.submit(),
					},
				],
			}"
			v-model="showAddPartnerCodeDialog"
		>
			<template v-slot:body-content>
				<p class="pb-2 text-p-base">
					输入您的合作伙伴提供的合作伙伴代码
				</p>
				<div class="rounded border border-gray-200 bg-gray-100 p-2 mb-4">
					<span class="text-sm leading-[1.5] text-gray-700">
						<strong>注意</strong>: 与合作伙伴关联后，以下信息将与您的合作伙伴团队共享：
						<br />
						<li>账单名称</li>
						<li>月度账单金额</li>
					</span>
				</div>
				<FormControl
					placeholder="例如：rGjw3hJ81b"
					v-model="code"
					@input="referralCodeChange"
				/>
				<div class="mt-1">
					<div v-if="partnerExists" class="text-sm text-green-600" role="alert">
						推荐代码 {{ code }} 属于 {{ partner }}
					</div>
				</div>
			</template>
		</Dialog>

		<Dialog
			v-model="showRemovePartnerDialog"
			:options="{
				title: '移除合作伙伴',
				actions: [
					{
						label: '移除',
						variant: 'solid',
						theme: 'red',
						onClick: () => {
							$resources.removePartner.submit();
						},
					},
				],
			}"
		>
			<template v-slot:body-content>
				<p class="text-p-base pb-3">
					这将移除与您的账户关联的合作伙伴。您确定要移除该合作伙伴吗？
				</p>
			</template>
		</Dialog>
	</Card>
</template>
<script>
import { Card, FormControl, jingrowRequest, debounce } from 'jingrow-ui';
import { DashboardError } from '../../../utils/error';
import { toast } from 'vue-sonner';
export default {
	name: 'AccountPartner',
	components: {
		Card,
		FormControl,
	},
	data() {
		return {
			showAddPartnerCodeDialog: false,
			showRemovePartnerDialog: false,
			code: '',
			partnerExists: false,
			partner: '',
			errorMessage: '',
		};
	},
	resources: {
		addPartnerCode() {
			return {
				url: 'jcloud.api.partner.add_partner',
				params: {
					referral_code: this.code,
				},
				onSuccess(data) {
					this.showAddPartnerCodeDialog = false;
					if (data === 'Request already sent') {
						toast.error('Approval Request has already been sent to Partner');
					} else {
						toast.success('Approval Request has been sent to Partner');
					}
				},
				onError() {
					throw new DashboardError('Failed to add Partner Code');
				},
			};
		},
		partnerName() {
			return {
				url: 'jcloud.api.partner.get_partner_name',
				auto: true,
				params: {
					partner_email: this.$team.pg?.partner_email,
				},
			};
		},
		removePartner() {
			return {
url: 'jcloud.api.partner.remove_partner',
				onSuccess() {
					this.showRemovePartnerDialog = false;
					toast.success('合作伙伴已成功移除');
				},
				onError() {
					throw new DashboardError('移除合作伙伴失败');
				},
			};
		},
	},
	methods: {
		referralCodeChange: debounce(async function (e) {
			let code = e.target.value;
			this.partnerExists = false;

			let result = await jingrowRequest({
				url: 'jcloud.api.partner.validate_partner_code',
				params: { code: code },
			});

			let isValidCode = result[0];
			let partnerName = result[1];

			if (isValidCode) {
				this.partnerExists = true;
				this.referralCode = code;
				this.partner = partnerName;
			} else {
				this.errorMessage = `${code} 是无效的推荐码`;
			}
		}, 500),
	},
	computed: {
		partner_billing_name() {
			return this.$resources.partnerName.data;
		},
	},
};
</script>