<template>
	<NavBar />
	<view class="container">
		<view class="title">
			<PageTitle :title="$t('home.changeTradePwd')" />
		</view>
		<uni-forms ref="changeTradePwdForm" :modelValue="changeTradePwdFormData" :rules="changeTradePwdFormRules">
			<view class="availableMoneyOut">
				{{ $t('form.mtAccount.label') }}
				<text class="value">{{ mt4_login ?? '-' }}</text>
			</view>
			<uni-forms-item name="mt4_password">
				<text class="uni-subtitle">{{ $t('form.password.label') }}</text>
				<uni-easyinput
					class="uni-mt-5"
					type="password"
					trim="all"
					primaryColor="#29BBE4"
					v-model="changeTradePwdFormData.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-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-item name="code">
							<text class="uni-subtitle">{{ $t('form.captcha.label') }}</text>
							<uni-easyinput type="password" trim="all" primaryColor="#29BBE4" v-model="changeTradePwdFormData.code"></uni-easyinput>
							<view class="resendCode" @click="sendCode">
								<image src="/static/reload.png" mode="aspectFit" :class="['resendIcon', sendCodeBtnLoading ? 'loading' : '']"></image>
								<text>{{ $t('form.verificationCode.invalid') }}</text>
							</view>
						</uni-forms-item>
						<button class="primaryButton" :disabled="submitBtnLoading" @click="saveTradePwd">
							<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>
</template>

<script>
import { getApplyLeverageList, updateLeverage, sendCodeMT, checkCodeMT, updateMTPassword } from '@/services/home/home.ts';
import { getExchangeRate, getGoldRange } from '@/services/capital/deposit.ts';
import { saveTransfer } from '@/services/capital/transfer.ts';
import { getBankList } from '@/services/user.ts';
import { getDictByCode } from '@/services/common.ts';
import { UserLanguage, patterns } from '@/utils/const';
import { useUserStore } from '@/stores/user';
export default {
	name: '',
	data() {
		return {
			mt4_login: undefined,
			mt4_server: undefined,
			mt4_leverage_old: undefined,
			nextBtnLoading: false,
			sendCodeBtnLoading: false,
			submitBtnLoading: false,
			sign: undefined,
			leverageOptions: [],
			changeTradePwdFormData: {},
			changeTradePwdFormRules: {
				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);
								});
							}
						}
					]
				},
				code: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.captcha.required')
						}
					]
				}
			},
			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: {
		passwordInputChange(e) {
			this.$nextTick(() => {
				this.changeTradePwdFormData.mt4_password = this.changeTradePwdFormData.mt4_password.replace(/[^a-zA-Z0-9!@#]/g, '')
				if (!this.validating) {
					this.validating = true;
				}
				this.validateStatuses.forEach((item, index) => {
					item.valid = patterns[`passwordPattern${index + 1}`].test(e);
				});
			})
		},
		async sendCode() {
			this.nextBtnLoading = true;
			this.closeDetailDialog()
			const userStore = useUserStore();
			this.sendCodeBtnLoading = true;
			const res = await sendCodeMT({
				email: userStore.userInfo.email,
				mt4_login: this.mt4_login,
				qcc_language: UserLanguage
			});
			this.sendCodeBtnLoading = false;
			this.nextBtnLoading = false;
			let success = false;
			if (res && res.code === 0) {
				this.$nextTick(() => {					
					this.$cusModal.showModal({
						type: 'message',
						status: 'success',
						contentText: this.$t('form.verificationCode.sendSuccess'),
						onClose: () => {
							this.$refs.alertDialog.open();
						}
					});
				})
				success = true;
			} else {
				this.$nextTick(() => {					
					this.$cusModal.showModal({
						type: 'message',
						status: 'warning',
						contentText: res.msg ?? this.$t('common.error.sysError')
					});
				})
			}
			return success;
		},
		async showDetailDialog() {
			this.$refs.changeTradePwdForm.validateField(['mt4_password']).then(async () => {
				const sendSuccess = await this.sendCode();
			});
		},
		closeDetailDialog() {
			this.$refs.alertDialog.close();
		},
		async saveTradePwd() {
			this.$refs.changeTradePwdForm.validate().then(async (fields) => {
				this.submitBtnLoading = true;
				const userStore = useUserStore();
				const checkRes = await checkCodeMT({
					email: userStore.userInfo.email,
					code: fields.code,
					qcc_language: UserLanguage
				});
				if (checkRes && checkRes.code === 0) {
					this.sign = checkRes.data;
				} else {
					this.closeDetailDialog()
					this.$nextTick(() => {						
						this.$cusModal.showModal({
							type: 'message',
							status: 'warning',
							contentText: checkRes.msg ?? this.$t('common.error.sysError')
						});
					})
					this.submitBtnLoading = false;
					return;
				}
				const res = await updateMTPassword({
					...fields,
					email: userStore.userInfo.email,
					mt4_login: this.mt4_login,
					mt4_server: this.mt4_server,
					qcc_language: UserLanguage,
					sign: this.sign
				});
				this.closeDetailDialog()
				if (res && res.code === 0) {
					this.$nextTick(() => {
						this.$cusModal.showModal({
							type: 'message',
							status: 'success',
							contentText: this.$t('common.success.action'),
							onClose() {
								uni.redirectTo({
									url: '/pages/home/changeTradePwd/success/index'
								});
							}
						});
					})
				} else {
					this.$nextTick(() => {						
						this.$cusModal.showModal({
							type: 'message',
							status: 'warning',
							contentText: res.msg ?? this.$t('common.error.sysError')
						});
					})
					this.submitBtnLoading = false;
					return;
				}
			});
		}
	},
	created() {},
	onLoad(params) {
		this.mt4_login = params.mt4_login;
		this.mt4_server = params.mt4_server;
	}
};
</script>

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