<template>
    <cwg-popup :title="pwdTitle" :visible="props.visible" :showFooters="false"
        @update:visible="$emit('update:visible', $event)" >
        <view class="popup-content">
            <text class="account-number">{{ accountLabel }} {{ account.login }}</text>

            <template v-if="props.pwdType != 3">
                <uni-forms :model="passwordInfo" labelWidth="200" label-position="top" class="crm-form">
                    <uni-forms-item
                        :label="props.pwdType == 1 ? t('Custom.Settings.LoginPwdOld') : t('Custom.Settings.LoginPwdOld1')">
                        <uni-easyinput type="password" :clearable="false" v-model="passwordInfo.oldPassword"
                            :placeholder="props.pwdType == 1 ? t('Custom.Settings.LoginPwdOld') : t('Custom.Settings.LoginPwdOld1')" />
                    </uni-forms-item>
                    <uni-forms-item :label="props.pwdType == 1 ? t('Custom.Settings.NewPwd') : t('Custom.Settings.InvestorNewPwd')">
                        <uni-easyinput type="password" :clearable="false" v-model="passwordInfo.newPassword"
                            :placeholder="props.pwdType == 1 ? t('Custom.Settings.NewPwd') : t('Custom.Settings.InvestorNewPwd')" />
                    </uni-forms-item>
                </uni-forms>

                <view class="notice-list">
                    <view v-for="(item, index) in noticeItems" :key="index"
                        :class="['notice-item', item.valid ? 'isOK' : '']">
                        {{ item.label }}
                    </view>
                </view>
            </template>

            <view class="save-btn">
                <view v-if="props.pwdType != 3" class="btn btn-secondary btn-shadow waves-effect" @click="save"
                    v-t="'Btn.Save'" />
                <view v-else class="btn btn-secondary btn-shadow waves-effect" @click="resetPwd"
                    v-t="'Btn.ResetPassword'" />
            </view>
        </view>
        <cwg-confirm-popup />
    </cwg-popup>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { customApi } from '@/service/custom';
import { useI18n } from 'vue-i18n'
import { showToast } from "@/utils/toast";
import { useConfirm } from '@/hooks/useConfirm'
const confirm = useConfirm()
const { t } = useI18n()

const props = defineProps({
    visible: { type: Boolean, default: false },
    account: { type: Object, default: () => ({}) },
    accountLabel: { type: String, default: '账户: #' },
    // 1: 交易密码, 2: 投资者密码
    pwdType: { type: [Number, String], default: 1 },
})

const emit = defineEmits(['update:visible', 'save'])

const passwordInfo = ref({
    oldPassword: '',
    newPassword: ''
});
const pwdTitle = computed(() => {
    switch (props.pwdType) {
        case 1:
            return t('vu.item3')
        case 2:
            return t('vu.item4')
        case 3:
            return t('Btn.ResetPassword')
    }
})
const rule1 = computed(() => {
    if (!passwordInfo.value.newPassword) return false;
    return /^.{8,16}$/.test(passwordInfo.value.newPassword);
});

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

const rule3 = computed(() => {
    return /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?!.*([~!@&%$^\\(\\)#_]).*\\1.*\\1)[A-Za-z0-9~!@&%$^\\(\\)#_]{8,16}$/.test(
        passwordInfo.value.newPassword
    );
});
const rule4 = computed(() => {
    return /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[~!@&%$^*./\\(\\)\\+\\=#_-])[A-Za-z0-9~!@&%$^*./\\(\\)\\+\\=#_-]{8,16}$/.test(
        passwordInfo.value.newPassword
    );
});

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 flag = ref(false); // 防止重复提交

const save = async () => {
    if (!/^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[~!@&%$^*./\\(\\)\\+\\=#_-])[A-Za-z0-9~!@&%$^*./\\(\\)\\+\\=#_-]{8,16}$/.test(passwordInfo.value.oldPassword)) {
        showToast(t('vaildate.password.format'));
        return;
    }
    if (!rule1.value || !rule2.value || !rule4.value) {
        return;
    }
    if (flag.value) return;
    flag.value = true;

    try {
        let res;
        if (props.pwdType == 1) {
            // 修改交易账户密码
            res = await customApi.ChangeDealPassword({
                login: props.account.login,
                ...passwordInfo.value
            });
        } else {
            // 修改投资者密码
            res = await customApi.ChangeInvestorOassword({
                login: props.account.login,
                ...passwordInfo.value
            });
        }

        if (res.code == 200) {
            await confirm({
                title: t('Msg.SystemPrompt'),
                content: t('ApplicationDialog.Des1'),
                confirmText: t('Btn.Confirm'),
                cancelText: t('Btn.Cancel')
            })
            emit('update:visible', false);
            passwordInfo.value = {
                oldPassword: '',
                newPassword: ''
            }
            emit('save');
        } else {
            await confirm({
                title: t('Msg.SystemPrompt'),
                content: res.msg,
                confirmText: t('Btn.Confirm'),
                cancelText: t('Btn.Cancel')
            })
            emit('update:visible', false);
        }
    } catch (error) {
        showToast(error.msg);
        emit('update:visible', false);
    } finally {
        flag.value = false;
    }
}
// 重置交易账号密码
const resetPwd = async () => {
    try {
        if (flag.value) {
            return
        } else {
            flag.value = true;
        }

        let res = await customApi.ResetDealPasswordEmail({
            login: props.account.login
        });
        if (res.code == 200) {
            flag.value = false;
            await confirm({
                title: t('Msg.SystemPrompt'),
                content: t('ApplicationDialog.Des1'),
                confirmText: t('Btn.Confirm'),
                cancelText: t('Btn.Cancel')
            })
            emit('update:visible', false);
        } else {
            flag.value = false;
            await confirm({
                title: t('Msg.SystemPrompt'),
                content: res.msg,
                confirmText: t('Btn.Confirm'),
                cancelText: t('Btn.Cancel')
            })
            // showToast(res.msg);
            emit('update:visible', false);
        }
    } catch (error) {
      error.msg&&showToast(error.msg);
        emit('update:visible', false);
    } finally {
        flag.value = false;
    }
}
watch(() => props.visible, (newVal) => {
    if (newVal) {
        passwordInfo.value = {
            oldPassword: '',
            newPassword: ''
        }
        flag.value = false;
    }
})
</script>

<style scoped lang="scss">
@import "@/uni.scss";
@media (min-width: 768px) {
    :deep(.cwg-dialog) {
        background-color: rgba(var(--bs-body-bg-rgb), var(--bs-bg-opacity)) !important;
        border-radius: px2rpx(8);
        width: px2rpx(480) !important;
    }
}

.popup-content {
    padding: px2rpx(16);
}

.account-number {
    text-align: left;
    display: block;
    font-size: px2rpx(14);
    color: var(--bs-emphasis-color);
    margin-bottom: px2rpx(24);
}

.crm-form {
    :deep(.uni-forms-item) {
        margin-bottom: px2rpx(16);
    }

    :deep(.uni-easyinput__content) {
        border: none !important;
        background-color: var(--color-zinc-100) !important;
    }
}

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

    .notice-item {
        text-align: left;
        font-size: px2rpx(14);
        color: var(--bs-emphasis-color);
        line-height: px2rpx(24);

        &::before {
            content: '●';
            display: inline-block;
            font-size: px2rpx(10);
            margin-right: px2rpx(4);
        }
    }

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

.save-btn {
    width: 100%;
    display: flex;
    justify-content: flex-end;
    margin-top: px2rpx(20);

    // .btn {
    //     border: 1px solid rgba(108, 133, 149, 0);
    //     border-radius: px2rpx(8);
    //     padding: px2rpx(8) px2rpx(20);
    //     font-size: px2rpx(14);
    //     color: rgba(var(--bs-dark-rgb), var(--bs-text-opacity)) !important;
    //     display: inline-flex;
    //     align-items: center;
    //     justify-content: center;
    //     gap: px2rpx(8);
    //     cursor: pointer;
    //     transition: all 0.2s;
    //     height: px2rpx(40);
    //     box-sizing: border-box;
    //     background-color: rgba(108, 133, 149, 0.08);

    //     &.primary {
    //         background-color: #cf1322;
    //         ;
    //         color: var(--bs-emphasis-color);

    //         &:hover {
    //             background-color: var(--color-navy-600);
    //         }

    //         &[disabled] {
    //             cursor: not-allowed;
    //         }
    //     }
    // }
}
</style>