<template>
	<view>
		<NavBar />
		<view class="container">
			<view class="title">
				<PageTitle :title="$t('withdrawal.pageTitle')" />
			</view>
      <view v-if="showServiceChargeTips">
        <uni-forms ref="withdrawForm" :modelValue="withdrawFormData" :rules="withdrawFormRules">
          <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="withdrawFormData.mt4_login"
                @change="mtLoginChange"
            ></uni-data-select>
          </uni-forms-item>
          <view class="availableMoneyOut">
            {{ $t('common.availableMoneyOut') }}
            <text class="value">${{ availableMoneyOut ?? 0 }}</text>
          </view>
          <uni-forms-item name="usd_amount">
            <text class="uni-subtitle">{{ $t('form.amount.label') }}</text>
            <uni-easyinput type="digit" primaryColor="#29BBE4" v-model="withdrawFormData.usd_amount" @input="handleAmountInput"></uni-easyinput>
            <view :class="['minAmount', amountAvailable ? '' : 'unavailable']">{{ unavailableAmountTip }}</view>
          </uni-forms-item>
          <uni-forms-item name="bank_no">
            <text class="uni-subtitle">{{ $t('form.acceptWallet.label') }}</text>
            <uni-data-select
                :placeholder="$t('form.pleaseSelect')"
                :emptyTips="$t('common.empty')"
                :localdata="bankOptions"
                v-model="withdrawFormData.bank_no"
                @change="bankChange"
            ></uni-data-select>
          </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="filteredCurrencyOptions"
                v-model="withdrawFormData.currency_type"
                @change="currencyChange"
            ></uni-data-select>
          </uni-forms-item>
          <uni-forms-item name="remark">
            <text class="uni-subtitle">{{ $t('form.remark.label') }}</text>
            <uni-easyinput trim="all" primaryColor="#29BBE4" v-model="withdrawFormData.remark"></uni-easyinput>
          </uni-forms-item>
          <uni-popup ref="alertDialog" :isMaskClick="false">
            <view class="detailModal">
              <uni-icons type="closeempty" size="17" class="closeIcon" @click="closeDetailDialog"></uni-icons>
              <view class="detailContent">
                <view class="titleWrapper">
                  <view class="title">{{ selectedMtLogin.mt4_login }}{{ $t('withdrawal.accountWithdraw') }}</view>
                  <view class="value">${{ this.withdrawFormData?.usd_amount }}</view>
                </view>
                <uni-forms-item name="safe_pass">
                  <text class="uni-subtitle">{{ $t('form.CRMPassword.label') }}</text>
                  <uni-easyinput type="password" trim="all" primaryColor="#29BBE4" v-model="withdrawFormData.safe_pass"></uni-easyinput>
                </uni-forms-item>
                <button class="primaryButton" :disabled="submitBtnLoading" @click="handleSaveWithdraw">
                  <image v-show="submitBtnLoading" src="/static/loadingCircle.svg" mode="aspectFit" style="width: 16px; height: 16px"></image>
                  {{ $t('form.submit') }}
                </button>
              </view>
            </view>
          </uni-popup>
        </uni-forms>
        <view class="exchangeRate">
          <view class="label">{{ $t('common.exchangeRate') }}</view>
          <view class="value">{{ exchangeRate ?? '-' }}</view>
        </view>
        <view class="currency_amount">
          <view class="label">{{ $t('common.monetaryEquivalent') }}</view>
          <view class="value">{{ currency_amount ?? '-' }}</view>
        </view>
        <button class="primaryButton" type="button" :disabled="nextBtnLoading || !authStatus" @click="showDetailDialog">
          <image v-show="nextBtnLoading" src="/static/loadingCircle.svg" mode="aspectFit" style="width: 16px; height: 16px"></image>
          {{ $t('form.next') }}
        </button>
      </view>
      <view v-else style="display: flex;flex-direction: column">
        <view style="display: flex;width: 100%;justify-content: center;flex-direction: column;align-items: center;padding-top: 100px;">
          <image src="/static/warning.png" style="width: 50px;height: 50px;" mode="aspectFit"></image>
          <view style="font-size: 24px;font-weight: 600">{{ $t('common.importantNote') }}</view>
        </view>
        <view style="padding-top: 40px;color: rgb(153, 153, 153);font-weight: 500">
          {{ $t('common.dearCustomer') }}
        </view>
        <view style="padding-top: 30px;color: rgb(153, 153, 153);font-weight: 500">
          {{ $t('common.serviceChargeTips',{num: num-1, num2: num,service_charge:service_charge} ) }}
        </view>
        <view style="padding-top: 30px;color: rgb(153, 153, 153);font-weight: 500">
          {{ $t('common.importantNote2') }}
        </view>
        <view>
          <button class="primaryButton" type="button" style="margin-bottom: 20px;margin-top: 50px" @click="showServiceChargeTips = true">
            {{ $t('common.importantNoteBtn2') }}
          </button>
          <button class="secondaryButton" type="button" @click="back">
            {{ $t('common.importantNoteBtn') }}
          </button>
        </view>
      </view>

		</view>
	</view>
</template>

<script>
import { getMTAccounts2, getIfChargeCommission } from '@/services/home/home.ts';
import { getExchangeRate, getGoldRange } from '@/services/capital/deposit.ts';
import { saveWithdraw } from '@/services/capital/withdraw.ts';
import { getBankList, getPersonalAuthStatus } from '@/services/user.ts';
import { getDictByCode } from '@/services/common.ts';
import { UserLanguage } from '@/utils/const';
export default {
	name: '',
	data() {
		return {
			authStatus: false,
			paramsMtLogin: undefined,
			mtLoginOptions: [],
			mtlogins: {},
			selectedMtLogin: null,
			bankOptions: [],
			banks: {},
			selectedBank: null,
			currencyOptions: [],
			goldRange: null,
			amountAvailable: true,
			unavailableAmountTip: '',
			availableMoneyOut: 0,
			exchangeRate: undefined,
			rateSign: undefined,
			currency_amount: undefined,
			nextBtnLoading: false,
			submitBtnLoading: false,
			withdrawFormData: { usd_amount: '' },
			withdrawFormRules: {
				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?.out_min) {
											// 不通过返回 reject(new Error('错误信息'))
											this.amountAvailable = false;
											reject(new Error(' '));
										} else if (Number(value) > (this.availableMoneyOut ?? 0)) {
											this.amountAvailable = false;
											reject(new Error(' '));
											this.unavailableAmountTip = `${this.$t('withdrawal.maxAmount')} $${this.availableMoneyOut ?? 0}`;
										} else {
											// 通过返回 resolve
											this.amountAvailable = true;
											resolve();
										}
									}, 0);
								});
							}
						}
					]
				},
				currency_type: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.currencyType.required')
						}
					]
				},
				bank_no: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.acceptWallet.required')
						}
					]
				},
				safe_pass: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.CRMPassword.required')
						}
					]
				}
			},
      showServiceChargeTips:true,
      num:0,
      service_charge:0,
      serviceChargeTips:''
		};
	},
	methods: {
		handleAmountInput() {
			this.amountAvailable = true;
			this.unavailableAmountTip = `${this.$t('withdrawal.minAmount')} $${this.goldRange?.out_min ?? 0}`;
		},
		goldRangePlaceholderRender(min, max) {
			return `${this.$t('form.amount.placeholderBefore')}${min}-${max}${this.$t('form.amount.placeholderAfter')}`;
		},
		async getAuthStatus() {
			const res = await getPersonalAuthStatus();
			if (res && res.code === 0) {
				this.authStatus = res.data.address == 1 && res.data.identity == 1 && res.data.email == 1;
				if (!this.authStatus) {
					this.$cusModal.showModal({
						type: 'message',
						status: 'warning',
						contentText: this.$t('common.noKycWithdraw'),
						onClose: () => {
							uni.navigateBack();
						}
					});
				}
			}
		},
		async getMtLoginData() {
			const res = await getMTAccounts2({ server_type: 'live' });
			if (res && res.code === 0) {
				this.mtLoginOptions = res.data?.map((mtAccount) => ({
					text: `${mtAccount.mt4_server_name} ${mtAccount.mt4_login}`,
					value: mtAccount.mt4_login?.toString()
				}));
				res.data?.forEach((mtAccount) => {
					this.mtlogins[mtAccount.mt4_login] = mtAccount;
				});
				if (res.data[0]) {
					if (this.paramsMtLogin && this.mtlogins[this.paramsMtLogin]) {
						this.withdrawFormData.mt4_login = this.paramsMtLogin;
						this.mtLoginChange(this.paramsMtLogin);
					} else {
						this.withdrawFormData.mt4_login = res.data[0].mt4_login;
						this.mtLoginChange(res.data[0].mt4_login);
					}
				}
			}
		},
		async getBankListData() {
			const res = await getBankList();
			if (res && res.code === 0) {
				this.bankOptions = res.data.map((item) => ({
					text: item.bank_no,
					value: item.bank_no,
					disable: item.apply_status !== 0
				}));
				res.data?.forEach((bank) => {
					this.banks[bank.bank_no] = bank;
				});
			}
		},
		async getCurrency() {
			const res = await getDictByCode('currency_type');
			if (res && res.code === 0) {
				this.currencyOptions = res.data?.map((item) => ({
					text: item.fun_item_text,
					value: item.fun_item_code
				}));
			}
		},
		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;
			}
		},
		async getRate() {
			const params = {
				mt4_server: this.selectedMtLogin?.mt4_server,
				mt4_login: this.selectedMtLogin?.mt4_login,
				exchange_currency: this.withdrawFormData?.currency_type,
				type: 'mt4',
				io: 'o'
			};
			const res = await getExchangeRate(params);
			if (res && res.code === 0) {
				this.exchangeRate = res.data.exchange_rate;
				this.rateSign = res.data.exchange_rate_sign;
			}
		},
		showDetailDialog() {
			this.$refs.withdrawForm.validateField(['mt4_login', 'usd_amount', 'currency_type', 'bank_no']).then(() => {
				if (this.selectedBank.bank_standby_1 !== 'B1' && Number(this.selectedBank.verify_email) === 0) {
					uni.navigateTo({
						url: `/pages/capital/verifyWallet/index?id=${this.selectedBank.id}`
					});
					return;
				}
				this.$refs.alertDialog.open();
			});
		},
		closeDetailDialog() {
			this.$refs.alertDialog.close();
		},
		async handleSaveWithdraw() {
			this.$refs.withdrawForm.validate().then(async (fields) => {
				this.submitBtnLoading = true;
				const res = await saveWithdraw({
					...fields,
					bank_cards: this.selectedBank.bank_cards,
					bank_name: this.selectedBank.bank_name,
					bank_sub_name: this.selectedBank.bank_sub_name,
					bank_swift: this.selectedBank.bank_swift,
					bank_remark: this.selectedBank.bank_remark,
					currency_amount: this.currency_amount,
					exchange_rate: this.exchangeRate,
					exchange_rate_sign: this.rateSign,
					qcc_language: UserLanguage,
					mt4_server: this.selectedMtLogin?.mt4_server
				});
				this.closeDetailDialog();
				this.submitBtnLoading = false;
				if (res && res.code === 0) {
					uni.redirectTo({
						url: '/pages/capital/withdraw/success/index'
					});
				} else {
					this.$nextTick(() => {						
						this.$cusModal.showModal({
							type: 'message',
							status: 'warning',
							contentText: res.msg ?? this.$t('common.error.sysError')
						});
					})
				}
			});
		},
		mtLoginChange(val) {
			this.selectedMtLogin = this.mtlogins[val];
			if (this.selectedMtLogin) {
				if (this.selectedMtLogin.ifCent === 'YES') {
					this.availableMoneyOut = (
						((this.selectedMtLogin.margin_free ?? 0) - (this.selectedMtLogin.margin ?? 0) - (this.selectedMtLogin.mt4_credit ?? 0)) /
						100
					).toFixed(2);
				} else if (this.selectedMtLogin.ifCent === 'NO') {
					this.availableMoneyOut = (
						(((this.selectedMtLogin.margin_free ?? 0) - (this.selectedMtLogin.margin ?? 0) - (this.selectedMtLogin.mt4_credit ?? 0)) * 100) /
						100
					).toFixed(2);
				}
				this.getGoldRangeData();
			}
		},
		currencyChange(val) {
			this.getRate();
		},
		bankChange(val) {
			this.selectedBank = this.banks[val];
			this.withdrawFormData.currency_type = this.selectedBank.bank_currency;
			this.getRate();
		},
    async loadOutServiceChargeTips(){
      const res = await getIfChargeCommission();
      if (res && res.code === 0) {
        let data = res.data
        if (data.ifChargeCommission){
          this.num = data.num
          this.service_charge = data.service_charge
          this.showServiceChargeTips = false
        }
      }
    },
    back(){
      uni.navigateBack();
    }
	},
	computed: {
		filteredCurrencyOptions() {
			return this.currencyOptions.filter((item) => item.value === this.selectedBank?.bank_currency);
		}
	},
	watch: {
		'withdrawFormData.usd_amount': {
			handler(newVal, oldVal) {
				this.currency_amount = this.exchangeRate && newVal ? this.exchangeRate * newVal : undefined;
			}
		},
		goldRange: {
			handler(newVal, oldVal) {
				this.unavailableAmountTip = `${this.$t('withdrawal.minAmount')} $${newVal?.out_min??0}`;
			}
		},
		exchangeRate: {
			handler(newVal, oldVal) {
				this.currency_amount = newVal && this.withdrawFormData.usd_amount ? (newVal * this.withdrawFormData.usd_amount).toFixed(2) : '-';
			}
		}
	},
	created() {
		this.getBankListData();
		this.getCurrency();
		this.getAuthStatus();
	},
	onLoad(params) {
		if (params.mtLogin) {
			this.paramsMtLogin = params.mtLogin;
		}
		this.getMtLoginData();
		this.loadOutServiceChargeTips()
	}
};
</script>

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