<template>
    <view class="main">
        <view class="contentBox">
            <view class="contentItem">
                <view class="itemLeft">头像</view>
                <view class="itemRight">
                    <view class="rightImgBox">
                        <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="contentItem">
                <view class="itemLeft">昵称</view>
                <view class="itemRight">
                    <!-- <view class="phoneBox">
                        {{ userInfo.MEMBERSHIP_NAME }}
                    </view> -->
                    <input class="phoneBox" v-model="editableNickname" placeholder="请输入昵称" />
                </view>
            </view>

            <!-- 添加性别选择 -->
            <view class="contentItem">
                <view class="itemLeft">性别</view>
                <view class="itemRight">
                    <picker @change="bindGenderChange" :value="genderIndex" :range="genderArray">
                        <view class="phoneBox">{{ genderArray[genderIndex] }}</view>
                    </picker>
                </view>
            </view>

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

            <!-- 添加证件号码输入 -->
            <view class="contentItem">
                <view class="itemLeft">证件号码</view>
                <view class="itemRight">
                    <input class="phoneBox" v-model="idNumber" placeholder="请输入证件号码" />
                </view>
            </view>

            <!-- 添加邮箱地址输入 -->
            <view class="contentItem">
                <view class="itemLeft">邮箱地址</view>
                <view class="itemRight">
                    <input class="phoneBox" v-model="email" placeholder="请输入邮箱地址" type="text" />
                </view>
            </view>


            <view class="contentItem">
                <view class="itemLeft">手机号码</view>
                <view class="itemRight">
                    <view class="phoneBox">
                        {{ phone }}
                    </view>
                </view>
            </view>

            <view class="contentItem" @click="handleChangePhone">
                <view class="itemLeft">切换账号</view>
                <view class="itemRight">
                    <view class="rightGoBox">
                        <text class="goText">点击切换</text>
                        <image class="goIcon" src="/static/images/home/rightArrow.svg" />
                    </view>
                </view>
            </view>

            <view class="contentItem" @click="handleGoAddress">
                <view class="itemLeft">地址管理</view>
                <view class="itemRight">
                    <view class="rightGoBox">
                        <text class="goText">点击跳转</text>
                        <image class="goIcon" src="/static/images/home/rightArrow.svg" />
                    </view>
                </view>
            </view>

            <view class="contentItem" @click="handleGoFavoriteStore">
                <view class="itemLeft">我的收藏</view>
                <view class="itemRight">
                    <view class="rightGoBox">
                        <text class="goText">点击跳转</text>
                        <image class="goIcon" src="/static/images/home/rightArrow.svg" />
                    </view>
                </view>
            </view>

            <view class="contentItem" style="border-bottom: 0px;" @click="handleShowPrivacy">
                <view class="itemLeft">隐私协议</view>
                <view class="itemRight">
                    <view class="rightGoBox">
                        <text class="goText">点击查看</text>
                        <image class="goIcon" src="/static/images/home/rightArrow.svg" />
                    </view>
                </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 {
            userInfo: {},// 用户信息
            editableNickname: '', // 可编辑的昵称
            genderArray: ['男', '女'], // 性别选项
            genderIndex: 0, // 选中的性别索引
            multiArray: [['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'], Array.from({ length: 31 }, (_, i) => `${i + 1}日`)], // 多列选择器的数据
            multiIndex: [0, 0], // 多列选择器的选中索引
            birthday: '',
            idNumber: '', // 证件号码
            email: '', // 邮箱地址
            WXProfile: '', // 微信头像
            newUserInfo: {}, // 新的用户信息
        }
    },
    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.handleGetUserNewInfo();
    },
    methods: {
        // 保存修改
        async handleSaveChange() {
            console.log('昵称', this.editableNickname);
            console.log('性别', this.genderArray[this.genderIndex]);
            console.log('生日', this.birthday);
            console.log('证件号码', this.idNumber);
            console.log('邮箱地址', this.email);

            const req = {
                Membership_NickName: this.editableNickname,
                Membership_Sex: this.genderArray[this.genderIndex] === '男' ? 1 : 2,
                Membership_Birthday: this.birthday,
                Certificate_Number: this.idNumber,
                Membership_Email: this.email,
                type: 'encryption'
            }
            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
                });
                // 更新用户信息
                this.handleGetUserNewInfo();
            } else {
                uni.showToast({
                    title: '修改失败，请稍后再试',
                    icon: 'none',
                    duration: 2000
                });
            }
        },
        // 拿到新的用户信息
        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
            }
        },
        // 性别选择改变
        bindGenderChange(e) {
            this.genderIndex = e.detail.value
        },
        // 生日多列选择器列改变
        bindMultiPickerColumnChange(e) {
            const data = [...this.multiArray]; // 复制 multiArray
            const multiIndex = [...this.multiIndex]; // 复制 multiIndex
            multiIndex[e.detail.column] = e.detail.value;

            if (e.detail.column === 0) { // 月份列改变
                const month = e.detail.value + 1; // 月份是 1-based
                let daysInMonth = 31;
                if (month === 4 || month === 6 || month === 9 || month === 11) {
                    daysInMonth = 30;
                } else if (month === 2) {
                    // 简化处理，不考虑闰年，二月按 28 天计算
                    daysInMonth = 28;
                }
                // 生成新的天数数组
                const daysArray = Array.from({ length: daysInMonth }, (_, i) => `${i + 1}日`);
                data[1] = daysArray; // 更新天数数组

                // 如果之前选择的天数索引超出新月份的天数范围，则重置天数索引
                if (multiIndex[1] >= daysInMonth) {
                    multiIndex[1] = daysInMonth - 1;
                }
            }

            // 更新数据和索引
            this.multiArray = data;
            this.multiIndex = multiIndex;
        },
        // 生日多列选择器值改变
        bindMultiPickerChange(e) {
            this.multiIndex = e.detail.value;
            const month = this.multiIndex[0] + 1;
            const day = this.multiIndex[1] + 1;
            // 格式化为 MM-DD 字符串，不足两位前补零
            const formattedMonth = month < 10 ? '0' + month : month;
            const formattedDay = day < 10 ? '0' + day : day;
            this.birthday = `${formattedMonth}-${formattedDay}`;
        },
        // 收藏的商品
        handleGoFavoriteStore() {
            uni.navigateTo({
                url:
                    "/pages/useConfig/FavoriteStore"
            });
        },
        // 切换账号
        handleChangePhone() {
            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) {
                    }
                }
            });
        },
        // 退出登录
        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) {
                    }
                }
            });
        },
        // 点击跳转地址管理
        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;
            this.$forceUpdate();
            console.log("this.userInfo", 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();
                        }
                    }
                },
            });
        },
    }
}
</script>

<style lang="less" scoped>
.main {
    width: 100vw;
    min-height: 100vh;
    box-sizing: border-box;
    background-color: #F5F5F5;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);

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

        .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>
