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

            <view class="card-bottom user-form crm-form">
                <view class="tabs-class">
                    <cwg-tabs v-model:cativeIndex="cativeIndex" :tabs="tabs" />

                </view>
                <uni-forms ref="baseForm" :model="formData" labelWidth="200" label-position="top" :rules="rules"
                    class="base-info-form">
                    <uni-row class="demo-uni-row uni-row1 uni-row2">
                        <!-- MT4/MT5 -->
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('Custom.NewAccount.Platform')">
                                <cwg-combox :clearable="false" v-model:value="formData.platform"
                                    :options="platformColumns" :placeholder="t('placeholder.choose')" />
                            </uni-forms-item>
                        </uni-col>
                        <!-- 货币类型 -->
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('Custom.NewAccount.Currency')">
                                <cwg-combox :clearable="false" v-model:value="formData.currency"
                                    :options="currencyColumns" :placeholder="t('placeholder.choose')" />
                            </uni-forms-item>
                        </uni-col>

                        <!-- 杠杆 -->
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('Custom.NewAccount.Lever')">
                                <cwg-combox :clearable="false" :disabled="hidden" v-model:value="formData.leverage"
                                    :options="leverageColumns" :placeholder="t('placeholder.choose')" />
                            </uni-forms-item>
                        </uni-col>

                        <!-- 账户余额 -->
                        <uni-col :xs="24" v-if="dome">
                            <uni-forms-item :label="t('Custom.NewAccount.Balance')">
                                <uni-easyinput type="digit" :clearable="false" v-model="formData.balance"
                                    :placeholder="t('Custom.NewAccount.BalancePlaceholder')" />
                            </uni-forms-item>
                        </uni-col>
                        <!-- 交易密码 -->
                        <uni-col :xs="24">
                            <uni-forms-item :label="t('Custom.NewAccount.Password')">
                                <uni-easyinput :clearable="false" v-model="formData.password"
                                    :placeholder="t('Custom.NewAccount.Password')" />
                            </uni-forms-item>
                        </uni-col>
                        <uni-col :xs="24">
                            <view class="notice-list">
                                <view v-for="(item, index) in noticeItems" :key="index"
                                    :class="['notice-item', item.valid ? 'isOK' : '']">
                                    {{ item.label }}
                                </view>
                            </view>
                        </uni-col>


                        <uni-col :xs="24">
                            <view class="btn btn-confirm" @click="newAccount">{{ t('Btn.Application') }}</view>
                        </uni-col>
                    </uni-row>
                </uni-forms>
            </view>

            <view class="card-content">
                <text class="account-name" v-t="currentAccount?.name"></text>

                <!-- 点差信息 -->
                <view class="info-row">
                    <view class="info-label">最低入金</view>
                    <view class="info-value">{{ currentAccount?.minDeposit || '--' }}</view>
                </view>
                <!-- 点差信息 -->
                <view class="info-row">
                    <view class="info-label">最小点差</view>
                    <view class="info-value">{{ currentAccount?.minSpread || '--' }}</view>
                </view>

                <!-- 杠杆信息 -->
                <view class="info-row">
                    <view class="info-label">最大杠杆</view>
                    <view class="info-value">{{ currentAccount?.maxLeverage || '--' }}</view>
                </view>
                <view class="info-row">
                    <view class="info-value"><a href="/static/pdf/PrivacyPolicy2019_01.pdf" target="_blank"
                            v-t="'news_add_field.OpenAccount.Des2'"></a></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>

        <!-- 账户开立上限提示弹框 -->
        <uni-popup :show="dialogAccountLimit" mode="center" round="16" @close="closeAccountLimitDialog">
            <view class="account-limit-content">
                <view class="icon">
                    <text class="iconfont icon-warning"></text>
                </view>
                <view class="title">{{ t('accountLimit.title') }}</view>
                <view class="content">
                    <view class="limit-text">
                        <view>{{ t('accountLimit.mt4Message') }}</view>
                        <view>
                            <view>{{ t('accountLimit.mt4Condition1') }}</view>
                        </view>
                        <view>{{ t('accountLimit.mt4Action') }}</view>
                    </view>
                </view>
                <view class="dialog-footer">
                    <uv-button type="primary" class="confirm-btn" @click="closeAccountLimitDialog">
                        {{ t('accountLimit.button') }}
                    </uv-button>
                </view>
            </view>
        </uni-popup>
    </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.indexOf('7') === -1,
        description: 'Custom.NewAccount.DesLogin5',
        minDeposit: '50 USD',
        minSpread: '0.01',
        maxLeverage: '1:1000',
        icon: '/static/images/info/bank-information-1.webp',
    },
    {
        id: 2,
        type: 'SeniorAccount',
        name: 'AccountType.SeniorAccount',
        showCondition: () => showLogin.value.indexOf('2') === -1,
        description: 'Custom.NewAccount.DesLogin3',
        features: [
            { key: 'Custom.NewAccount.DesLogin31', condition: true },
            { key: 'Custom.NewAccount.DesLogin32', condition: true },
            { key: 'Custom.NewAccount.DesLogin33', condition: true },
            { key: 'Custom.NewAccount.DesLogin34', condition: true }
        ],
        minDeposit: '200 USD',
        minSpread: '0.01',
        maxLeverage: '1:2000',
        icon: '/static/images/info/bank-information-2.webp',
    },
    {
        id: 8,
        type: 'CentAccount',
        name: 'AccountType.CentAccount',
        showCondition: () => showLogin.value.indexOf('8') === -1 && isTimeShow.value,
        description: 'Custom.NewAccount.DesLogin8',
        features: [
            { key: 'Custom.NewAccount.DesLogin81', condition: true },
            { key: 'Custom.NewAccount.DesLogin82', condition: true },
            { key: 'Custom.NewAccount.DesLogin84', condition: true }
        ],
        minDeposit: '10 USD',
        minSpread: '0.01',
        maxLeverage: '1:1000',
        icon: '/static/images/info/bank-information-3.webp',
    }
])
const cativeIndex = ref(0)
const tabs = computed(() => ([
    { id: 'real', name: '真实' },
    { id: 'demo', name: '模拟' }
]))

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 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 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.3rd'), valid: rule3.value }
])

// 验证规则
const rules = {
    password: [
        {
            validator: (rule, value, callback) => {
                if (/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[~!@&%$^*./\\(\\)\\+\\=#_-])[A-Za-z0-9~!@&%$^*./\\(\\)\\+\\=#_-]{8,16}$/.test(value)) {
                    callback();
                } else {
                    callback(new Error(t('vaildate.password.format')));
                }
            },
            trigger: 'blur',
            required: true
        }
    ],
    platform: [
        {
            required: true,
            message: t('vaildate.select.empty'),
            trigger: 'change'
        }
    ],
    currency: [
        {
            required: true,
            message: t('vaildate.select.empty'),
            trigger: 'change'
        }
    ],
    leverage: [
        {
            required: true,
            message: t('vaildate.select.empty'),
            trigger: 'change'
        }
    ],
    balance: [
        {
            validator: (rule, value, callback) => {
                if (value === null || value === undefined || value === '') {
                    callback();
                    return;
                }
                const numValue = Number(value);
                if (isNaN(numValue)) {
                    callback(new Error(t('vaildate.amount.format')));
                    return;
                }
                if (numValue < 0 || numValue > 100000) {
                    callback(new Error(t('vaildate.amount.amount') + '0-100000'));
                    return;
                }
                callback();
            },
            trigger: ['blur', 'change']
        }
    ]
};
// 平台选项
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 = () => {
    if (formRef.value) {
        formRef.value.resetFields();
    }
    dialogCheck.value = false;
    dialogVisible.value = false;
};

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

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

// 获取必要数据
const getMustData = async (type, isDome) => {
    const api = isDome ? customApi.AccountApplyDataDome : customApi.AccountApplyData;
    const res = await api({
        type: type
    });
    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 () => {

    if (flag.value) return;
    flag.value = true;
    const api = dome.value ? customApi.AccountApplyAddDome : customApi.AccountApplyAdd;
    const res = await api({
        type: 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;
        dialogCheck.value = true;
        dialogVisible.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;
        dialogCheck.value = true;
        dialogVisible.value = false;
        flag.value = false;
    }
};


// 选择平台
const checkPlatform = (pla) => {
    if (pla === 'mt5s') {
        hidden.value = false;
    } else {
        hidden.value = true;
    }
    formData.currency = '';
    formData.leverage = '';
    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) {
        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/webview/index?url=https://www.${ho.value}.com/${path}`
    });
};

// 打开PDF
const openPdf = (path) => {
    uni.navigateTo({
        url: `/pages/webview/index?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 == 1
});

// 生命周期
onLoad((e) => {
    dome.value = e.server == 'demo'
    cativeIndex.value = e.server == 'demo' ? 1 : 0
    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";

.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(--color-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: var(--color-secondary);
            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);
        color: var(--color-yellow-800);
        line-height: px2rpx(24);
    }

    .isOK {
        color: var(--color-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: #1e2a3a;
        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: #1e2a3a;
        }
    }

    .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>