<template>
	<NavBar />
	<view class="container">
		<view class="pageTitle">
			<PageTitle :title="$t('openAccount.pageTitle2')" />
		</view>
		<view class="errorAlert" v-if="applyDisabled">
			{{ $t('openAccount.disabledApplication') }}
		</view>
		<view class="MTTypeDataWrapper">
			<view class="MTTypeData">
				<view v-for="item in MTTypes" :key="item.id" class="MTTypeDataItem">
					<view class="title">
						<view class="label">{{ item.name }}</view>
						<view class="tag">{{ item.ifCent === 'NO' ? $t('common.unit.dollar') : $t('common.unit.cent') }}</view>
					</view>
					<view class="descs">
						<view class="descItem" v-if="item.server_type === 'live'">
							<view class="descLabel">{{ $t('openAccount.minDepositAmount') }}</view>
							<view class="descValue">{{ item.in_min ?? '0' }}</view>
						</view>
						<!-- 	<view class="descItem">
							<view class="descLabel">手续费</view>
							<view class="descValue">-</view>
						</view>
						<view class="descItem">
							<view class="descLabel">强平比例</view>
							<view class="descValue">-</view>
						</view> -->
					</view>

					<button class="primaryButton registerBtn" :disabled="applyDisabled" @click="showDetailDialog(item)">{{ $t('openAccount.startRegister') }}</button>
				</view>
			</view>
			<view v-if="!MTTypes.length" style="display: flex; justify-content: center; align-items: center; width: 100%">
				<Spin v-show="MTTypesLodaing" />
				<image v-show="!MTTypesLodaing" src="/static/empty.png" mode="aspectFit" style="width: 72px; height: 100px; margin-top: 64px"></image>
			</view>
		</view>
		<uni-popup ref="alertDialog" :isMaskClick="false">
			<view class="detailModal">
				<uni-icons type="closeempty" size="17" class="closeIcon" @click="closeDetailDialog"></uni-icons>
				<view class="detailContent">
					<uni-forms ref="completeForm" :modelValue="completeFormData" :rules="completeFormRules">
						<uni-forms-item name="mt4_leverage">
							<text class="uni-subtitle">{{ $t('form.leverage.label') }}</text>
							<uni-data-select
								:localdata="leverageOptions"
								v-model="completeFormData.mt4_leverage"
								:placeholder="$t('form.pleaseSelect')"
								:emptyTips="$t('common.empty')"
							></uni-data-select>
						</uni-forms-item>
						<uni-forms-item name="mt4_init_amount" v-if="currentMTType.server_type === 'test'">
							<text class="uni-subtitle">{{ $t('form.applyMtInitAmount.label') }}</text>
							<uni-data-select
								:localdata="initAmountOptions"
								v-model="completeFormData.mt4_init_amount"
								:placeholder="$t('form.pleaseSelect')"
								:emptyTips="$t('common.empty')"
							></uni-data-select>
						</uni-forms-item>
						<uni-forms-item name="mt4_password">
							<text class="uni-subtitle">{{ $t('form.password.label') }}</text>
							<uni-easyinput type="password" trim="all" primaryColor="#29BBE4" v-model="completeFormData.mt4_password" @input="passwordInputChange"></uni-easyinput>
							<view v-if="validating" class="validateStatusWrapper">
								<view v-for="(status, index) in validateStatuses" :key="index" class="validateStatus">
									<view class="verificationRes">
										<image :src="status.valid ? '/static/right.png' : '/static/error.png'" :class="status.valid ? 'right' : 'error'" mode="aspectFit"></image>
									</view>
									<view :class="status.valid ? 'rightText' : 'errorText'">{{ status.text }}</view>
								</view>
							</view>
						</uni-forms-item>
					</uni-forms>
					<button class="primaryButton" :disabled="submitBtnLoading" @click="handleOpenAccount">
						<image v-show="submitBtnLoading" src="/static/loadingCircle.svg" mode="aspectFit" style="width: 16px; height: 16px"></image>
						{{ $t('form.submit') }}
					</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import { getMTTypeList, getMTDemoTypeList, getApplyMTAwaitAuditNum, saveApplyMT } from '@/services/home/home.ts';
import { UserLanguage, patterns } from '@/utils/const';
export default {
	name: '',
	data() {
		return {
			MTTypes: [],
			MTTypesLodaing: false,
			mt_versions: undefined,
			server_type: undefined,
			applyDisabled: false,
			submitBtnLoading: false,
			leverageOptions: [],
			initAmountOptions: [],
			completeFormData: {},
			completeFormRules: {
				mt4_leverage: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.leverage.required')
						}
					]
				},
				mt4_init_amount: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.applyMtInitAmount.required')
						}
					]
				},
				mt4_password: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.password.required')
						},
						{
							validateFunction: (rule, value, data, callback) => {
								// 异步需要返回 Promise 对象
								return new Promise((resolve, reject) => {
									setTimeout(() => {
										if (this.validateStatuses.every((item) => item.valid)) {
											// 通过返回 resolve
											resolve();
										} else {
											// 不通过返回 reject(new Error('错误信息'))
											reject(new Error(this.$t('form.password.invalid')));
										}
									}, 0);
								});
							}
						}
					]
				}
			},
			currentMTType: null,
			validating: false,
			validateStatuses: [
				{ valid: false, text: this.$t('form.password.pattern1') },
				{ valid: false, text: this.$t('form.password.pattern2') },
				{ valid: false, text: this.$t('form.password.pattern3') },
				{ valid: false, text: this.$t('form.password.pattern4') }
			]
		};
	},
	methods: {
		showDetailDialog(MTType) {
			this.currentMTType = MTType;
			this.leverageOptions = MTType.mt4_leverage.split(',').map((item) => ({
				text: item,
				value: item
			}));
			this.initAmountOptions = MTType.init_amount.split(',').map((item) => ({
				text: item,
				value: item
			}));
			this.completeFormData.mt4_leverage = this.leverageOptions[0].value;
			this.completeFormData.mt4_init_amount = MTType.init_amount.split(',')[0];
			this.$refs.alertDialog.open();
		},
		closeDetailDialog() {
			this.$refs.alertDialog.close();
			this.completeFormData = {};
			this.validating = false;
		},
		async getMTTypeData() {
			this.MTTypesLodaing = true;
			const res = await getMTTypeList({
				qcc_language: UserLanguage,
				server_type: 'live'
			});
			this.MTTypesLodaing = false;
			if (res && res.code === 0) {
				this.MTTypes = res.data.filter((item) => item.mt_versions === this.mt_versions && item.server_type === this.server_type);
			}
		},
		async getMTDemoTypeData() {
			this.MTTypesLodaing = true;
			const res = await getMTDemoTypeList({
				qcc_language: UserLanguage
			});
			this.MTTypesLodaing = false;
			if (res && res.code === 0) {
				this.MTTypes = res.data;
			}
		},
		async getAwaitAuditNum() {
			const res = await getApplyMTAwaitAuditNum();
			if (res && res.code === 0) {
				if (res.data.await_audit_num !== 0) {
					this.applyDisabled = true;
				} else {
					this.applyDisabled = false;
				}
			}
		},
		passwordInputChange(e) {
			if (!this.validating) {
				this.validating = true;
			}
			this.validateStatuses.forEach((item, index) => {
				item.valid = patterns[`passwordPattern${index + 1}`].test(e);
			});
		},
		async handleOpenAccount() {
			this.$refs.completeForm.validate().then(async (fields) => {
				this.submitBtnLoading = true;
				const res = await saveApplyMT({
					...fields,
					mt4_server: this.currentMTType.mt4_server,
					mt4_type_id: this.currentMTType.id
				});
				this.closeDetailDialog();
				this.submitBtnLoading = false;
				if (res && res.code === 0) {
					if (res.data.isAudit == 1) {
						this.$cusModal.showModal({
							type: 'message',
							status: 'success',
							contentText: this.$t('openAccount.waitAudit'),
							onClose: async () => {
								uni.redirectTo({
									url: '/pages/home/index'
								});
							}
						});
					} else {
						this.$cusModal.showModal({
							type: 'message',
							status: 'success',
							contentText: res.msg ?? this.$t('common.success.submit'),
							onClose: async () => {
								this.$cusModal.closeModal();
								uni.redirectTo({
									url: '/pages/home/index'
								});
							}
						});
					}
				} else {
					this.$cusModal.showModal({
						type: 'message',
						status: 'warning',
						contentText: res.msg ?? this.$t('common.error.sysError')
					});
				}
			});
		}
	},
	created() {
		this.getAwaitAuditNum();
	},
	onLoad(params) {
		this.mt_versions = params.mt_versions;
		this.server_type = params.server_type;
		if (this.server_type === 'live') {
			this.getMTTypeData();
		} else if (this.server_type === 'test') {
			this.getMTDemoTypeData();
		}
	}
};
</script>

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