<template>
	<view>
		<NavBar />
		<view class="container">
			<view class="title">
				<PageTitle title="USDT" backTarget="/pages/capital/deposit/index" />
			</view>
			<uni-forms ref="depositForm" :modelValue="depositFormData" :rules="depositFormRules">
				<uni-forms-item name="mt4_server">
					<text class="uni-subtitle">{{ $t('form.mtServer.label') }}</text>
					<uni-data-select
						:placeholder="$t('form.pleaseSelect')"
						:emptyTips="$t('common.empty')"
						:localdata="mtServerOptions"
						v-model="depositFormData.mt4_server"
						@change="mtServerChange"
						:clear="false"
					></uni-data-select>
				</uni-forms-item>
				<uni-forms-item name="mt4_login">
					<text class="uni-subtitle">{{ $t('form.mtAccount.label') }}</text>
					<uni-data-select
						:placeholder="$t('form.pleaseSelect')"
						:emptyTips="$t('common.empty')"
						:localdata="mtLoginOptions"
						v-model="depositFormData.mt4_login"
						@change="mtLoginChange"
					></uni-data-select>
				</uni-forms-item>
				<uni-forms-item name="usd_amount">
					<text class="uni-subtitle">{{ $t('form.amount.label') }}</text>
					<uni-easyinput type="number" primaryColor="#29BBE4" v-model="depositFormData.usd_amount" @input="handleAmountInput"></uni-easyinput>
					<view v-if="goldRange" :class="['minAmount', amountAvailable ? '' : 'unavailable']">{{ $t('deposit.minAmount') }} ${{ goldRange?.in_min }}</view>
				</uni-forms-item>
				<uni-forms-item name="currency_type">
					<text class="uni-subtitle">{{ $t('form.currencyType.label') }}</text>
					<uni-data-select
						:placeholder="$t('form.pleaseSelect')"
						:emptyTips="$t('common.empty')"
						:localdata="currencyOptions"
						v-model="depositFormData.currency_type"
						@change="currencyChange"
					></uni-data-select>
				</uni-forms-item>
				<view class="exchangeRate">
					<view class="label">{{ $t('common.exchangeRate') }}</view>
					<view class="value">{{ exchangeRate ?? '-' }}</view>
				</view>
				<view class="currency_amount">
					<view class="label">{{ $t('deposit.remittanceAmount') }}</view>
					<view class="value">{{ currency_amount ?? '-' }}</view>
				</view>
				<view class="exchangeRate" v-show="actId">
					<view class="label">{{ $t('deposit.presentedCredit') }}</view>
					<view class="value">{{ presentedCredit ? `$${presentedCredit}` : '-' }}</view>
				</view>
				<view class="exchangeRate" v-show="actId">
					<view class="label">{{ $t('deposit.presentedAmountResidue') }}</view>
					<view class="value">{{ presentedAmountResidue ? `$${presentedAmountResidue}` : '-' }}</view>
				</view>
        <view class="exchangeRate" v-show="pay_subsidy">
          <view class="label">{{ $t('deposit.paySubsidy') }}</view>
          <view class="value">{{ paySubsidy ? `$${paySubsidy}` : '-' }}</view>
        </view>
			</uni-forms>
			<button class="primaryButton" type="button" :disabled="!exchangeRate||nextBtnLoading" @click="handleSaveDeposit">
				<image v-show="nextBtnLoading" src="/static/loadingCircle.svg" mode="aspectFit" style="width: 16px; height: 16px"></image>
				{{ $t('form.next') }}
			</button>
		</view>
	</view>
</template>

<script>
import { getMTAccounts } from '@/services/home/home.ts';
import { saveDeposit, getExchangeRate, getGoldRange, getCurrencyByPay, getDepositSign, getActInfo, getPresentedCredit } from '@/services/capital/deposit.ts';
import { getMtServers, getCustomerMtLoginList } from '@/services/common.ts';
import { UserLanguage } from '@/utils/const';
export default {
	name: '',
	data() {
		return {
			actId: undefined,
			actInfo: null,
			mt4Server: undefined,
			mt4Login: undefined,
			mtServerOptions: [],
			mtLoginOptions: [],
			currencyOptions: [],
			mtlogins: {},
			selectedMtLogin: null,
			currency_amount: undefined,
			goldRange: null,
			amountAvailable: true,
			exchangeRate: undefined,
			rateSign: undefined,
      paySubsidy: undefined,
      pay_subsidy: undefined,
			presentedCredit: undefined, //赠送信用金
			presentedAmountResidue: undefined, //剩余赠金额度
			depositFormData: { usd_amount: '' },
			nextBtnLoading: false,
			depositFormRules: {
				mt4_login: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.mtAccount.required')
						}
					]
				},
				usd_amount: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.amount.required')
						},
						{
							validateFunction: (rule, value, data, callback) => {
								// 异步需要返回 Promise 对象
								return new Promise((resolve, reject) => {
									setTimeout(() => {
										if (value < this.goldRange?.in_min) {
											// 不通过返回 reject(new Error('错误信息'))
											this.amountAvailable = false;
											reject(new Error(' '));
										} else {
											// 通过返回 resolve
											this.amountAvailable = true;
											resolve();
										}
									}, 0);
								});
							}
						}
					]
				},
				currency_type: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.currencyType.required')
						}
					]
				}
			}
		};
	},
	methods: {
		handleAmountInput(val) {
			this.amountAvailable = true;
			if (this.actId) {
				this.calculatePresentedCredit(this.actId, val);
			}
		},
		goldRangePlaceholderRender(min, max) {
			return `${this.$t('form.amount.placeholderBefore')}${min}-${max}${this.$t('form.amount.placeholderAfter')}`;
		},
		async getMtLoginData(serverId) {
			const res = await getCustomerMtLoginList({ qcc_language: UserLanguage, mt4_server: serverId, activity_id: this.actId });
			if (res && res.code === 0) {
				this.mtLoginOptions = res.data?.map((mtAccount) => ({
					text: mtAccount.mt4_login,
					value: mtAccount.mt4_login
				}));
				res.data?.forEach((mtAccount) => {
					this.mtlogins[mtAccount.mt4_login] = mtAccount;
				});
				if (res.data[0] && !this.actId && !this.mt4Server && !this.mt4Login) {
					this.depositFormData.mt4_login = res.data[0].mt4_login;
					this.mtLoginChange(res.data[0].mt4_login);
				}
			}
		},
		async getMtServerOptions() {
			const res = await getMtServers({ qcc_language: UserLanguage, server_type: 'live' });
			if (res && res.code === 0) {
				let tempOptions = res.data?.map((item) => ({
					text: item.server_name,
					value: item.id
				}));
				if (this.actInfo && this.actInfo.actMtLogin && this.actInfo.actMtServer) {
					tempOptions = tempOptions.filter((item) => item.value === Number(this.actInfo.actMtServer));
				}
				this.mtServerOptions = tempOptions;
			}
			if (this.mtServerOptions[0] && !this.actId && !this.mt4Server && !this.mt4Login) {
				this.depositFormData.mt4_server = this.mtServerOptions[0].value;
			}
		},
		async getActInfoFn(actId) {
			const res = await getActInfo(actId);
			if (res && res.code === 0) {
				this.actInfo = res.data;
				if (res.data.actMtLogin && res.data.actMtServer) {
					res.data.actMtLogin = Number(res.data.actMtLogin);
					res.data.actMtServer = Number(res.data.actMtServer);
					this.mtLoginOptions = [{ text: res.data.actMtLogin, value: res.data.actMtLogin }];
					this.mtServerOptions = this.mtServerOptions.filter((mtServer) => mtServer.value === res.data.actMtServer);
					this.depositFormData.mt4_login = res.data.actMtLogin;
					this.depositFormData.mt4_server = res.data.actMtServer;
					this.mtLoginChange({
						mt4_login: res.data.actMtLogin,
						mt4_server: res.data.actMtServer,
						mt4_server_name: res.data.actMtServerName
					});
				}
			} else {
				this.$cusModal.showModal({
					type: 'message',
					status: 'warning',
					contentText: res.msg ?? this.$t('common.error.sysError'),
					onClose() {
						uni.navigateBack();
					}
				});
			}
		},
		async calculatePresentedCredit(actId, usdAmount) {
			this.presentedCredit = undefined;
			this.presentedAmountResidue = undefined;
			const res = await getPresentedCredit({
				act_id: actId,
				usd_amount: usdAmount
			});
			if (res && res.code === 0) {
				this.presentedCredit = res.data;
				if (res.msg) {
					this.presentedAmountResidue = JSON.parse(res.msg).presented_amount_residue;
				}
			}
		},
		async getGoldRangeData() {
			const res = await getGoldRange({ mt4_login: this.selectedMtLogin.mt4_login, mt4_server: this.selectedMtLogin.mt4_server });
			if (res && res.code === 0) {
				this.goldRange = res.data;
			}
		},
		mtLoginChange(val) {
			if (!val) {
				this.depositFormData.mt4_login = undefined;
				this.goldRange = null;
				return;
			}
			if (typeof val !== 'object') {
				this.selectedMtLogin = this.mtlogins[val];
			} else {
				this.selectedMtLogin = val;
			}
			this.getGoldRangeData();
		},
		async mtServerChange(val) {
			this.mtLoginChange(undefined);
			await this.getMtLoginData(val);
		},
		async getCurrencyByPayId(pay_id) {
			const res = await getCurrencyByPay({ pay_id });
			if (res && res.code === 0) {
				this.currencyOptions = res.data?.map((item) => ({
					text: item.currency,
					value: item.currency
				}));
			}
		},
		async getRate() {
			const params = {
				mt4_server: this.selectedMtLogin?.mt4_server,
				mt4_login: this.selectedMtLogin?.mt4_login,
				exchange_currency: this.depositFormData?.currency_type,
				type: 'mt4',
				io: 'i'
			};
			const res = await getExchangeRate(params);
			if (res && res.code === 0) {
				this.exchangeRate = res.data.exchange_rate;
				this.rateSign = res.data.exchange_rate_sign;
				this.getGoldRangeData();
			}
		},
		currencyChange(val) {
			this.getRate();
		},
		async handleSaveDeposit() {
			this.$refs.depositForm.validate().then(async (fields) => {
				const params = {
					...fields,
					act_id: this.actId,
					// bank_desc: this.selectedIBMtLogin?.pay_config_bank_id,
					currency_amount: this.currency_amount,
					exchange_rate: this.exchangeRate,
					exchange_rate_sign: this.rateSign,
					language: UserLanguage,
					mt4_server: this.selectedMtLogin?.mt4_server,
					pay_channel: this.pageParams?.pay_code,
					usd_service_charge: 0
				};
				this.nextBtnLoading = true;
				const res = await saveDeposit(params);
				this.nextBtnLoading = false;
				if (res && res.code === 0) {
					const resp = await getDepositSign({ ...res.data, language: UserLanguage });
					if (resp && resp.code === 0) {
						resp.data.pay_code = this.pageParams.pay_code;
						uni.navigateTo({
							url: `/pages/capital/deposit/remittanceInfo/index?depositData=${JSON.stringify(resp.data)}`
						});
					}
				} else {
					this.$cusModal.showModal({
						type: 'message',
						status: 'warning',
						contentText: res.msg ?? this.$t('common.error.sysError')
					});
				}
			});
		}
	},
	watch: {
		'depositFormData.currency_type': {
			handler(newVal, oldVal) {
				if (this.depositFormData.currency_amount) {
				}
			}
		},
		'depositFormData.usd_amount': {
			handler(newVal, oldVal) {
				this.currency_amount = this.exchangeRate && newVal ? (this.exchangeRate * newVal).toFixed(2) : undefined;
        this.paySubsidy = this.pay_subsidy && newVal ? ((this.pay_subsidy * newVal) / 100).toFixed(2) : undefined;
      }
		},
		exchangeRate: {
			handler(newVal, oldVal) {
				this.currency_amount = newVal && this.depositFormData.usd_amount ? (newVal * this.depositFormData.usd_amount).toFixed(2) : '-';
			}
		}
	},
	created() {
		this.getMtServerOptions();
	},
	async onLoad(params) {
		this.pageParams = params;
    this.pay_subsidy = this.pageParams.pay_subsidy
		if (params?.pay_id) {
			this.getCurrencyByPayId(params.pay_id);
		}
		const actId = uni.getStorageSync('actId');
		const mt4Server = Number(uni.getStorageSync('curs'));
		const mt4Login = Number(uni.getStorageSync('curl'));
		if (actId) {
			this.actId = actId;
			this.getActInfoFn(actId);
		}
		if (mt4Server) {
			this.mt4Server = mt4Server;
			this.depositFormData.mt4_server = mt4Server;
			await this.mtServerChange(mt4Server);
		}
		if (mt4Login) {
			this.mt4Login = mt4Login;
			this.depositFormData.mt4_login = mt4Login;
			this.mtLoginChange(mt4Login);
		}
	}
};
</script>

<style lang="scss" scoped>
@import './index.scss';
</style>
