<style lang="scss">
    /* 注意要写在第一行，同时给style标签加入lang="scss"属性 */
    @import "uview-ui/index.scss";
</style>
<script>
    export default {
        onLaunch: function () {
            console.log('App Launch')
        },
        onShow: function () {
            console.log('App Show 小程序显示了+++++++++++++++++++++++')
            let that = this;

            // 检查是否已登录（有 accessToken）
            const accessToken = uni.getStorageSync('accessToken')

            if (accessToken) {
                // 已登录，直接使用本地数据执行拓客逻辑，不再调用 wxLogin
                console.log('++++++++++已登录用户，直接使用本地数据执行拓客逻辑++++++++++')
                that.handleShareBind()
                that.handleExpandLogic()
                return
            }

            // 未登录，走静默登录
            wx.login({
                success(re) {
                    that.$api.wxLogin({code: re.code}).then(res => {
                        console.log('++++++++++登录返回了++++++++++++++++', res)
                        uni.setStorageSync('userInfo', res.data.data.userInfo)
                        uni.setStorageSync('accessToken', res.data.data.access_token)
                        uni.setStorageSync('phoneIsBind', res.data.data.phoneIsBind)
                        uni.setStorageSync('wxLoginIsNew', res.data.data.isNew)
                        let isNew = res.data.data.isNew
                        uni.removeStorageSync('parent_member_id');

                        that.handleShareBind(res.data.data.userInfo.otherId)
                        that.handleExpandLogic(isNew)

                    }).catch(err => {
                        console.log('++++++++++App.vue wxLogin 失败++++++++++++++++')
                        console.log('err.data:', err.data)
                        console.log('err.statusCode:', err.statusCode)
                        console.log('err.header:', err.header)
                    })
                },
            })


        },
        methods: {
            // 处理用户分享绑定
            handleShareBind(openId) {
                let shareUserId = uni.getStorageSync('shareUserId')
                if (!shareUserId) return

                let userInfo = uni.getStorageSync('userInfo')
                let targetOpenId = openId || (userInfo && userInfo.otherId)
                if (!targetOpenId) return

                this.$api.scanCode({
                    openId: targetOpenId,
                    memberId: shareUserId
                }).then(res => {
                    console.log('用户分享用户绑定成功', res)
                    uni.removeStorageSync('shareUserId');
                })
            },
            // 处理拓客端扫码逻辑
            // isNew: 是否新用户（true=新用户弹窗领券，false=老用户记录推广失败）
            handleExpandLogic(isNew) {
                let expandParam = uni.getStorageSync('expandParam')
                if (!expandParam) return

                // 使用传入的参数或本地缓存
                let _isNew = isNew !== undefined ? isNew : uni.getStorageSync('wxLoginIsNew')

                if (expandParam.isUse != 1){
                    console.log('获取到的拓客端参数',expandParam)
                    if (new Date().getTime() <= expandParam.timestamp){
                        if (_isNew){
                            //登录成功，且是新用户，触发首页的自定义事件（弹出新人专享窗口）
                            uni.$emit("loginSuccess")
                            // 标记为已使用，避免重复处理
                            expandParam.isUse = 1
                            uni.setStorageSync('expandParam', expandParam)
                        }else {

                            this.$api.addRecordForAttach({
                                ...expandParam,
                                isNew:0,
                                isBindSuccess:0,
                            }).then(res=>{
                                expandParam.isUse = 1
                                uni.setStorageSync('expandParam', expandParam)
                                console.log('+++++++++老用户，扫码推广失败记录！++++++++++++++++')
                            })

                            // uni.removeStorageSync('expandParam');
                        }

                    }else {
                        uni.showModal({
                            title: '温馨提示',
                            content: ' 当前二维码已过期，请重新扫码',
                            showCancel:false,
                            success: function (res) {
                                if (res.confirm) {
                                    console.log('用户点击确定');
                                } else if (res.cancel) {
                                    console.log('用户点击取消');
                                }
                            }
                        });
                        expandParam.isUse = 1
                        uni.setStorageSync('expandParam', expandParam)
                        // uni.removeStorageSync('expandParam');
                    }
                }
            }
        },
        onHide: function () {
            console.log('App Hide')
        }
    }
</script>


