<template>
    <cwg-page-wrapper class="create-page " :isHeaderFixed="true">

        <view class="container">
            <view
                class="app-page-head card-header d-flex gap-3 flex-wrap align-items-center justify-content-between border-0">
                <view class="app-page-head mb-0">
                    <h1 class="app-page-title" v-t="currentAccount?.name"></h1>
                </view>
            </view>
            <view class="row">
                <view class="col-lg-8">
                    <view class="card">
                        <view class="border-0 card-header">
                            <uni-forms ref="formRef" :model="formData" :rules="rules" label-width="200"
                                label-position="top" class="base-info-form" validate-trigger="submit">
                                <view class="row">
                                    <view class="col-lg-12">
                                        <h5 class="mb-3" v-t="'Custom.PaymentHistory.AccountType'"></h5>
                                        <uni-forms-item name="platform">
                                            <cwg-combox :clearable="false" v-model:value="cativeIndex" :options="tabs"
                                                :placeholder="t('placeholder.choose')" />
                                        </uni-forms-item>
                                    </view>
                                    <view class="col-lg-6">
                                        <h5 class="mb-3" v-t="'Custom.NewAccount.Platform'"></h5>
                                        <uni-forms-item name="platform">
                                            <cwg-combox :clearable="false" v-model:value="formData.platform"
                                                :options="platformColumns" :placeholder="t('placeholder.choose')" />

                                        </uni-forms-item>
                                    </view>
                                    <view class="col-lg-6">
                                        <h5 class="mb-3" v-t="'Custom.NewAccount.Currency'"></h5>
                                        <uni-forms-item name="currency">
                                            <cwg-combox :clearable="false" v-model:value="formData.currency"
                                                :options="currencyColumns" :placeholder="t('placeholder.choose')" />
                                        </uni-forms-item>
                                    </view>

                                    <view class="col-lg-6">
                                        <h5 class="mb-3" v-t="'Custom.NewAccount.Lever'"></h5>
                                        <uni-forms-item name="leverage">
                                            <cwg-combox :clearable="false" v-model:value="formData.leverage"
                                                :options="leverageColumns" :placeholder="t('placeholder.choose')" :disabled="formData.platform == 'MT4'"/>
                                        </uni-forms-item>
                                    </view>
                                    <view class="col-lg-6">
                                        <h5 class="mb-3" v-t="'Custom.NewAccount.Password'"></h5>
                                        <uni-forms-item name="password">
                                            <uni-easyinput :clearable="false" v-model="formData.password"
                                                :placeholder="t('Custom.NewAccount.Password')" />
                                        </uni-forms-item>
                                    </view>
                                    <view class="col-lg-6" v-if="dome">
                                        <h5 class="mb-3" v-t="'Custom.NewAccount.Balance'"></h5>
                                        <uni-forms-item name="balance">
                                            <uni-easyinput type="digit" :clearable="false" v-model="formData.balance"
                                                :placeholder="t('Custom.NewAccount.BalancePlaceholder')" />
                                        </uni-forms-item>
                                    </view>
                                    <view class="px-4">
                                        <view class="notice-list">
                                            <view v-for="(item, index) in noticeItems" :key="index"
                                                :class="['notice-item', item.valid ? 'isOK' : '']">
                                                {{ item.label }}
                                            </view>
                                        </view>
                                    </view>
                                    <!-- <view class="col-lg-12 mb-3">
                                        <view class="form-check mb-3">
                                            <input class="form-check-input" type="checkbox" value="" id="invalidCheck2"
                                                required="">
                                            <label class="form-check-label" for="invalidCheck2">* I have read all the
                                                instructions and agreed to the terms and conditions of the Standard
                                                Account</label>
                                        </view>
                                    </view> -->
                                    <button @click="newAccount" class="btn btn-danger waves-effect waves-light"><i
                                            class="fi fi-rs-check"></i>
                                        {{ t('Btn.Application') }}</button>
                                </view>
                            </uni-forms>
                        </view>

                    </view>

                </view>
                <view class="col-lg-4">
                    <view class="card overflow-hidden card-action action-border-primary">
                        <view class="card-header bg-light border-0 p-4 accordion-b utton text-white bg">
                            <!-- <view class="ribbon">Premium</view> -->
                            <h4 class="text-white" v-t="currentAccount?.name"></h4>
                            <p class="mb-4" v-t="currentAccount?.description"></p>
                            <view class="display-6 fw-bold  text-white lh-1 price-monthly">{{ currentAccount?.minDeposit
                                || '--' }} <text class="h6 text-white">{{ t('vu.item9') }}</text> </view>
                        </view>
                        <view class="card-body p-4">
                            <view class="fs-5 list-inline text-dark">
                                <view class="d-flex gap-2 align-items-center py-1"> <i
                                        class="fa-regular fa-circle-check text-success"></i> {{ t('vu.item10') }}: {{
                                            currentAccount?.minSpread || '--' }}
                                </view>
                                <view class="d-flex gap-2 align-items-center py-1"> <i
                                        class="fa-regular fa-circle-check text-success"></i> {{ t('vu.item11') }}: {{
                                            currentAccount?.maxLeverage || '--' }}
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <!-- 提交后的弹出框 -->
        <uni-popup :show="dialogCheck" mode="center" round="16" @close="closeDia">
            <view class="dia-content" v-if="dialogVisible">
                <view class="icon">
                    <text class="iconfont icon-success"></text>
                </view>
                <view class="des1">{{ t('ApplicationDialog.Des1') }}</view>
                <view class="des2">{{ t('ApplicationDialog.Des12') }}</view>
                <view class="dialog-footer">
                    <uv-button type="primary" @click="closeDia">
                        {{ t('Btn.Confirm') }}
                    </uv-button>
                    <uv-button @click="closeDia">
                        {{ t('Btn.Cancel') }}
                    </uv-button>
                </view>
            </view>

            <view class="dia-content" v-if="!dialogVisible">
                <view class="icon">
                    <text class="iconfont icon-warning"></text>
                </view>
                <view class="des1">{{ RES }}</view>
                <view class="dialog-footer">
                    <uv-button type="primary" @click="closeDia">
                        {{ t('Btn.Confirm') }}
                    </uv-button>
                    <uv-button @click="closeDia">
                        {{ t('Btn.Cancel') }}
                    </uv-button>
                </view>
            </view>
        </uni-popup>

        <cwg-error-popup v-model:visible="dialogError" :responseMessage="RES" />
        <cwg-success-popup v-model:visible="dialogSuccess" @confirm="closeDia" type="create" />
        <!-- 账户开立上限提示弹框 -->
        <cwg-account-limit-popup v-model:visible="dialogAccountLimit" @confirm="closeAccountLimitDialog" />
    </cwg-page-wrapper>

</template>

<script setup>
import { ref, reactive, computed, onMounted, watch, nextTick } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { customApi } from "@/service/custom";
import useUserStore from "@/stores/use-user-store";
import useRouter from "@/hooks/useRouter";
import { useI18n } from "vue-i18n";
const router = useRouter();
const { t, locale } = useI18n();
const userStore = useUserStore();
// 定义账户数据类型
const standardAccounts = ref([
    {
        id: 7,
        type: 'StandardAccount',
        name: 'AccountType.StandardAccount',
        showCondition: () => showLogin.value && showLogin.value.indexOf('7') == -1,
        description: 'Custom.NewAccount.DesLogin5',
        minDeposit: '$200',
        minSpread: '0.01',
        maxLeverage: '1:1000',
        icon: '/static/images/info/bank-information-1.webp',
    },
    {
        id: 2,
        type: 'SeniorAccount',
        name: 'AccountType.SeniorAccount',
        showCondition: () => showLogin.value && showLogin.value.indexOf('2') == -1,
        description: 'Custom.NewAccount.DesLogin3',
        minDeposit: '$200',
        minSpread: '0.01',
        maxLeverage: '1:1000',
        icon: '/static/images/info/bank-information-2.webp',
    },
    {
        id: 8,
        type: 'CentAccount',
        name: 'AccountType.CentAccount',
        showCondition: () => showLogin.value && showLogin.value.indexOf('8') == -1 && isTimeShow.value,
        description: 'Custom.NewAccount.DesLogin8',
        minDeposit: '$200',
        minSpread: '0.01',
        maxLeverage: '1:500',
        icon: '/static/images/info/bank-information-3.webp',
    }
])
const cativeIndex = ref('real')
const tabs = computed(() => ([
    { value: 'real', text: t('vu.item1') },
    { value: 'demo', text: t('vu.item2') }
]))

const dialogError = ref(false)
const dialogSuccess = ref(false)
const currentAccount = computed(() => {
    // 从账户列表中查找匹配的账户
    const matched = standardAccounts.value.find(account => account.id == isOpenAccount.value);
    // 如果未找到，返回一个默认空对象或 null，模板中需做判空处理
    return matched || null;
});

// 数据定义
const pictLoading = ref(false);
const flag = ref(false);
const RES = ref('');
const dialogCheck = ref(false);
const dialogVisible = ref(false);
const showData = ref(null);
const isOpenAccount = ref(0);
const checked = ref('');
const optionsLev = ref([]);
const optionsCur = ref([]);
const dome = ref(null);
const showLogin = ref([]);
const showPage = ref(false);
const isTimeShow = ref(false);
const dialogAccountLimit = ref(false);
const limitPlatform = ref('');
const hidden = ref(true);
const ho = ref('');

// 表单引用
const formRef = ref(null);

// 表单数据
const formData = reactive({
    password: '',
    currency: '',
    leverage: '',
    platform: '',
    balance: null,
});
const resetForm = async () => {
    await nextTick();
    formRef.value?.clearValidate();
    formData.password = ""
    formData.currency = ""
    formData.leverage = ""
    formData.platform = ""
    formData.balance = ""
    optionsLev.value = []
    optionsCur.value = []
    showData.value = null
    // amountErrorMessage.value = ""
    // submitting.value = false
    flag.value = false
    // loginValue.value = ""
    dialogCheck.value = false
    dialogVisible.value = false
}


// 计算属性
const rule1 = computed(() => {
    if (!formData.password) return false;
    return /^.{8,15}$/.test(formData.password);
});

const rule2 = computed(() => {
    return /^(?=.*?[a-z])(?=.*?[A-Z]).*$/.test(formData.password);
});

const rule3 = computed(() => {
    return /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?!.*([~!@&%$^\\(\\)#_]).*\\1.*\\1)[A-Za-z0-9~!@&%$^\\(\\)#_]{8,16}$/.test(
        formData.password
    );
});
const rule4 = computed(() => {
    return /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[~!@&%$^*./\\(\\)\\+\\=#_-])[A-Za-z0-9~!@&%$^*./\\(\\)\\+\\=#_-]{8,16}$/.test(
        formData.password
    );
});
const noticeItems = computed(() => [
    { label: t('signup.form.rules.1st'), valid: rule1.value },
    { label: t('signup.form.rules.2nd'), valid: rule2.value },
    { label: t('signup.form.rules.4rd'), valid: rule4.value }
])
const rules = computed(() => ({
    platform: {
        rules: [
            {
                required: true,
                errorMessage: t('vaildate.select.empty'),
                trigger: 'change',
            },
        ],
    },
    currency: {
        rules: [
            {
                required: true,
                errorMessage: t('vaildate.select.empty'),
                trigger: 'change',
            },
        ],
    },
    leverage: {
        rules: [
            {
                required: true,
                errorMessage: t('vaildate.select.empty'),
                trigger: 'change',
            },
        ],
    },

    password: {
        rules: [
            {
                required: true,
                errorMessage: t('vaildate.password.format'),
                trigger: 'blur',
            },
            {
                validateFunction: (rule, value, data, callback) => {
                    if (/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[~!@&%$^*./\\(\\)\\+\\=#_-])[A-Za-z0-9~!@&%$^*./\\(\\)\\+\\=#_-]{8,16}$/.test(value)) {
                        return true;
                    } else {
                        callback(t('vaildate.password.format')); return false;
                    }
                },
                trigger: 'blur',
            },
        ],
    },
    balance: {
        rules: [
            {
                required: true,
                errorMessage: t('vaildate.amount.format'),
            },
            {
                validateFunction: (rule, value, data, callback) => {
                    if (value === null || value === undefined || value === '') {
                        return true;
                    }
                    const numValue = Number(value);
                    if (isNaN(numValue)) {
                        callback(t('vaildate.amount.format'));
                        return false;
                    }
                    if (numValue < 0 || numValue > 100000) {
                        callback(t('vaildate.amount.amount') + '0-100000');
                        return false;
                    }
                }
            },
        ],
    },

}));

// 平台选项
const platformColumns = computed(() => {
    const columns = [];
    if (showData.value && showData.value['mt4s'] && showData.value['mt4s'].length) {
        columns.push({ text: 'MT4', value: 'MT4' });
    }
    if (showData.value && showData.value['mt5s'] && showData.value['mt5s'].length) {
        columns.push({ text: 'MT5', value: 'MT5' });
    }
    return columns;
});

// 货币选项
const currencyColumns = computed(() => {
    if (optionsCur.value.length) {
        return optionsCur.value.map(item => ({ text: item, value: item }));
    }
    return [];
});

// 杠杆选项
const leverageColumns = computed(() => {
    if (optionsLev.value.length) {
        return optionsLev.value.map(item => ({ text: String(item), value: item }));
    }
    return [];
});

// 方法
const closeDia = () => {
    resetForm()
};

const closeAccountLimitDialog = () => {
    dialogAccountLimit.value = false;
    limitPlatform.value = '';
};

const showAccountLimitDialog = (platform) => {
    limitPlatform.value = platform;
    dialogAccountLimit.value = true;
};

// 获取必要数据
const getMustData = async (type, isDome) => {
    console.log(type, isDome, locale)
    const api = isDome ? customApi.AccountApplyDataDome : customApi.AccountApplyData;
    // console.log(api, 121212);

    const res = await api({
        type: type
    });
    // console.log(res, 121212);
    if (res.code === 200) {
        showData.value = res.data;
    } else {
        uni.showToast({
            title: res.msg,
            icon: 'none'
        });
    }
};

// 获取显示权限
const getExcludeShowLogin = async () => {
    pictLoading.value = true;
    const res = await customApi.excludeShowLogin({});
    if (res.code === 200) {
        showLogin.value = res.data?.excludeShowLoginTypes || [];
        showPage.value = true;
        pictLoading.value = false;
    } else {
        uni.showToast({
            title: res.msg,
            icon: 'none'
        });
        pictLoading.value = false;
    }
};

// 提交开户
const newAccount = async () => {


    try {
        if (formRef.value) {
            const valid = await formRef.value.validate()
            if (flag.value) return;
            flag.value = true;
            const api = dome.value ? customApi.AccountApplyAddDome : customApi.AccountApplyAdd;
            const res = await api({
                type: Number(isOpenAccount.value),
                ...formData
            });

            if (res.code === 200) {
                if (dome.value) {
                    uni.showToast({
                        title: t('Msg.Success'),
                        icon: 'success'
                    });
                }
                router.push('/pages/customer/index')
                isOpenAccount.value = 0;
                dialogSuccess.value = true;
                if (formRef.value) {
                    formRef.value.resetFields();
                }
                flag.value = false;
            } else if (res.code === 407) {
                showAccountLimitDialog(formData.platform);
                flag.value = false;
            } else {
                RES.value = res.msg;
                dialogError.value = true;
                flag.value = false;
                resetForm()
            }
        }
    } catch (error) {
        console.log(error)
        flag.value = false;
        if (error instanceof Array) {
            // showToast(error[0].errorMessage);
            return
        } else {
            console.log(error)
            dialogError.value = true;
            RES.value = error.msg;
            console.log(dialogError.value);
            resetForm()
        }
    }
};


// 选择平台
const checkPlatform = (pla) => {
    if (pla === 'mt5s') {
        hidden.value = false;
    } else {
        hidden.value = true;
    }
    optionsLev.value = [];
    optionsCur.value = [];
    const Cur = [];
    showData.value[pla].forEach((item) => {
        Cur.push(item.currency);
    });
    Cur.forEach((item) => {
        if (!optionsCur.value.includes(item)) {
            optionsCur.value.push(item);
        }
    });
};
watch(() => formData.platform, (newVal) => {
    if (newVal) {
        optionsLev.value = [];
        optionsCur.value = [];
        formData.currency = ''
        formData.leverage = ''
        formData.balance = ''
        formData.password = ''

        checkPlatform(newVal === 'MT4' ? 'mt4s' : 'mt5s');
    }
});
watch(() => formData.currency, (newVal) => {
    if (newVal && formData.platform) {
        checkCurrency(formData.platform, newVal);
    }
});

// 选择货币
const checkCurrency = (pla, cur) => {
    formData.leverage = '';
    optionsLev.value = [];
    const platform = pla === 'MT4' ? 'mt4s' : 'mt5s';
    const list = [];
    showData.value[platform].forEach((item) => {
        if (item.currency === cur) {
            list.push(item.leverage);
        }
    });
    formData.leverage = list.reduce((a, b) => Math.max(a, b));
    optionsLev.value = list;
};

// 时间判断
const isAfterJuly28 = () => {
    // 实现日期判断逻辑
    return false;
};

const isTimeShowType8 = () => {
    const endTime1 = '2024/9/25 00:00:00';
    const timezone = 2;
    const offset_GMT = new Date().getTimezoneOffset();
    const nowDate = new Date().getTime();
    const now = new Date(nowDate + offset_GMT * 60 * 1000 + timezone * 60 * 60 * 1000).getTime();
    const end = new Date(endTime1).getTime();
    if (now > end) {
        isTimeShow.value = true;
    }
};

// 余额变化验证
const handleBalanceChange = () => {
    if (formRef.value) {
        formRef.value.validateField('balance');
    }
};

// 打开链接
const openLink = (path) => {
    uni.navigateTo({
        url: `/pages/common/webview?url=https://www.${ho.value}.com/${path}`
    });
};

// 打开PDF
const openPdf = (path) => {
    uni.navigateTo({
        url: `/pages/common/webview?url=/pdf/${path}`
    });
};

// 监听balance变化
watch(() => formData.balance, (newVal, oldVal) => {
    if (newVal !== oldVal && newVal !== null && newVal !== undefined) {
        // nextTick(() => {
        //     if (formRef.value) {
        //         formRef.value.validateField('balance');
        //     }
        // });
    }
});
watch(() => cativeIndex.value, (newVal) => {
    dome.value = newVal == 'demo'
    console.log(newVal, 1111)
    getMustData(isOpenAccount.value, dome.value);
    resetForm()
});

// 生命周期
onLoad((e) => {
    dome.value = e.server == 'demo'
    cativeIndex.value = e.server
    isOpenAccount.value = e.id
    const host = window?.location?.host || '';
    ho.value = host.split('.')[1] || '';

    getExcludeShowLogin();
    getMustData(isOpenAccount.value, dome.value);
    isTimeShowType8();
});

onMounted(() => {
    // 挂载后的操作
});
</script>

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

.bg {
    background-image: url('/static/images/vu/account-bg.png');
    background-size: cover;
    background-position: center bottom;
}

.tit {
    text-align: center;
    font-size: px2rpx(30);
    font-weight: bold;
    color: var(--color-slate-900);
    margin: px2rpx(24) 0;
}

.des {
    color: var(--color-slate-900);
    font-size: px2rpx(14);
    line-height: 1.5;
    margin-bottom: px2rpx(24);
    text-align: center;
}

.box {
    margin-top: px2rpx(20);
}

.box-text {
    margin: px2rpx(20) 0;

    .text {

        font-size: px2rpx(14);
        line-height: px2rpx(24);
        text-align: center;
    }
}

.b-card {
    min-height: px2rpx(683);
    margin-bottom: px2rpx(20);
    position: relative;
    overflow: hidden;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    flex-direction: column;
    justify-content: center;

    .header {
        width: 100%;
        text-align: center;
    }

    .descending {
        margin: 0 auto;
        margin-top: px2rpx(32);
        min-height: px2rpx(160);

        .feature {
            display: flex;
            align-items: flex-start;
            justify-content: flex-start;
            margin-bottom: px2rpx(16);
        }

        .icon-success {
            display: flex;
            align-items: center;
            justify-content: center;
            width: px2rpx(24);
            height: px2rpx(24);
            margin-right: px2rpx(12);
            background-color: color-mix(in oklab, var(--bs-success) 10%, transparent);
        }
    }

    .btn-bottom {
        width: 100%;
        display: flex;
        justify-content: center;
        color: var(--color-white);
        margin-top: px2rpx(32);
        gap: px2rpx(16);

        .btn-open {
            background-color: #cf1322;
            padding: px2rpx(12) px2rpx(20);
        }

        .btn-try {
            background-color: var(--color-slate-150);
            color: var(--color-navy-800);
            padding: px2rpx(12) px2rpx(20);
        }
    }

}

:deep(.uni-row1) {
    .uni-col {
        padding: 0 10px !important;
    }

    .uni-forms-item {
        min-height: px2rpx(79);
        margin-bottom: px2rpx(10);
    }

}

.btn {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: px2rpx(12) 0;
    background-color: var(--color-error);
    color: white;
    border: none;
    font-size: px2rpx(16);
    cursor: pointer;
    margin: px2rpx(24) 0;
}

.notice-list {
    // margin: px2rpx(10) 0;
    padding: 0 px2rpx(12) px2rpx(12) 0;

    .notice-item {
        font-size: px2rpx(14);
        line-height: px2rpx(24);
    }

    .isOK {
        color: var(--bs-success);
    }
}

.email-code {
    display: flex;
    align-items: flex-end;

    .email-code-item {
        flex: 1;
    }

    .btn-code {
        margin-bottom: px2rpx(18);
        width: auto;
        padding: px2rpx(10) px2rpx(16);
    }

}

.card-bottom {
    max-width: px2rpx(566);
    margin-top: px2rpx(20);

    .tabs-class {
        margin: 0 px2rpx(10) px2rpx(20) px2rpx(10);
    }
}

.create-card {
    display: flex;
    gap: px2rpx(30);
    justify-content: space-between;
}

@media (max-width: 992px) {
    .card-bottom {
        width: 100%;
        margin-top: px2rpx(20);
    }

    .create-card {
        display: flex;
        gap: px2rpx(30);
        flex-wrap: wrap;
    }
}

.card-content {
    margin-top: px2rpx(30);
    padding: px2rpx(16);
    width: px2rpx(300);


    .account-name {
        display: block;
        font-size: px2rpx(18);
        font-weight: 600;
        color: var(--bs-emphasis-color);
        padding-bottom: px2rpx(16);
        padding-left: px2rpx(20);
        border-left: 1px solid #f0f2f5;
    }

    .info-row {
        padding-left: px2rpx(20);
        padding-bottom: px2rpx(12);
        border-left: 1px solid #f0f2f5;

        .info-label {
            font-size: px2rpx(15);
            line-height: px2rpx(30);
            color: #7f8c8d;
        }

        .info-value {
            font-size: px2rpx(14);
            font-weight: 500;
            color: var(--bs-emphasis-color);
        }

        .link-item {
            line-height: px2rpx(20);
            font-size: px2rpx(12);
            letter-spacing: px2rpx(0.5);
            color: #cf1322;
            text-decoration: underline;
            cursor: pointer;

            &:active {
                opacity: 0.7;
            }
        }
    }

    .link-wrapper {
        display: flex;
        align-items: center;
        justify-content: flex-end;
        margin-top: px2rpx(8);
        padding-top: px2rpx(8);
        border-top: 1rpx solid #f0f2f5;

        .link-text {
            font-size: px2rpx(14);
            color: #007aff;
            margin-right: px2rpx(4);
        }

        .link-icon {
            font-size: px2rpx(14);
            color: #007aff;
        }
    }
}
</style>