<template>
	<view>
		<NavBar />
		<view class="container">
			<view class="title">
				<PageTitle :title="$t('mtTransfer.pageTitle')" />
			</view>
			<uni-forms ref="transferForm" :modelValue="transferFormData" :rules="transferFormRules">
				<view class="availableMoneyOut">
					{{ $t('mtTransfer.transferableAmount') }}
					<text class="value">${{ ibFund?.amount ?? '-' }}</text>
				</view>

				<uni-forms-item name="transfer_type">
				  <text class="uni-subtitle">{{ $t('form.transType.label') }}</text>
				  <uni-data-select
					  :placeholder="$t('form.pleaseSelect')"
					  :emptyTips="$t('form.transType.required')"
					  :localdata="transTypeOptions"
					  v-model="transferFormData.transfer_type"
					  @change="transTypeChange"
				  ></uni-data-select>
				</uni-forms-item>

				<uni-forms-item name="mt4_server" v-if="showTransferOut">
				  <text class="uni-subtitle">{{ $t('form.mtServer.label') }}</text>
				  <uni-data-select
					  :placeholder="$t('form.pleaseSelect')"
					  :emptyTips="$t('common.empty')"
					  :localdata="mtServerOptions"
					  v-model="transferFormData.mt4_server"
					  :clear="false"
				  ></uni-data-select>
				</uni-forms-item>

				<uni-forms-item name="mt4_login_in" v-if="showTransferOut">
				  <text class="uni-subtitle">{{ $t('form.mtAccount.labelIn') }}</text>
				  <uni-easyinput type="number" primaryColor="#29BBE4" v-model="transferFormData.mt4_login_in"></uni-easyinput>
				</uni-forms-item>

				<uni-forms-item name="mt4_login_name" v-if="showTransferOut" >
				  <text class="uni-subtitle">{{ $t('form.mtAccountName.label') }}</text>
				  <uni-easyinput type="text" :placeholder="$t('form.mtAccountName.placeholder')"  primaryColor="#29BBE4" v-model="transferFormData.mt4_login_name"></uni-easyinput>
				</uni-forms-item>

				<uni-forms-item name="mt4_login_in" v-if="showTransferOwn">
					<text class="uni-subtitle">{{ $t('form.mtAccount.label') }}</text>
					<uni-data-select
						:placeholder="$t('form.pleaseSelect')"
						:emptyTips="$t('common.empty')"
						:localdata="mtLoginOptions"
						v-model="transferFormData.mt4_login_in"
						@change="mtLoginInChange"
					></uni-data-select>
				</uni-forms-item>
				<uni-forms-item name="usd_amount">
					<text class="uni-subtitle">{{ $t('form.amount.label') }}</text>
					<uni-easyinput type="digit" primaryColor="#29BBE4" v-model="transferFormData.usd_amount" @input="handleAmountInput"></uni-easyinput>
					<view :class="['minAmount', amountAvailable ? '' : 'unavailable']">{{ unavailableAmountTip }}</view>
				</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">{{ selectedMtLoginOut.mt4_login }}{{ $t('withdrawal.accountWithdraw') }}</view>
							<view class="value">${{ this.transferFormData?.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="transferFormData.safe_pass"></uni-easyinput>
							</uni-forms-item>
							<button class="primaryButton" :disabled="submitBtnLoading" @click="handleSaveIBTransfer">
								<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>
			<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>
</template>

<script>
import { getMTAccounts, getIbFundSum } from '@/services/home/home.ts';
import { getGoldRange } from '@/services/capital/deposit.ts';
import { saveIBTransfer, getIfOTParams} from '@/services/capital/transfer.ts';
import { getMtServers, getDictByCode, getSys } from '@/services/common.ts';
import { UserLanguage } from '@/utils/const';
import UniEasyinput from "../../../uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue";
export default {
	name: '',
  components: {UniEasyinput},
	data() {
		return {
			ibFund: {},
      showTransferOwn: false,
      showTransferOut: false,
      ioPowerMap: {},
      mtServerOptions: [],
			mtLoginOptions: [],
			mtLoginInOptions: [],
      transTypeOptions: [],
			mtlogins: {},
			selectedMtLoginIn: null,
			currencyOptions: [],
			goldRange: null,
			amountAvailable: true,
			unavailableAmountTip: '',
			nextBtnLoading: false,
			submitBtnLoading: false,
			transferFormData: { usd_amount: '' },
			transferFormRules: {
				transfer_type: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.transType.required')
						}
					]
				},
				mt4_server: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.mtServer.required')
						}
					]
				},
				mt4_login_in: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.mtAccount.required')
						}
					]
				},
				mt4_login_name: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.mtAccountName.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_transfer) {
											// 不通过返回 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('mtTransfer.maxAmount')} $${this.ibFund?.amount ?? 0}`;
										} else {
											// 通过返回 resolve
											this.amountAvailable = true;
											resolve();
										}
									}, 0);
								});
							}
						}
					]
				},
				safe_pass: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.CRMPassword.required')
						}
					]
				}
			}
		};
	},
	methods: {
		handleAmountInput() {
			this.amountAvailable = true;
			this.unavailableAmountTip = `${this.$t('mtTransfer.minAmount')} $${this.goldRange?.sys_min_transfer??0}`;
		},
		goldRangePlaceholderRender(min, max) {
			return `${this.$t('form.amount.placeholderBefore')}${min}-${max}${this.$t('form.amount.placeholderAfter')}`;
		},
		async getMtLoginData() {
			const res = await getMTAccounts({ 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
				}));
				res.data?.forEach((mtAccount) => {
					this.mtlogins[mtAccount.mt4_login] = mtAccount;
				});
				// if (res.data[0]) {
				// 	this.transferFormData.mt4_login_in = res.data[0].mt4_login;
				// 	this.selectedMtLoginIn = this.mtlogins[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.transferFormData.mt4_server = this.mtServerOptions[0].value;
      // }
    },
    async getIfOTParams() {
      const res = await getIfOTParams();
      if (res && res.code === 0) {
        this.ioPowerMap = res.data;
        if(this.ioPowerMap != null  && this.ioPowerMap.fund_transfer_own==0 && this.ioPowerMap.fund_transfer_out==0 ){
          this.transTypeOptions = [{text:this.$t('form.transType.0'),value:0}, {text:this.$t('form.transType.1'),value:1}]
        }else if (this.ioPowerMap != null  && this.ioPowerMap.fund_transfer_own==1 && this.ioPowerMap.fund_transfer_out==0 ){
          this.transTypeOptions = [{text:this.$t('form.transType.1'),value:1}]
        }else if (this.ioPowerMap != null  && this.ioPowerMap.fund_transfer_own!=1 && this.ioPowerMap.fund_transfer_out==1 ){
          this.transTypeOptions = [{text:this.$t('form.transType.0'),value:0}]
        }else {
          this.transTypeOptions = []
        }
      }
    },
		async getIbFundData() {
			const res = await getIbFundSum();
			if (res && res.code === 0) {
				this.ibFund = res.data;
			}
		},
		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] = Number(item.text);
				});
				this.goldRange = temp;
			}
		},
		showDetailDialog() {
			this.$refs.transferForm.validateField(['transfer_type', 'mt4_server', 'mt4_login_out', 'mt4_login_in', 'mt4_login_name', 'usd_amount']).then(() => {
				this.$refs.alertDialog.open();
			});
		},
		closeDetailDialog() {
			this.$refs.alertDialog.close();
		},
		async handleSaveIBTransfer() {
			this.$refs.transferForm.validate().then(async (fields) => {
				this.submitBtnLoading = true;
				const res = await saveIBTransfer({
					...fields,
					qcc_language: UserLanguage,
          mt4_server: this.transferFormData.mt4_server
				});
				this.closeDetailDialog();
				this.submitBtnLoading = false;
				if (res && res.code === 0) {
					uni.redirectTo({
						url: '/pages/capital/ibTransfer/success/index'
					});
				} else {
					this.$nextTick(() => {
						this.$cusModal.showModal({
							type: 'message',
							status: 'warning',
							contentText: res.msg ?? this.$t('common.error.sysError')
						});
					})
				}
			});
		},
    transTypeChange(val){
		this.transferFormData.mt4_server = undefined
		this.transferFormData.mt4_login_in = undefined
		this.transferFormData.mt4_login_name = undefined
      if(val == 0) {
        this.showTransferOut = false
        this.showTransferOwn = true
      }else if (val == 1){
        this.showTransferOut = true
        this.showTransferOwn = false
      }else {
        this.showTransferOut = false
        this.showTransferOwn = false
      }

    },
		mtLoginInChange(val) {
			this.selectedMtLoginIn = this.mtlogins[val];
      this.transferFormData.mt4_server = this.mtlogins[val].mt4_server;
		}
	},
	watch: {
		goldRange: {
			handler(newVal, oldVal) {
				this.unavailableAmountTip = `${this.$t('mtTransfer.minAmount')} $${newVal?.sys_min_transfer}`;
			}
		}
	},
	created() {
    this.getIfOTParams();
		this.getMtLoginData();
		this.getCurrency();
		this.getIbFundData();
		this.getGoldRangeData();
    this.getMtServerOptions();
	}
};
</script>

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