<template>
    <uv-popup
        ref="popup"
        class="update-popup"
        :class="[`${themeInfo.theme}-theme`]"
        custom-style="width: 90%; border-radius: 16rpx;"
    >
        <view class="update-wrap">
            <view class="auth-btn" @click="wxGetUserProfile">{{ $t("login.wxLogin") }}</view>
        </view>
    </uv-popup>

    <uv-popup
        ref="phonePopup"
        customStyle="width: 80%; height: 400rpx; padding:20rpx 0; border-radius: 32rpx; display: flex; flex-direction: column; justify-content: center; align-items: center;"
        @change="popupChange"
    >
        <text>{{ $t("common.bindPhone") }}</text>
        <text style="padding: 0 40rpx; margin-top: 20rpx; text-align: center;"> {{ $t("common.bindPhoneAfter") }}</text>
        <button
            style="width: 80%; margin-top: 20px; background: #5BBC6B; color: #FFFFFF; line-height: 80rpx;"
            open-type="getPhoneNumber"
            @getphonenumber="getPhoneNumber"
        >
            {{ $t("common.QuickBind") }}
        </button>
    </uv-popup>
</template>

<script setup>
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useMainStore } from "@/store/index.js";
import { projectInfo } from "@/config/index.js";
const { themeInfo, getUserInfo, storeState } = useMainStore();

import { useLoginApi } from "@/Apis/login.js";
const getApi = useLoginApi();

const popup = ref(null);
const phonePopup = ref(null);

const props = defineProps({
    name: {
        type: String,
        default: "",
    },
});

const open = () => {
    popup.value.open();
};
defineExpose({ open });

const code = ref("");
const encryptedData = ref("");
const iv = ref("");
const wxLogin = () => {
    // 微信 登陆授权 code
    return new Promise(function (reslove, reject) {
        wx.login({
            success(res) {
                code.value = res.code;
                reslove(res.code);
            },
            fail: (err) => {
                reject(err);
                console.error("wx.login调用失败：", err);
            },
        });
    });
};
const AuthorizedLogin = (data) => {
    uni.showLoading();
    getApi.AuthorizedLogin(data).then(async (res) => {
        uni.hideLoading();
        if (res.code == 200) {
            storeState.token = res.data.token;
            uni.setStorageSync("token", res.data.token);
            uni.setStorageSync("openId", res.data.openId);
            uni.removeStorage({
             key:'Pre_ID'   
            })
            uni.removeStorage({
             key:'mediatorId'   
            })
            const { data: userInfo } = await getUserInfo();
            if (!userInfo.phone) {
                phonePopup.value.open();
            }
            popup.value.close();
        }
    });
};
const wxGetUserProfile = async () => {
    uni.showLoading();
    wx.getUserProfile({
        desc: "用于完善会员资料", // 获取用户信息的提示语
        success: async (res) => {
            encryptedData.value = res.encryptedData;
            iv.value = res.iv;
            // 微信 登陆授权 code
            uni.checkSession({
                success: (res) => {
                    // 发起网络请求
                    AuthorizedLogin({
                        code: code.value,
                        encryptedData: encryptedData.value,
                        iv: iv.value,
                        openId: uni.getStorageSync("openId"),
                        Pre_ID: uni.getStorageSync("Pre_ID"),
                        mediatorId: uni.getStorageSync('mediatorId')
                    });
                },
                fail: (err) => {
                    wxLogin().then((res) => {
                        AuthorizedLogin({
                            code: code.value,
                            encryptedData: encryptedData.value,
                            iv: iv.value,
                            openId: uni.getStorageSync("openId"),
                            Pre_ID: uni.getStorageSync("Pre_ID"),
                            mediatorId: uni.getStorageSync('mediatorId')
                        });
                    });
                },
            });
        },
        fail: (err) => {
            uni.hideLoading();
            console.error("获取用户信息失败：", err);
        },
    });
}

const getPhoneNumber = async (e) => {
    uni.showLoading();
    if (e.detail.code) {
        getApi.GetPhoneNumber({code:e.detail.code}).then((res) => {
            if (res.code == 200) {
                uni.hideLoading();
                phonePopup.value.close();
            }
        });
    } else {
        uni.hideLoading();
        uni.showToast({
            title: "获取手机号失败",
            icon: "none",
            duration: 2000,
        });
    }
}

onLoad(() => {
    if (uni.getAppBaseInfo().hostName === "WeChat") {
        wxLogin();
    }
});
</script>

<style lang="scss" scoped>
.update-wrap {
    overflow: hidden;
    background: #ffffff;

    .title-wrap {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 120rpx;
        background: #f7f7f7;

        .title {
            display: flex;
            position: relative;
            color: #242e42;
            z-index: 2;

            &::after {
                content: "";
                position: absolute;
                bottom: 2px;
                left: -10px;
                width: calc(100% + 20px);
                height: 6px;
                border-radius: 4px;
                background: var(--main-color);
                z-index: -1;
            }
        }
    }

    .content {
        padding: 50rpx 40rpx 10rpx;

        .text {
            color: #292927;
            margin-bottom: 40rpx;
        }
    }

    .auth-btn {
        margin: 0 40rpx 60rpx;
        padding: 20rpx 0;
        text-align: center;
        border-radius: 10rpx;
        letter-spacing: 2px;
        background: var(--main-color);
    }
}
</style>
