<template>
    <view class="scroll-container theme-light">
        <view class="set-pay-password-page">
            <MemberInfoSubNav :title="isReset ? '修改支付密码' : '设置支付密码'" @back="goBack" />
            <view class="set-pay-password-page__body">
                <view class="spp-intro">
                    <image class="spp-intro__icon" src="https://gymfuture.oss-cn-chengdu.aliyuncs.com/static/images/lock.png" mode="aspectFit" />
                </view>

                <VerifyCodeInput
                    ref="verifyInputRef"
                    v-model="password"
                    :title="currentTitle"
                    :desc="currentDesc"
                    :length="6"
                    :mask="true"
                    type="box"
                    :errorMsg="errorMsg"
                    @complete="handleComplete"
                />

                <view class="spp-forgot" v-if="isReset && step === 1" @tap="goForgotPassword">
                    <text>忘记密码？</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import MemberInfoSubNav from '@/components/memberInfo/MemberInfoSubNav.vue'
import VerifyCodeInput from '@/components/global/VerifyCodeInput.vue'
import { getMemberId } from '@/utils/request.js'
import { setPayPassword, verifyPayPassword, resetPayPassword } from '@/api/main.js'

const password = ref('')
const step = ref(1)
const firstPassword = ref('')
const isReset = ref(false)
const errorMsg = ref('')
const verifyInputRef = ref(null)

const currentTitle = computed(() => {
    if (isReset.value && step.value === 1) {
        return '请输入原6位支付密码'
    }
    if (step.value === 1) {
        return isReset.value ? '请输入新的6位支付密码' : '请设置6位支付密码'
    }
    return '请再次输入6位支付密码'
})

const currentDesc = computed(() => {
    if (isReset.value && step.value === 1) {
        return '验证原密码后可设置新密码'
    }
    return '支付密码用于充值、消费等资金操作，请妥善保管'
})

onLoad((options) => {
    if (options && options.reset === 'true') {
        isReset.value = true
    }
})

function handleComplete(pwd) {
    errorMsg.value = ''

    if (isReset.value && step.value === 1) {
        verifyOldPassword(pwd)
        return
    }

    if (step.value === 1) {
        firstPassword.value = pwd
        step.value = 2
        password.value = ''
        nextTick(() => {
            verifyInputRef.value?.focusInput()
        })
    } else {
        if (pwd !== firstPassword.value) {
            errorMsg.value = '两次密码输入不一致，请重新输入'
            password.value = ''
            step.value = 1
            firstPassword.value = ''
            nextTick(() => {
                verifyInputRef.value?.focusInput()
            })
            return
        }
        submitPassword(pwd)
    }
}

async function verifyOldPassword(pwd) {
    const memberId = getMemberId()

    if (!memberId) {
        uni.showToast({ title: '用户未登录', icon: 'none' })
        return
    }

    uni.showLoading({ title: '验证中...' })

    try {
        const res = await verifyPayPassword(memberId, pwd)
        uni.hideLoading()

        if (res && (res.valid === true || res.data?.valid === true)) {
            step.value = 2
            password.value = ''
            firstPassword.value = ''
            nextTick(() => {
                verifyInputRef.value?.focusInput()
            })
        } else {
            errorMsg.value = '原密码错误，请重新输入'
            password.value = ''
            nextTick(() => {
                verifyInputRef.value?.focusInput()
            })
        }
    } catch (e) {
        uni.hideLoading()
        errorMsg.value = '验证失败，请稍后重试'
        password.value = ''
    }
}

async function submitPassword(pwd) {
    const memberId = getMemberId()

    if (!memberId) {
        uni.showToast({ title: '用户未登录', icon: 'none' })
        return
    }

    uni.showLoading({ title: '设置中...' })

    try {
        let res
        if (isReset.value) {
            res = await resetPayPassword(memberId, firstPassword.value, pwd)
        } else {
            res = await setPayPassword(memberId, pwd)
        }

        uni.hideLoading()

        if (res && (res.code === 200 || res.code === 200 || res.message === '设置成功' || res.message === '重置成功')) {
            uni.showToast({ title: isReset.value ? '修改成功' : '设置成功', icon: 'success' })
            setTimeout(() => {
                uni.navigateBack()
            }, 1500)
        } else {
            uni.showToast({ title: res.message || '设置失败', icon: 'none' })
            password.value = ''
            step.value = 1
            firstPassword.value = ''
        }
    } catch (e) {
        uni.hideLoading()
        uni.showToast({ title: '设置失败，请稍后重试', icon: 'none' })
        password.value = ''
        step.value = 1
        firstPassword.value = ''
    }
}

function goBack() {
    uni.navigateBack()
}

function goForgotPassword() {
    uni.showToast({ title: '请联系客服重置密码', icon: 'none' })
}
</script>

<style lang="scss">
@import '@/common/style/base.css';
@import '@/common/style/memberInfo/pages/page-reset.css';
@import '@/common/style/memberInfo/pages/sub-page-base.css';

.set-pay-password-page {
    min-height: 100vh;
    background: #F5F7FA;
}

.set-pay-password-page__body {
    padding: 40px 24px;
}

.spp-intro {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 24px;
}

.spp-intro__icon {
    width: 56px;
    height: 56px;
}

.spp-forgot {
    text-align: right;
    margin-top: 8px;
}

.spp-forgot text {
    font-size: 13px;
    color: #1677FF;
}
</style>
