<template>
    <view class="page">
        <!-- 表单 -->
        <view class="form">
            <u-form label-position="left" :model="form" ref="form" label-width="180rpx">
                <!-- 用户ID -->
                <u-form-item label="用户ID">
                    <view class="value id-box">
                        <text>{{ userInfo.userId }}</text>
                        <u-button size="mini" type="success" plain class="copy-btn" @click="copyUserId">复制</u-button>
                    </view>
                </u-form-item>

                <!-- 头像 -->
                <u-form-item label="头像">
                    <view class="value avatarbox">
                        <button open-type="chooseAvatar" class="avatarBtn" @chooseavatar="onChooseavatar">
                            <u-avatar style="height: 72rpx;" size="72" :src="userInfo.imgPath"></u-avatar>
                        </button>
                    </view>
                </u-form-item>

                <!-- 昵称 -->
                <u-form-item label="昵称">
                    <view class="value nickname-input">
                        <input type="nickname" v-model="userInfo.nickName" placeholder="请输入昵称"
                            placeholder-style="color: #696969" @input="onNicknameInput" />
                    </view>
                </u-form-item>

                <!-- 手机号 -->
                <u-form-item label="手机号">
                    <view class="value">
                        <!-- 未绑定手机号，显示获取手机号按钮 -->
                        <button class="get-phone-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
                            <text class="common-text-2" v-if="userInfo.mobile">{{ userInfo.mobile }}</text>
                            <text class="common-text" v-else>未绑定</text>
                            <u-icon :color="arrowColor" style="margin-left: 20rpx;" size="28"
                                name="arrow-right"></u-icon>
                        </button>
                    </view>
                </u-form-item>
            </u-form>
        </view>

        <!-- 提交按钮 -->
        <view class="btn">
            <u-button type="primary" shape="circle" :loading="submitting" @click="submitChanges">提交</u-button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            arrowColor: this.$appTheme.appThemeTextGrayColor,
            themeColor: this.$appTheme.appThemeColor,
            userInfo: {
                userId: '125885222658442698874444',
                nickName: '',
                imgPath: '',
                mobile: ''
            },
            originalInfo: {}, // 保存原始信息，用于对比是否有修改
            submitting: false, // 提交状态
            uploading: false, // 添加上传状态
        }
    },
    onLoad() {
        this.getUserInfo()
    },
    methods: {
        // 获取用户信息
        getUserInfo() {
            uni.$u.http.get('/token/user/detail').then(res => {
                if (res.code == 200) {
                    this.userInfo = res.data
                }
            })
        },

        // 复制用户ID
        copyUserId() {
            uni.setClipboardData({
                data: this.userInfo.userId,
                success: () => {
                    uni.$u.toast('复制成功')
                }
            })
        },

        // 昵称输入
        onNicknameInput(e) {
            this.userInfo.nickName = e.detail.value
            this.updateUserInfo()
        },

        // 选择并上传头像
        async onChooseavatar(e) {
            const tempFilePath = e.detail.avatarUrl
            if (!tempFilePath) {
                return uni.$u.toast('获取头像失败')
            }

            try {
                this.uploading = true
                uni.showLoading({
                    title: '上传中...',
                    mask: true
                })

                // 上传头像
                const uploadRes = await this.uploadFile(tempFilePath)

                if (uploadRes.code === 200) {
                    this.userInfo.imgPath = uploadRes.data
                    uni.$u.toast('头像上传成功')
                } else {
                    throw new Error(uploadRes.msg || '上传失败')
                }
            } catch (error) {
                uni.$u.toast('头像上传失败，请重试')

                // 还原头像
                this.userInfo.imgPath = this.originalInfo.imgPath
            } finally {
                this.uploading = false
                uni.hideLoading()
            }
        },

        // 文件上传方法
        uploadFile(filePath) {
            return new Promise((resolve, reject) => {
                uni.uploadFile({
                    url: this.$u.http.config.baseUrl + '/token/user/avatarUpload',
                    filePath: filePath,
                    name: 'file',
                    header: {
                        'Authorization': 'Bearer ' + uni.getStorageSync('token')
                    },
                    success: (uploadFileRes) => {
                        try {
                            // 解析响应数据
                            const res = JSON.parse(uploadFileRes.data)
                            resolve(res)
                        } catch (e) {
                            reject(new Error('解析响应失败'))
                        }
                    },
                    fail: (error) => {
                        reject(error)
                    }
                })
            })
        },

        // 跳转换绑手机号页面
        goToChangeMobile() {
            uni.navigateTo({
                url: '/pages-mine/pages/change-mobile/index'
            })
        },

        // 获取手机号
        async getPhoneNumber(e) {
            if (e.detail.errMsg !== 'getPhoneNumber:ok') {
                return uni.$u.toast('获取手机号失败')
            }

            try {
                uni.showLoading({
                    title: '手机号获取中'
                })

                // 调用后端接口解密手机号
                uni.$u.http.post('/token/user/wxMobileUpdate', { code: e.detail.code }).then(res => {
                    if (res.code === 200) {
                        // 更新本地用户信息
                        this.userInfo.mobile = res.data.mobile

                        uni.showToast({
                            title: '绑定成功',
                            icon: 'success'
                        })
                    } else {
                        uni.$u.toast('手机号绑定失败')
                    }
                })
            } catch (error) {
                uni.$u.toast('手机号绑定失败')
            } finally {
                uni.hideLoading()
            }
        },

        //更新用户信息
        updateUserInfo() {
            uni.$u.http.post('/token/user/wxBasicUpdate', {
                nickName: this.userInfo.nickName,
                imgPath: this.userInfo.imgPath
            }).then(res => {
                console.log(res)
            })
        },

        // 提交修改
        async submitChanges() {
            if (this.uploading) {
                return uni.$u.toast('头像上传中，请稍候...')
            }

            if (!this.hasChanges) return

            if (!this.userInfo.nickName.trim()) {
                return uni.$u.toast('请输入昵称')
            }

            this.submitting = true
            try {
                const { code, data } = await this.$u.api.setUserBaseInfoAjax({
                    nickName: this.userInfo.nickName,
                    imgPath: this.userInfo.imgPath
                })

                if (code === 1) {
                    uni.$u.toast('保存成功')
                    this.originalInfo = { ...this.userInfo }
                    uni.$emit("getUserInfo")
                    setTimeout(() => {
                        uni.navigateBack()
                    }, 1500)
                }
            } catch (error) {
                uni.$u.toast('保存失败，请重试')
            } finally {
                this.submitting = false
            }
        },

        // 更新计算属性中的判断逻辑
        computed: {
            hasChanges() {
                return !this.uploading && (
                    this.userInfo.nickName !== this.originalInfo.nickName ||
                    this.userInfo.imgPath !== this.originalInfo.imgPath
                )
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.page {
    padding: 24rpx 30rpx;
    background-color: $app-theme-bg-color;
    min-height: 100vh;
    display: flex;
    flex-direction: column;

    .form {
        flex: 1;
        background: #FFFFFF;
        border-radius: 12rpx;
        padding: 20rpx 0;

        .value {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            font-size: 28rpx;
            color: $app-theme-card-gray-deep-color;

            &.nickname-input {
                input {
                    text-align: right;
                    width: 400rpx;
                    font-size: 28rpx;
                }

                .wechat-tag {
                    font-size: 24rpx;
                    color: #999;
                    margin-left: 12rpx;
                }
            }

            &.id-box {
                .copy-btn {
                    margin-left: 20rpx;
                    padding: 0 20rpx;
                    height: 48rpx !important;
                    line-height: 44rpx !important;
                }
            }

            .phone-box {
                display: flex;
                align-items: center;
            }

            .get-phone-btn {
                background: none;
                border: none;
                padding: 0;
                margin: 0;
                display: flex;
                align-items: center;
                font-size: 28rpx;

                &::after {
                    border: none;
                }
            }
        }
    }

    .avatarBtn {
        border: none;
        background-color: transparent;
        display: inline-flex;
        align-items: center;
        padding: 0;
        margin: 0;
        width: 75rpx;
        height: 75rpx;
        border-radius: 50%;
    }
}
</style>
