<template>
    <view class="main">
        <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">
                <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="请输入昵称" />

                </view>
            </view>

            <view class="userInfoItem">
                <view class="userInfoItemLabel">性别</view>
                <view class="userInfoItemRight">
                    <picker @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 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">
                <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">
                <view class="userInfoItemLabel">真实姓名</view>
                <view class="userInfoItemRight">
                    <input class="phoneBox" v-model="realName" placeholder="请输入真实姓名" />
                </view>
            </view>

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

        <view class="btnBox">
            <view class="saveBtn" style="margin-bottom: 24rpx;" @click="handleSaveChange">保存修改</view>
            <view class="loginOut" @click="handleGoLoginOut">退出登录</view>
        </view>
    </view>
</template>

<script>
import { mapGetters } from "vuex";
export default {
    data() {
        return {
            editableNickname: "",// 昵称
            genderArray: ['男', '女'], // 性别选项
            genderIndex: 0, // 选中的性别索引
            birthday: '',
            email: '', // 邮箱地址
            realName: "",
            idCard: "",
            userInfo: {},
            emailError: false, // 判断邮箱校验是否通过
            idCardError: false, // 判断身份证号校验是否通过
        }
    },
    computed: {
        ...mapGetters({
            user: "user",
        }),
    },
    async onLoad() {
        await this.handleGetUserDetail()
    },
    methods: {
        // 退出登录
        handleGoLoginOut() {
            let _this = this
            uni.showModal({
                content: '确定退出登录？',
                success: function (res) {
                    if (res.confirm) {
                        uni.clearStorageSync()
                        _this.$store.commit('RESET_ALL_STATE')
                        setTimeout(() => {
                            try {
                                // 尝试使用reLaunch完全重启应用
                                uni.reLaunch({
                                    url: '/pages/index/index'
                                })
                            } catch (e) {
                                // 如果reLaunch失败，则使用switchTab
                                uni.switchTab({
                                    url: '/pages/index/index'
                                })
                            }
                        }, 100);
                    } else if (res.cancel) {
                    }
                }
            });
        },
        // 保存信息修改
        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) {
                uni.showToast({
                    title: '修改成功',
                    icon: 'success',
                    duration: 2000
                });
                setTimeout(() => {
                    uni.navigateBack({
                        delta: 1 // 返回上一页
                    });
                }, 1000);
            } else {
                uni.showToast({
                    title: '修改失败，请稍后再试',
                    icon: 'none',
                    duration: 2000
                });
            }
        },
        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
            }
        },
        // 性别选择改变
        bindGenderChange(e) {
            this.genderIndex = e.detail.value
        },
        // 生日多列选择器值改变
        bindMultiPickerChange(e) {
            console.log('eee', e);
            this.birthday = e.detail.value;
        },
        // 用户上传头像
        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();
                        }
                    }
                },
            });
        },
        // 拿到用户详情
        async handleGetUserDetail() {
            const userData = await this.$api.getCoop({
                action_type: "GetMembershipInfo",
                WechatUserId: this.user.WechatUserId,
            });
            this.userInfo = userData.Data;
            this.editableNickname = this.userInfo.NICK_NAME // 昵称
            this.genderIndex = this.userInfo.MEMBERSHIP_SEX // 性别
            this.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.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)));
        },
    }
}
</script>
<style lang="less" scoped>
.main {
    width: 100vw;
    height: 100vh;
    background-color: #F5F5F5;
    position: relative;

    .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 {
                font-family: PingFang-SC, PingFang-SC;
                font-weight: 500;
                font-size: 28rpx;
                color: #333333;
                line-height: 40rpx;
                text-align: left;
                font-style: normal;
                text-transform: none;
            }

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

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

                .phoneBox {
                    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%;

                        }
                    }
                }
            }
        }
    }

    .btnBox {
        width: 100%;
        box-sizing: border-box;
        padding: 0 32rpx;
        position: absolute;
        bottom: 60rpx;

        .saveBtn {
            width: 100%;
            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: 100%;
            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>