<template>
    <!-- {{ formData.avatar }} -->
    <Form :rules="fieldConfigs" v-model="formData" ref="formRef">
        <up-table>
            <up-tr>
                <up-th>艺术照</up-th>
                <Td field="avatar">
                    <SsUploadAvatar v-model="formData.avatar" @updated="onAvatarUpdated"  />
                </Td>
            </up-tr>
            <up-tr>
                <up-th>原密码</up-th>
                <Td field="oldPwd">
                    <SsInput v-model="formData.oldPwd" placeholder="请输入" />
                </Td>
            </up-tr>
            <up-tr>
                <up-th>新密码</up-th>
                <Td field="newPwd">
                    <SsInput v-model="formData.newPwd" placeholder="请输入" />
                </Td>
            </up-tr>
            <up-tr>
                <up-th>确认新密码</up-th>
                <Td field="confirmPwd">
                    <SsInput v-model="formData.confirmPwd" placeholder="请输入" />
                </Td>
            </up-tr>
        </up-table>
    </Form>

    <!-- 底部按钮 -->
    <SsBottom :buttons="bottomButtons" @button-click="handleBottomAction" />
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import Form from '@/components/Form/index.vue'
import Td from '@/components/Td/index.vue'
import SsInput from '@/components/SsInput/index.vue'
import SsUploadAvatar from '@/components/SsUploadAvatar/index.vue'
import SsBottom from '@/components/SsBottom/index.vue'
import { goBack } from '@/utils/navigation'
import { userApi } from '@/api/user'
import { useUserStore } from '@/store/modules/user'

const userStore = useUserStore()

// 从缓存中获取用户信息，初始化头像
const getUserAvatar = () => {
    let userInfo = uni.getStorageSync('userInfo')
    if (typeof userInfo === 'string') {
        userInfo = JSON.parse(userInfo)
    }
    // 优先使用 yszwj（艺术照文件）字段
    if (userInfo?.yszwj) {
        return userInfo.yszwj
    }
    // 根据性别返回默认头像
    return userInfo?.xbm == 1
        ? '/static/images/yishuzhao_nan.svg'
        : '/static/images/yishuzhao_nv.svg'
}

const formData = ref({
    avatar: getUserAvatar(),
    oldPwd: '',
    newPwd: '',
    confirmPwd: ''
})
const formRef = ref(null)
const bottomButtons = [
    { text: '取消', action: 'back' },
    { text: '保存', action: 'save' }
]
const handleBottomAction = (data) => {
    console.log('底部按钮操作:', data)

    switch (data.action) {
        case 'back':
            // 返回处理
            goBack()
            break
        case 'save':
            handleSubmit()
            break
    }
}
const handleSubmit = async () => {
    if (formRef.value) {
        try {
            // 从缓存中获取用户信息
            let userInfo = uni.getStorageSync('userInfo')
            if (typeof userInfo === 'string') {
                userInfo = JSON.parse(userInfo)
            }

            const oldPwd = formData.value.oldPwd
            const newPwd = formData.value.newPwd
            const confirmPwd = formData.value.confirmPwd
            const yhm = userInfo?.yhm || ''

            // 判断用户意图：是否要修改密码
            const hasPasswordInput = oldPwd || newPwd || confirmPwd

            if (hasPasswordInput) {
                // ===== 用户要修改密码，进行密码校验 =====

                // 1. 检查所有密码字段是否都填写了
                if (!oldPwd) {
                    uni.showToast({
                        title: '请输入原密码',
                        icon: 'none'
                    })
                    return false
                }
                if (!newPwd) {
                    uni.showToast({
                        title: '请输入新密码',
                        icon: 'none'
                    })
                    return false
                }
                if (!confirmPwd) {
                    uni.showToast({
                        title: '请输入确认密码',
                        icon: 'none'
                    })
                    return false
                }

                // 2. 新密码与密码确认不一致
                if (newPwd !== confirmPwd) {
                    uni.showToast({
                        title: '新密码与确认密码不一致！',
                        icon: 'none'
                    })
                    return false
                }

                // 3. 密码长度必需大于等于6位
                if (newPwd.length < 6) {
                    uni.showToast({
                        title: '密码长度必需大于等于6位！',
                        icon: 'none'
                    })
                    return false
                }

                // 4. 密码必需包含数字和字母
                if (!(newPwd.match(/[a-zA-Z]+/) && newPwd.match(/\d+/))) {
                    uni.showToast({
                        title: '密码必需包含数字和字母！',
                        icon: 'none'
                    })
                    return false
                }

                // 5. 密码不能包含账号
                if (yhm && newPwd.indexOf(yhm) !== -1) {
                    uni.showToast({
                        title: '密码不能包含账号！',
                        icon: 'none'
                    })
                    return false
                }
            }

            // ===== 组装提交数据 =====
            const submitData = {
                yhid: userInfo?.yhid || '',
                yszwj: formData.value.avatar
            }

            // 如果要修改密码，添加密码字段
            if (hasPasswordInput) {
                submitData.oldPwd = oldPwd
                submitData.newPassword = newPwd
                submitData.againNewPassword = confirmPwd
            }

            console.log('提交数据:', submitData)

            // 调用接口提交数据
            const res = await userApi.updPwd(submitData)

            

            // 修改成功
            if (res.data.msg === '密码修改成功，请重新登录') {
                uni.showToast({
                    title: '修改成功，请重新登录',
                    icon: 'success'
                })

                // 清除缓存并跳转登录
                setTimeout(() => {
                    uni.removeStorageSync('userInfo')
                    uni.removeStorageSync('JSESSIONID')
                    userStore.showH5Login()
                }, 1500)
            } else {
                // 修改失败，显示错误信息
                console.error('❌ 修改失败:', res.data.msg)
                uni.showToast({
                    title: res.data.msg,
                    icon: 'none',
                    duration: 2000
                })
                return
            }
        }
        catch (error) {
            console.log('提交失败:', error)
            uni.showToast({
                title: error.message || '提交失败，请重试',
                icon: 'none'
            })
        }
    }
}

function onAvatarUpdated(newUrl) {
  console.log('最新头像地址:', newUrl)
}
</script>

<style scoped></style>