<template>
    <hc-card is-action-btn>
        <el-tabs tab-position="left" class="hc-h-full">
            <el-tab-pane label="个人信息">
                <div class="relative w-[460px] p-4">
                    <el-form ref="formUserRef" :model="formUserModel" :rules="formUserRules" label-position="top">
                        <el-form-item label="头像图片：" prop="avatar">
                            <hc-form-upload type="preview" :src="formUserModel.avatar" :num="1" @upload="avatarUpload" />
                        </el-form-item>
                        <el-form-item label="姓名：" prop="name">
                            <el-input v-model="formUserModel.name" />
                        </el-form-item>
                        <el-form-item label="用户名：" prop="realName">
                            <el-input v-model="formUserModel.realName" />
                        </el-form-item>
                        <el-form-item label="手机号码：" prop="phone">
                            <el-input v-model="formUserModel.phone" />
                        </el-form-item>
                        <el-form-item label="电子邮箱：">
                            <el-input v-model="formUserModel.email" />
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>
            <el-tab-pane label="修改密码">
                <div class="relative w-[460px] p-4">
                    <el-form ref="formPasswordRef" :model="formPasswordModel" :rules="formPasswordRules" label-position="top">
                        <el-form-item label="原密码：" prop="oldPassword">
                            <el-input v-model="formPasswordModel.oldPassword" />
                        </el-form-item>
                        <el-form-item label="新密码：" prop="newPassword">
                            <el-input v-model="formPasswordModel.newPassword" />
                        </el-form-item>
                        <el-form-item label="确认密码：" prop="newPassword1">
                            <el-input v-model="formPasswordModel.newPassword1" />
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>
        </el-tabs>

        <!-- 上传文件 -->
        <hc-upload-file ref="uploadRef" :options="uploadOptions" @success="uploadSuccess" />

        <template #action>
            <el-button hc-btn @click="resetClick">重置</el-button>
            <el-button hc-btn type="primary" :loading="submitLoading" @click="submitClick">提交</el-button>
        </template>
    </hc-card>
</template>

<script setup>
import { onActivated, ref } from 'vue'
import { getHeader } from 'hc-vue3-ui'
import { deepClone, formValidate, getObjValue, isPhone } from 'js-fast-way'
import mainApi from '~api/system/user'
import { reloadPage } from '~uti/tools.js'

defineOptions({
    name: 'UserInfo',
})

onActivated(() => {
    getUserInfoApi()
})

//获取用户信息
const oldUserInfo = ref({})
const getUserInfoApi = async () => {
    const { data } = await mainApi.getUserInfo()
    const res = getObjValue(data)
    oldUserInfo.value = res
    formUserModel.value = deepClone(res)
}

//个人信息表单
const formUserRef = ref(null)
const formUserModel = ref({})
const formUserRules = {
    avatar: {
        required: true,
        trigger: 'blur',
        message: '请上传头像图片',
    },
    name: {
        required: true,
        trigger: 'blur',
        message: '请输入姓名',
    },
    realName: {
        required: true,
        trigger: 'blur',
        message: '请输入用户名',
    },
    phone: {
        required: true,
        validator: (rule, value, callback) => {
            if (!value) {
                callback(new Error('请输入手机号'))
            } else if (!isPhone(value)) {
                callback(new Error('手机号码格式错误'))
            } else {
                callback()
            }
        },
        trigger: 'blur',
    },
}

//密码表单
const formPasswordRef = ref(null)
const formPasswordModel = ref({})
const formPasswordRules = {
    oldPassword: {
        required: true,
        trigger: 'blur',
        message: '请上传头像图片',
    },
    newPassword: {
        required: true,
        validator: (rule, value, callback) => {
            const { newPassword1 } = formPasswordModel.value
            if (!value) {
                callback(new Error('请输入新的密码'))
            } else if (newPassword1 && value !== newPassword1) {
                callback(new Error('新的密码和确认新密码不一致'))
            } else {
                callback()
            }
        },
        trigger: 'blur',
    },
    newPassword1: {
        required: true,
        validator: (rule, value, callback) => {
            const { newPassword } = formPasswordModel.value
            if (!value) {
                callback(new Error('请输入确认新密码'))
            } else if (newPassword && value !== newPassword) {
                callback(new Error('新的密码和确认新密码不一致'))
            } else {
                callback()
            }
        },
        trigger: 'blur',
    },
}


//上传文件
const uploadRef = ref(null)
const uploadOptions = ref({
    url: '/api/blade-resource/oss/endpoint/put-file2',
    headers: getHeader(),
    multiple: false,
    accept: '.png,.jpg,.jpeg,.gif,.awebp,.webp',
    accept_tip: '只能上传png/jpg/jpeg/gif/awebp/webp格式的图片文件',
    size: 30,
})

//上传头像
const avatarUpload = () => {
    uploadRef.value?.selectFile()
}

// 文件上传成功的回调
const uploadSuccess = ({ resData }) => {
    formUserModel.value.avatar = resData
    uploadRef.value?.setModalShow(false)
}

//重置
const resetClick = () => {
    formUserModel.value = deepClone(oldUserInfo.value)
}

//提交
const submitLoading = ref(false)
const submitClick = async () => {
    submitLoading.value = true
    //修改用户信息
    const isUserRes = await updateUserInfo()
    //修改密码
    const isPasswordRes = await updatePasswordInfo()
    submitLoading.value = false
    //状态提示
    if (isUserRes || isPasswordRes) {
        window?.$message?.success('保存成功')
        reloadPage()
    }
}

//修改用户信息
const updateUserInfo = async () => {
    const formRes = await formValidate(formUserRef.value)
    if (!formRes) return false
    const { id, avatar, name, realName, phone, email } = formUserModel.value
    const { error, code, msg } = await mainApi.updateInfo({
        id, avatar, name, realName, phone, email,
    })
    if (!error && code === 200) {
        return true
    } else {
        window?.$message?.error(msg ?? '操作失败')
        return false
    }
}

//修改密码
const updatePasswordInfo = async () => {
    const formRes = await formValidate(formPasswordRef.value)
    if (!formRes) return false
    const { oldPassword, newPassword, newPassword1 } = formPasswordModel.value
    const { error, code, msg } = await mainApi.updatePassword({
        oldPassword, newPassword, newPassword1, plaintextPassword: newPassword,
    })
    if (!error && code === 200) {
        return true
    } else {
        window?.$message?.error(msg ?? '操作失败')
        return false
    }
}
</script>
