<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>
                        <image src="../static/copy.png" style="width: 42rpx;height:42rpx;margin-left: 20rpx;"
                            @click="copyUserId"></image>
                    </view>
                </u-form-item>

                <!-- 头像 -->
                <u-form-item label="头像">
                    <view class="value avatarbox">
                        <!-- #ifdef MP-WEIXIN -->
                        <button style="flex: none;" open-type="chooseAvatar" class="avatarBtn"
                            @chooseavatar="onChooseavatar">
                            <u-avatar shape="circle" style="height: 72rpx;" size="72"
                                :src="userInfo.imgPath"></u-avatar>
                        </button>
                        <!-- #endif -->
                        <!-- #ifdef MP-ALIPAY -->
                        <button style="flex: none;" open-type="chooseAvatar" class="avatarBtn"
                        onChooseAvatar="onChooseavatar">
                            <u-avatar shape="circle" style="height: 72rpx;" size="72"
                                :src="userInfo.imgPath"></u-avatar>
                        </button>
                        <!-- #endif -->
                    </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 phone-value">
                        <!-- #ifdef MP-WEIXIN -->
                        <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>
                        <!-- #endif -->
                        <!-- #ifdef MP-ALIPAY -->
                        <button class="get-phone-btn" open-type="getAuthorize" scope="phoneNumber"
                            @getAuthorize="onGetAuthorize" @error="handleAuthError">
                            <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>
                        <!-- #endif -->
                    </view>
                </u-form-item>
            </u-form>
        </view>

        <!-- 提交按钮 -->
        <view class="btn" style="padding: 60rpx 0;">
            <u-button type="primary" :loading="submitting" @click="submitChanges">更新信息</u-button>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            arrowColor: this.$appTheme.appThemeTextGrayColor,
            themeColor: this.$appTheme.appThemeColor,
            userInfo: {
                userId: '',
                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.toString(),
                success: () => {
                    uni.$u.toast('复制成功')
                },
                fail: (e) => {
                    console.log(e)
                    uni.$u.toast('复制失败')
                }
            })
        },

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

        // 选择并上传头像
        async onChooseavatar(e) {
            const tempFilePath = e.detail.avatarUrl
            // http://tfs.alipayobjects.com/images/partner/TB1kQ2kXv5GDuNjHvSCXXczuXXa
            console.log(tempFilePath, 'onChooseavatar')
            if (!tempFilePath) {
                return uni.$u.toast('获取头像失败')
            }
            // #ifdef MP-ALIPAY
            // 下载支付宝头像
            //将tempFilePath转换为https://tfs.alipayobjects.com/images/partner/TB1kQ2kXv5GDuNjHvSCXXczuXXa
            let url = tempFilePath.indexOf('http://') > -1 ? tempFilePath.replace('http://', 'https://') : tempFilePath
            my.downloadFile({
                url: url,
                success: (res) => {
                    if (res.statusCode === 200) {
                        let aliTempFilePath = res.tempFilePath
                        this.uploadAvatar(aliTempFilePath)
                    }
                },
                fail: (err) => {
                    console.log(err, 'downloadFile fail')
                }
            })
            // #endif
            // #ifdef MP-WEIXIN
            this.uploadAvatar(tempFilePath)
            // #endif
        },
        //上传头像
        async uploadAvatar(tempFilePath){
            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 {
                    this.uploading = false
                    uni.hideLoading()
                    throw new Error(uploadRes.msg || '上传失败')
                }
            } 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)
                    }
                })
            })
        },

        onGetAuthorize(e) {
            console.log(e, 'onGetAuthorize')
            my.getPhoneNumber({
                success: (res) => {
                    this.getPhoneNumberApi(res.response, 'alipay')
                },
                fail: (err) => {
                    console.log('获取手机号失败', err);
                }
            })
        },

        handleAuthError(e) {
            console.log(e, 'handleAuthError')
        },

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

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


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

            try {
                uni.showLoading({
                    title: '手机号获取中'
                })
                this.getPhoneNumberApi(e.detail.code)
            } catch (error) {
                uni.$u.toast('手机号绑定失败')
            } finally {
                uni.hideLoading()
            }
        },

        //更新用户信息
        submitChanges() {
            this.submitting = true
            uni.$u.http.post('/token/user/wxBasicUpdate', {
                nickName: this.userInfo.nickName,
                imgPath: this.userInfo.imgPath
            }).then(res => {
                if (res.code == 200) {
                    this.$u.toast('更新信息成功')
                    uni.navigateBack({
                        delta: 1
                    })
                }
            }).finally(() => {
                this.submitting = false
            })
        },
    }
}
</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;

        .value {
            display: flex;
            align-items: center;
            justify-content: flex-end;
            font-size: 28rpx;
            color: #333333;

            &.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;
                }
            }

            &.avatarbox {
                justify-content: flex-end;
                width: 100%;
            }

            &.phone-value {
                justify-content: flex-end;
                width: 100%;
            }
        }

        .get-phone-btn {
            background: none;
            border: none;
            padding: 0;
            margin: 0;
            display: flex;
            align-items: center;
            justify-content: flex-end;
            font-size: 28rpx;
            width: 100%;

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

    .avatarBtn {
        border: none;
        background-color: transparent;
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0;
        margin: 0;
        width: 72rpx;
        height: 72rpx;

        &::after {
            border: none;
        }

        :deep(.u-avatar) {
            width: 72rpx !important;
            height: 72rpx !important;
            border-radius: 50% !important;
        }
    }
}
</style>