<template>
	<view>
		<NavBar />
		<view class="container">
			<view class="title">
				<PageTitle :title="$t('ib.dailyFunds.crmGoldOut')" />
			</view>
      <view v-if="showServiceChargeTips">
        <uni-forms ref="withdrawForm" :modelValue="withdrawFormData" :rules="withdrawFormRules">
          <view class="availableMoneyOut">
            {{ $t('common.availableMoneyOut') }}
            <text class="value">${{ ibFund?.amount ?? '-' }}</text>
          </view>
          <uni-forms-item name="usd_amount">
            <text class="uni-subtitle">{{ $t('form.amount.label') }}</text>
            <uni-easyinput trim="all" 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">{{ $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="handleSaveIBWithdraw">
                  <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" @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 { getIbFundSum, getIfChargeCommission } from '@/services/home/home.ts';
import { getExchangeRate, getGoldRange } from '@/services/capital/deposit.ts';
import { saveIBWithdraw } from '@/services/capital/withdraw.ts';
import { getBankList, getPersonalAuthStatus } from '@/services/user.ts';
import { getDictByCode, getSys } from '@/services/common.ts';
import { UserLanguage } from '@/utils/const';
export default {
	name: '',
	data() {
		return {
			ibFund: {},
			bankOptions: [],
			banks: {},
			selectedBank: null,
			currencyOptions: [],
			goldRange: null,
			amountAvailable: true,
			unavailableAmountTip: '',
			exchangeRate: undefined,
			rateSign: undefined,
			currency_amount: undefined,
			nextBtnLoading: false,
			submitBtnLoading: false,
			withdrawFormData: {},
			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 (Number(value) < this.goldRange?.sys_min_out) {
											// 不通过返回 reject(new Error('错误信息'))
											this.amountAvailable = false;
											reject(new Error(' '));
										} else if (Number(value) > (this.ibFund?.amount ?? 0)) {
											this.amountAvailable = false;
											reject(new Error(' '));
											this.unavailableAmountTip = `${this.$t('withdrawal.maxAmount')} $${this.ibFund?.amount ?? 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?.sys_min_out??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 getIbFundData() {
			const res = await getIbFundSum();
			if (res && res.code === 0) {
				this.ibFund = res.data;
			}
		},
		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 getSys();
			if (res && res.code === 0) {
				const temp = {};
				res.data.forEach((item) => {
					temp[item.sub_type] = item.text;
				});
				this.goldRange = temp;
			}
		},
		async getRate() {
			const params = {
				exchange_currency: this.withdrawFormData?.currency_type,
				type: 'crm',
				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 handleSaveIBWithdraw() {
			this.$refs.withdrawForm.validate().then(async (fields) => {
				this.submitBtnLoading = true;
				const res = await saveIBWithdraw({
					...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
				});
				this.submitBtnLoading = false;
				if (res && res.code === 0) {
					uni.redirectTo({
						url: '/pages/capital/ibWithdraw/success/index'
					});
				} else {
					this.closeDetailDialog()
					this.$nextTick(() => {
						this.$cusModal.showModal({
							type: 'message',
							status: 'warning',
							contentText: res.msg ?? this.$t('common.error.sysError')
						});
					})
				}
			});
		},
		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();
    }
	},
	created() {
		this.getBankListData();
		this.getCurrency();
		this.getIbFundData();
		this.getGoldRangeData();
		this.getAuthStatus();
    this.loadOutServiceChargeTips()
	},
	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')} $${this.goldRange?.sys_min_out??0}`;
			}
		},
		exchangeRate: {
			handler(newVal, oldVal) {
				this.currency_amount = newVal && this.withdrawFormData.usd_amount ? (newVal * this.withdrawFormData.usd_amount).toFixed(2) : '-';
			}
		}
	}
};
</script>

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