<template>
    <view class="main">
        <!-- <view class="userInfoBox" @click="handleGoUserInfoCenter">
            <view class="userInfoBoxLeft">
                <view class="userInfoHeaderImg">
                    <image class="headerImg"
                        :src="userInfo.MEMBERSHIP_HEADIMAGEURL || user.MEMBERSHIP_HEADIMAGEURL || ''" />
                </view>

                <view class="userInfoMessage">
                    <view class="userInfoName">{{ userInfo.NICK_NAME || user.MEMBERSHIP_NAME || '' }}</view>
                    <view class="mainTopMessageUserLevelBox">
                        <image class="mainTopMessageUserLevelIcon"
                            src="https://eshangtech.com/caiyunyiImg/levelIcon.png" />
                        <view class="mainTopMessageUserLevelText">{{ user.MEMBERSHIP_LEVEL_TEXT || '' }}</view>
                    </view>
                </view>
            </view>
            <view class="userInfoBoxRight">
                <image class="rightArrow" src="https://eshangtech.com/caiyunyiImg/rightArrow.png" />
            </view>
        </view> -->

        <view class="userInfoContent">
            <view class="userInfoItem">
                <view class="userInfoItemLabel">头像</view>
                <view class="userInfoItemRight">
                    <view class="headerImgBox">
                        <button class="avatarBtn" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                            <image class="headerImg" :src="WXProfile ||
                                (userInfo && userInfo.MEMBERSHIP_HEADIMAGEURL
                                    ? userInfo.MEMBERSHIP_HEADIMAGEURL
                                    : '')
                                " />
                        </button>
                    </view>
                </view>
            </view>
            <view class="userInfoItem" @click="moveCursorToEnd(1)">
                <view class="userInfoItemLabel">昵称</view>
                <view class="userInfoItemRight">
                    <!-- <image class="rightArrow" src="https://eshangtech.com/caiyunyiImg/rightArrow.png" /> -->
                    <!-- <text class="rightText">{{ phone }}</text> -->
                    <input class="phoneBox" v-model="editableNickname" placeholder="请输入昵称" :focus="isFocused"
                        cursor-spacing="0" />

                </view>
            </view>

            <view class="userInfoItem">
                <view class="userInfoItemLabel">性别</view>
                <view class="userInfoItemRight">
                    <picker style="width: 100%;" @change="bindGenderChange" :value="genderIndex" :range="genderArray">
                        <view class="phoneBox">{{ genderArray[genderIndex] }}</view>
                    </picker>
                </view>
            </view>

            <view class="userInfoItem">
                <view class="userInfoItemLabel">生日</view>
                <view class="userInfoItemRight">
                    <picker style="width: 100%;" mode="date" @change="bindMultiPickerChange">
                        <view class="phoneBox">{{ birthday || '请选择生日' }}</view>
                    </picker>

                    <!-- <picker mode="multiSelector" @change="bindMultiPickerChange"
                        @columnchange="bindMultiPickerColumnChange" :value="multiIndex" :range="multiArray">
                        <view class="phoneBox">{{ birthday || '请选择生日' }}</view>
                    </picker> -->
                </view>
            </view>

            <view class="userInfoItem" @click="moveCursorToEnd(2)">
                <view class="userInfoItemLabel">邮箱地址</view>
                <view class="userInfoItemRight">
                    <input class="phoneBox" v-model="email" placeholder="请输入邮箱地址" @blur="validateEmail" />
                </view>
            </view>
        </view>

        <view class="userInfoContent">
            <view class="userInfoItem" @click="moveCursorToEnd(3)">
                <view class="userInfoItemLabel">真实姓名</view>
                <view class="userInfoItemRight">
                    <input class="phoneBox" v-model="realName" placeholder="请输入真实姓名" />
                </view>
            </view>

            <view class="userInfoItem" @click="moveCursorToEnd(4)">
                <view class="userInfoItemLabel">身份证号</view>
                <view class="userInfoItemRight">
                    <input class="phoneBox" v-model="idCard" placeholder="请输入身份证号" @blur="validateIdCard" />
                </view>
            </view>
        </view>

        <view class="userInfoContent">
            <view class="userInfoItem">
                <view class="userInfoItemLabel">电话号码</view>
                <view class="userInfoItemRight">
                    <!-- <image class="rightArrow" src="https://eshangtech.com/caiyunyiImg/rightArrow.png" /> -->
                    <text class="rightText">{{ phone }}</text>
                </view>
            </view>
            <!-- <view class="userInfoItem">
                <view class="userInfoItemLabel">实名认证</view>
                <view class="userInfoItemRight">
                    <image class="rightArrow" src="https://eshangtech.com/caiyunyiImg/rightArrow.png" />
                </view>
            </view> -->
            <view class="userInfoItem" @click="handleGoAddress">
                <view class="userInfoItemLabel">地址管理</view>
                <view class="userInfoItemRight">
                    <image class="rightArrow" src="https://eshangtech.com/caiyunyiImg/rightArrow.png" />
                </view>
            </view>
            <view class="userInfoItem" @click="handleGoFavoriteStore">
                <view class="userInfoItemLabel">我的收藏</view>
                <view class="userInfoItemRight">
                    <image class="rightArrow" src="https://eshangtech.com/caiyunyiImg/rightArrow.png" />
                </view>
            </view>
        </view>

        <view class="userInfoContent">
            <view class="userInfoItem" @click="handleShowPrivacy">
                <view class="userInfoItemLabel">隐私协议</view>
                <view class="userInfoItemRight">
                    <image class="rightArrow" src="https://eshangtech.com/caiyunyiImg/rightArrow.png" />
                </view>
            </view>
            <view class="userInfoItem" @click="handleGoLoginOut">
                <view class="userInfoItemLabel">退出登录</view>
                <view class="userInfoItemRight">
                    <image class="rightArrow" src="https://eshangtech.com/caiyunyiImg/rightArrow.png" />
                </view>
            </view>
        </view>

        <view class="btnBox">
            <view class="saveBtn" @click="handleSaveChange">保存修改</view>
            <view class="loginOut" @click="handleGoLoginOut">退出登录</view>
        </view>
    </view>
</template>

<script>
import { mapGetters } from "vuex";
export default {
    data() {
        return {
            userInfo: {},// 用户信息
            editableNickname: '', // 可编辑的昵称
            genderArray: ['男', '女'], // 性别选项
            genderIndex: 0, // 选中的性别索引
            birthday: '',
            email: '', // 邮箱地址
            realName: "",
            idCard: '', // 证件号码
            WXProfile: '', // 微信头像
            emailError: false, // 判断邮箱校验是否通过
            idCardError: false, // 判断身份证号校验是否通过

            autoFocus: false
        }
    },
    computed: {
        ...mapGetters({
            user: "user",
        }),
        phone() {
            if (this.user.MEMBERSHIP_MOBILEPHONE) {
                let a = this.user.MEMBERSHIP_MOBILEPHONE.substring(0, 3);
                let b = this.user.MEMBERSHIP_MOBILEPHONE.substring(7, 11);
                return a + "****" + b;
            } else {
                return "";
            }
        },
    },
    onLoad() {
        // 拿用户信息
        this.handleGetUserDetail();

        this.$utils.addUserBehaviorNew({
            behaviorRecordDesc: "进入用户设置"
        });
    },
    onShow() {
        // // 拿用户信息
        // this.handleGetUserDetail();
        // // 拿到用户新的信息
        // this.handleGetUserNewInfo();
    },
    methods: {
        moveCursorToEnd(type) {
            // 1. 先解除聚焦状态
            this.isFocused = false;
            // 2. 在下个渲染周期重新聚焦
            this.$nextTick(() => {
                this.isFocused = true;
                // 3. 强制重置输入框内容（关键步骤）
                this.$nextTick(() => {
                    let val = ""
                    if (type === 1) {
                        val = this.editableNickname;
                        this.editableNickname = val + ' ';
                    } else if (type === 2) {
                        val = this.email;
                        this.email = val + ' ';
                    } else if (type === 3) {
                        val = this.realName;
                        this.realName = val + ' ';
                    } else if (type === 4) {
                        val = this.idCard;
                        this.idCard = val + ' ';
                    }
                    // const val = this.editableNickname;
                    // this.editableNickname = val + ' '; // 添加空格
                    this.$nextTick(() => {
                        if (type === 1) {
                            this.editableNickname = val.trim(); // 移除空格
                        } else if (type === 2) {
                            this.email = val.trim(); // 移除空格
                        } else if (type === 3) {
                            this.realName = val.trim(); // 移除空格
                        } else if (type === 4) {
                            this.idCard = val.trim(); // 移除空格
                        }
                    });
                });
            });
        },
        // 性别选择改变
        bindGenderChange(e) {
            this.genderIndex = e.detail.value
        },
        // 生日多列选择器值改变
        bindMultiPickerChange(e) {
            console.log('eee', e);
            this.birthday = e.detail.value;
        },
        // 跳转到个人中心
        handleGoUserInfoCenter() {
            uni.navigateTo({
                url:
                    "/pages/useConfig/userInfo"
            });
        },
        // 拿到新的用户信息
        async handleGetUserNewInfo() {
            const userInfoData = await this.$api.$post(
                "/WeChat/GetMembershipInfoById",
                {
                    type: 'encryption'
                }
            );
            console.log('userInfoData', userInfoData);
            if (userInfoData.Result_Code === 100) {
                this.newUserInfo = userInfoData.Result_Data;
                console.log('this.newUserInfo', this.newUserInfo);



                this.editableNickname = this.newUserInfo.Membership_NickName || '';
                this.genderIndex = this.newUserInfo.Membership_Sex === 1 ? 0 : 1; // 男性为0，女性为1
                this.multiIndex = [
                    new Date(this.newUserInfo.Membership_Birthday).getMonth(),
                    new Date(this.newUserInfo.Membership_Birthday).getDate() - 1
                ]; // 月份和日期索引
                console.log('this.multiIndex', this.multiIndex);
                const date = new Date(this.newUserInfo.Membership_Birthday);
                this.birthday = `${date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1}-${date.getDate() < 10 ? '0' + date.getDate() : date.getDate()}`; // 格式化为 MM-DD

                this.idNumber = this.newUserInfo.Certificate_Number
                this.email = this.newUserInfo.Membership_Email
            }
        },
        // 收藏的商品
        handleGoFavoriteStore() {
            uni.navigateTo({
                url:
                    "/pages/useConfig/FavoriteStore"
            });
        },
        // 退出登录
        handleGoLoginOut() {
            let _this = this
            uni.showModal({
                content: '确定退出登录？',
                success: function (res) {
                    if (res.confirm) {
                        uni.clearStorageSync();
                        _this.$store.commit('RESET_ALL_STATE')

                        // 3. 重置微信登录状态（关键步骤）
                        if (uni.getStorageSync('hasRequestUserInfo')) {
                            uni.removeStorageSync('hasRequestUserInfo');
                        }

                        setTimeout(() => {
                            try {
                                // 尝试使用reLaunch完全重启应用
                                uni.reLaunch({
                                    url: '/pages/index/index'
                                })
                            } catch (e) {
                                // 如果reLaunch失败，则使用switchTab
                                uni.switchTab({
                                    url: '/pages/index/index'
                                })
                            }
                        }, 100);
                    } else if (res.cancel) {
                    }
                }
            });
        },
        // 点击跳转地址管理
        handleGoAddress() {
            uni.navigateTo({
                url:
                    "/pages/myAddress/address/index"
            });
        },
        // 打开隐私协议
        handleShowPrivacy() {
            wx.openPrivacyContract()
        },
        // 拿到用户详情
        async handleGetUserDetail() {
            const userData = await this.$api.getCoop({
                action_type: "GetMembershipInfo",
                WechatUserId: this.user.WechatUserId,
            });
            this.userInfo = userData.Data;
            console.log('userDatauserDatauserData', userData.Data);


            uni.setStorageSync("userData", userData.Data);

            this.editableNickname = this.userInfo.NICK_NAME // 昵称
            this.genderIndex = this.userInfo.MEMBERSHIP_SEX // 性别
            this.birthday = this.userInfo.MEMBERSHIP_BIRTHDAY ? this.$utils.formatDate(this.userInfo.MEMBERSHIP_BIRTHDAY) : "-" // 生日
            this.email = this.userInfo.MEMBERSHIP_EMAIL // 邮箱地址
            this.validateEmail()
            let _data = userData;
            let _this = this
            _this.user.MEMBERSHIP_ID = _data.Data.MEMBERSHIP_ID || "";
            _this.user.MEMBERSHIP_NAME = _data.Data.MEMBERSHIP_NAME || "";
            _this.user.MEMBERSHIP_LEVEL_TEXT =
                _data.Data.MEMBERSHIP_LEVEL_TEXT || "";
            _this.user.COUPON_COUNT = _data.Data.COUPON_COUNT || "";
            _this.user.PENDORDER_COUNT = _data.Data.PENDORDER_COUNT || "";
            _this.user.RESERVATION_COUNT = _data.Data.RESERVATION_COUNT || "";
            _this.user.ACCOUNT_BALANCE = _data.Data.ACCOUNT_BALANCE || "";
            _this.user.ISPLUS = _data.Data.ISPLUS || "";
            _this.user.INDUSTRY_MEMBERSHIP_ID =
                _data.Data.INDUSTRY_MEMBERSHIP_ID || "";
            _this.user.MEMBERSHIP_TYPE = _data.Data.MEMBERSHIP_TYPE || "";
            _this.user.MEMBERSHIP_LEVEL = _data.Data.MEMBERSHIP_LEVEL || "";
            _this.user.InviteCode = _data.Data.InviteCode || "";
            _this.user.MEMBERSHIP_POINT = _data.Data.MEMBERSHIP_POINT || "";
            _this.user.MEMBERSHIP_MOBILEPHONE =
                _data.Data.MEMBERSHIP_MOBILEPHONE || "";
            _this.WXProfile = _data.Data.MEMBERSHIP_HEADIMAGEURL;
            _this.user.TEST_MEMBER = _data.Data.TEST_MEMBER || "";
            // _this.setUser(user);
            _this.$store.commit("setUser", _this.user);

            if (_data.Data.MEMBERSHIP_HEADIMAGEURL) {
                _this.displayedAvatarUrl = _data.Data.MEMBERSHIP_HEADIMAGEURL + '?t=' + Date.now();
            } else {
                _this.displayedAvatarUrl = ''; // 或者设置为默认头像 URL
            }
            _this.$forceUpdate()
            _this.realName = _this.userInfo.MEMBERSHIP_NAME // 真实姓名
            _this.idCard = _this.userInfo.CERTIFICATE_NUMBER
            _this.validateIdCard()

            this.$forceUpdate();
            console.log("this.userInfo", JSON.parse(JSON.stringify(this.userInfo)));
        },
        // 用户上传头像
        async onChooseAvatar(e) {
            let _this = this;
            uni.uploadFile({
                url: "https://api.eshangtech.com/EShangApiMain/Picture/UploadPicture", // 你的接口 URL
                filePath: e.detail.avatarUrl,
                name: "file", // 表单中的文件字段名
                formData: {
                    Tabletype: "1005", // 表单中其他数据
                },
                success: async (uploadRes) => {
                    let data = uploadRes.data ? JSON.parse(uploadRes.data) : "";
                    let url = data.Result_Data.ImageUrl;
                    if (url) {
                        let req = {
                            membershipId: this.user.MEMBERSHIP_ID,
                            headImgUrl: url,
                        };
                        _this.WXProfile = url;
                        const userInfoData = await _this.$api.$get(
                            "/WeChat/UpdateMemberInfo",
                            req
                        );
                        if (userInfoData.Result_Code === 100) {
                            _this.handleGetUserDetail();
                        }
                    }
                },
            });
        },
        validateIdCard() {
            // 简单的中国大陆身份证号校验（18位或15位）
            const idCardPattern = /^(^[1-9]\d{5}(18|19|20)?\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$)|(^[1-9]\d{7}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}$)$/;
            if (this.idCard && idCardPattern.test(this.idCard)) {
                this.idCardError = true
            } else {
                this.idCardError = false
            }
        },
        validateEmail() {
            // 简单邮箱正则
            const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
            if (this.email && emailPattern.test(this.email)) {
                this.emailError = true
            } else {
                this.emailError = false
            }
        },
        // 保存信息修改
        async handleSaveChange() {
            console.log('this.emailthis.email', this.email);

            if (!this.emailError && this.email) {
                uni.showToast({
                    title: '邮箱地址错误！',
                    icon: 'none'
                });
                return;
            }
            if (!this.idCardError && this.idCard) {
                uni.showToast({
                    title: '身份证号错误！',
                    icon: 'none'
                });
                return;
            }
            // 进行保存操作
            const req = {
                Membership_NickName: this.editableNickname,
                Membership_Sex: this.genderArray[this.genderIndex] === '男' ? 0 : 1,
                Membership_Birthday: this.birthday,
                // Certificate_Number: this.idNumber,
                Membership_Email: this.email,
                Membership_Name: this.realName,
                CERTIFICATE_NUMBER: this.idCard,
                type: 'encryption1'
            }
            console.log('reqreqreqreq', req);

            const userInfoData = await this.$api.$post(
                "/WeChat/ModifyMemberInfo",
                req
            );

            console.log('userInfoData', userInfoData);
            if (userInfoData.Result_Code === 100) {

                let userData = uni.getStorageSync('userData')
                console.log('userDatauserDatauserData', userData);

                if (userData) {
                    uni.setStorageSync("userData", {
                        ...userData,
                        ...req
                    });
                }
                uni.showToast({
                    title: '修改成功',
                    icon: 'success',
                    duration: 2000
                });
            } else {
                uni.showToast({
                    title: '修改失败，请稍后再试',
                    icon: 'none',
                    duration: 2000
                });
            }
        },
    }
}
</script>

<style lang="less" scoped>
.main {
    width: 100vw;
    min-height: 100vh;
    box-sizing: border-box;
    background-color: #F5F5F5;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);

    .userInfoBox {
        width: 100%;
        height: 164rpx;
        box-sizing: border-box;
        padding: 28rpx 30rpx 28rpx 34rpx;
        background-color: #fff;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .userInfoBoxLeft {
            width: calc(100% - 32rpx);
            display: flex;
            align-items: center;

            .userInfoHeaderImg {
                width: 108rpx;
                height: 108rpx;
                margin-right: 30rpx;

                .headerImg {
                    width: 100%;
                    height: 100%;
                    border-radius: 50%;
                }
            }

            .userInfoMessage {
                width: calc(100% - 138rpx);

                .userInfoName {
                    width: 100%;
                    font-family: PingFangSC, PingFang SC;
                    font-weight: 600;
                    font-size: 40rpx;
                    color: rgba(0, 0, 0, 0.85);
                    line-height: 56rpx;
                    text-align: left;
                    font-style: normal;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .mainTopMessageUserLevelBox {
                    display: inline-flex;
                    align-items: center;
                    background-color: #515050;
                    padding: 4rpx 18rpx;
                    border-radius: 32rpx;
                    margin-top: 18rpx;

                    .mainTopMessageUserLevelIcon {
                        width: 24rpx;
                        height: 24rpx;
                        margin-right: 10rpx;
                    }

                    .mainTopMessageUserLevelText {
                        font-family: PingFangSC, PingFang SC;
                        font-weight: 500;
                        font-size: 24rpx;
                        color: #F4DA7F;
                        line-height: 34rpx;
                        text-align: left;
                        font-style: normal;
                        text-transform: none;
                        display: inline-block;
                    }
                }
            }
        }

        .userInfoBoxRight {
            width: 32rpx;

            .rightArrow {
                width: 32rpx;
                height: 32rpx;
            }
        }
    }


    .userInfoContent {
        width: 100%;
        box-sizing: border-box;
        padding: 0 30rpx;
        background-color: #fff;
        margin-top: 18rpx;

        .userInfoItem {
            width: 100%;
            padding: 32rpx 0;
            border-bottom: 2rpx solid #F5F5F5;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .userInfoItemLabel {
                width: calc(100% / 3);
                font-family: PingFang-SC, PingFang-SC;
                font-weight: 500;
                font-size: 24rpx;
                color: #333333;
                line-height: 40rpx;
                text-align: left;
                font-style: normal;
                text-transform: none;
            }

            .userInfoItemRight {
                width: calc(100% / 3 * 2);
                display: flex;
                justify-content: flex-end;

                .rightArrow {
                    width: 32rpx;
                    height: 32rpx;
                }

                .rightText {
                    font-family: PingFang-SC, PingFang-SC;
                    font-weight: 500;
                    font-size: 24rpx;
                    color: #999999;
                    line-height: 40rpx;
                    text-align: left;
                    font-style: normal;
                    text-transform: none;
                }

                .phoneBox {
                    width: 100%;
                    font-size: 24rpx;
                    color: #a1a1a1;
                    text-align: right;
                }

                .headerImgBox {
                    width: 64rpx;
                    height: 64rpx;

                    .avatarBtn {
                        width: 64rpx;
                        height: 64rpx;
                        border-radius: 50%;
                        border: 1px solid #fff;
                        padding: 0 !important;

                        .headerImg {
                            width: 100%;
                            height: 100%;

                        }
                    }
                }
            }
        }
    }



    .contentBox {
        width: 100%;
        background-color: #fff;
        box-sizing: border-box;
        padding: 0 32rpx;
        margin-top: 16rpx;

        .contentItem {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 32rpx 0;
            border-bottom: 2px solid #F5F5F5;

            .itemLeft {
                width: 40%;
                font-size: 28rpx;
            }

            .itemRight {
                width: 60%;

                .rightImgBox {
                    display: flex;
                    justify-content: flex-end;

                    .avatarBtn {
                        width: 104rpx;
                        height: 104rpx;
                        padding: 0;
                        border-radius: 50%;
                        margin: 0;

                        .headerImg {
                            width: 100%;
                            height: 100%;
                            border-radius: 50%;
                        }
                    }
                }

                .rightGoBox {
                    display: flex;
                    align-items: center;
                    justify-content: flex-end;

                    .goText {
                        font-size: 24rpx;
                        color: #a1a1a1;
                    }

                    .goIcon {
                        width: 26rpx;
                        height: 26rpx;
                        margin-left: 8rpx;
                    }
                }

                .phoneBox {
                    font-size: 24rpx;
                    color: #a1a1a1;
                    text-align: right;
                }


            }
        }
    }

    .btnBox {
        width: 100%;
        box-sizing: border-box;
        padding: 0 32rpx;
        margin-top: 32rpx;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .saveBtn {
            width: calc(50% - 16rpx);
            border-radius: 48rpx;
            background-color: #07C160;
            font-weight: 400;
            font-size: 32rpx;
            color: #FFFFFF;
            text-align: center;
            font-style: normal;
            padding: 24rpx 0;
        }

        .loginOut {
            width: calc(50% - 16rpx);
            border-radius: 48rpx;
            font-weight: 400;
            font-size: 32rpx;
            color: #07C160;
            text-align: center;
            font-style: normal;
            padding: 24rpx 0;
            border: 1px solid #07C160;
            box-sizing: border-box;
        }
    }
}
</style>
