<template>
	<view>
		<NavBar />
		<view class="container">
			<view class="title">
				<PageTitle :title="$t('home.subsidy')" />
			</view>
      <view>
        <uni-forms ref="withdrawForm" :modelValue="withdrawFormData" :rules="withdrawFormRules">
          <uni-forms-item name="mt_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.mt_login"
                @change="mtLoginChange"
            ></uni-data-select>
          </uni-forms-item>
        </uni-forms>
		<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>
	</view>
</template>

<script>
import { getMTAccounts, getIfChargeCommission } from '@/services/home/home.ts';
import { applySubsidy } from '@/services/capital/deposit.ts';
export default {
	name: '',
	data() {
		return {
			mtLoginOptions: [],
			mtlogins: {},
			selectedMtLogin: null,
			submitBtnLoading: false,
			withdrawFormData: { mt_login: '' },
			withdrawFormRules: {
				mt_login: {
					rules: [
						{
							required: true,
							errorMessage: this.$t('form.mtAccount.required')
						}
					]
				}
			},
		};
	},
	methods: {
		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?.toString()
				}));
				res.data?.forEach((mtAccount) => {
					this.mtlogins[mtAccount.mt4_login] = mtAccount;
				});
			}
		},
		async handleSaveWithdraw() {
			this.$refs.withdrawForm.validate().then(async (fields) => {
				this.submitBtnLoading = true;
				const res = await applySubsidy({
					...fields,
					mt_server: this.selectedMtLogin?.mt4_server
				});
				this.submitBtnLoading = false;
				if (res && res.code === 0) {
					this.$nextTick(() => {
						this.$cusModal.showModal({
							type: 'message',
							status: 'success',
							contentText: this.$t('activity.dh')
						});
					})
				} 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];
		},
		back(){
		  uni.navigateBack();
		}
	},
	onLoad(params) {
		this.getMtLoginData();
	}
};
</script>

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