<template>
	<Dialog :options="{ title: '添加货币汇率', size: 'lg' }">
		<template #body-content>
			<div class="grid grid-cols-2 gap-4">
				<FormControl
					label="源货币"
					v-model="fromCurrency"
					variant="subtle"
					:options="['USD']"
					name="from_currency"
					type="select"
					class="mb-5"
				/>

				<FormControl
					label="目标货币"
					v-model="toCurrency"
					name="to_currency"
					variant="subtle"
					:options="['KES']"
					type="select"
					class="mb-5"
				/>

				<FormControl
					label="汇率"
					v-model="exchangeRate"
					name="exchange_rate"
					class="mb-5"
					type="number"
					required
				/>
			</div>

			<div class="mt-4 flex w-full items-center justify-center">
				<Button
					@click="saveExchangeRate"
					class="justify-center w-full"
					variant="solid"
					type="primary"
					>添加货币汇率</Button
				>
			</div>
		</template>
		<ErrorMessage class="mt-2" :message="ErrorMessage" />
	</Dialog>
</template>

<script>
import { toast } from 'vue-sonner';
import FormControl from 'jingrow-ui/src/components/FormControl.vue';
import ErrorMessage from 'jingrow-ui/src/components/ErrorMessage.vue';

export default {
	name: 'AddExchangeRate',
	data() {
		return {
			fromCurrency: 'KES',
			toCurrency: 'USD',
			exchangeRate: '',
		};
	},

	resources: {
		addCurrencyExchange() {
			return {
				url: 'jcloud.api.regional_payments.mpesa.utils.create_exchange_rate',
				params: {
					from_currency: this.fromCurrency,
					to_currency: this.toCurrency,
					exchange_rate: this.exchangeRate,
				},
				validate() {
					if (!this.fromCurrency || !this.toCurrency || !this.exchangeRate) {
						toast.error('所有字段都是必填项');
						return false;
					}
				},
				async onSuccess() {
					if (data) {
						toast.success('货币汇率添加成功');
						this.$emit('close');
					} else {
						toast.error('添加货币汇率失败');
					}
				},
			};
		},
	},

	methods: {
		async saveExchangeRate() {
			try {
				const response = await this.$resources.addCurrencyExchange.submit();
				if (response) {
					this.$toast.success('货币汇率添加成功');
					this.fromCurrency = '';
					this.toCurrency = '';
					this.exchangeRate = '';
				}
				this.$emit('closeDialog');
			} catch (error) {
				console.log(error);
				this.$toast.error(`添加货币汇率时出错: ${error.message}`);
			}
		},
	},
};
</script>