<template>
    <view class="wrapper">
        <!-- 获取用户信息 -->
        <view v-if="showUserInfo" class="ttt">
            <button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
                <image class="avatar" :src="avatarUrl"></image>
            </button> 
            <view class="tipUserHeader">设置头像</view>
            <input class="weui-input" v-model="userName" placeholder="请输入昵称"/>
            <button type="primary" :disabled="disabledSubmit" @click="handleSubmit" class="submit">提交</button>
        </view>
        <button @click="handleUserDestory"> 用户注销  </button>
        <view class="shadow">
        </view>

        <view class="section" >
            <view class="shadowBoard" :style="{backgroundImage:'url('+ photo[i] +')'}"></view>
            <view class="swiper">
                <z-swiper v-model="list" ref="swiper" @slideChange="onSlideChange" :options="options" class="swiper">
                    <z-swiper-item :custom-style="slideCustomStyle" v-for="(item,index) in list" :key="index">
                        <button class="btn" @click="NavTo(index)">
                            <image class="image" :src="item.image" mode="aspectFill"></image>
                            <view class="CardContent">
                                <view class="card">
                                    <view class="header1">{{item.title}}</view>
                                    <view class="header2">
                                        <view class="sdsd">{{item.content1}}</view>
                                        <view class="distence"></view>
                                        <view class="detail">{{item.content2}}</view>
                                    </view>
                                </view>
                            </view>
                        </button>
                    </z-swiper-item>
                </z-swiper>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            err:null,
            disabledSubmit:false,
            id:274,
            showUserInfo:false,
            userName:'',
            avatarUrl: 'https://admin.mindepoch.com:8089/static/poster1.png',
            // avatarUrl:'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
            code:'',
            clickNoArgee:false,
            clickArgee:false,
            isBindPhone:false,
            needDialog:true,
            nickName:'',
            // avatarUrl:'',
            OpenId:'',
            i:0,
            photo:[
                'https://admin.mindepoch.com:8089/worlds/情圣日记.png',
                'https://admin.mindepoch.com:8089/worlds/荒村公寓.png',
                'https://admin.mindepoch.com:8089/worlds/舌战群儒.png'
            ],
            list: [
                {image:'https://admin.mindepoch.com:8089/worlds/情圣日记.png',title:'情圣日记',content1:'-Love&Entropy',content2:'你还...记得我吗？'},
                {image:'https://admin.mindepoch.com:8089/worlds/荒村公寓.png',title:'荒村公寓',content1:'-规则怪谈',content2:'一觉醒来，身处陌生的公寓,奇怪的规则，神秘的怪谈,我该如何逃生'},
                {image:'https://admin.mindepoch.com:8089/worlds/舌战群儒.png',title:'荒村公寓',content1:'-规则怪谈',content2:'一觉醒来，身处陌生的公寓,奇怪的规则，神秘的怪谈,我该如何逃生'},
            ],
            options:{
                effect: 'cards'
            },
            slideCustomStyle: {
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                borderRadius: '36rpx'
            }
        }
    },
    mounted() {
        //用户验证用户是否登陆过
        // console.log(this)
        var that = this
        wx.login({
            success(res) {
                if (res.code) {
                    // uni.setStorageSync('code', res.code)
                    that.code = res.code
                    console.log('code',that.code)
                    // 将 res.code 发送至后台服务器进行处理
                    uni.request({
                        url: 'https://admin.mindepoch.com:8089/wechat/CheckWxUserIsRegisterAndBindPhone',
                        method: 'POST',
                        header: {
                            'Content-Type': 'application/x-www-form-urlencoded'
                        },
                        data: { code: res.code },
                        success: function(res) {
                            console.log('resres',res)
                            that.isBindPhone = res.data.isBindPhone
                            that.wxUid = res.data.wxUid
                            if(res.data.message==="微信用户已注册，模拟登录成功!"){
                                uni.setStorageSync('wxUid', res.data.wxUid); //保存用户id
                                uni.setStorageSync('userName', res.data.userName)
                                uni.setStorageSync('session_token', res.cookies[0].split(';')[0]) //保存cookie值
                            }else{
                                if(res.data.code===1){
                                    //用户已注册

                                }else{
                                    that.showUserInfo = true
                                }
                            }


                        },
                        fail: function(err) {
                            console.log(err)
                        }
                    })
                } else {
                    console.error('登录失败！' + res.errMsg);
                }
            }
        })
    },
    onload() {},
    methods: {
        //获取到用户昵称  以及用户头像
        handleSubmit(){
            this.disabledSubmit = true
            var that = this
            wx.login({
                success(res) {
                    if(!res.code) return
                    console.log(that.avatarUrl)
                    uni.downloadFile({
                        url: that.avatarUrl,
                        success: downloadRes => {
                            if (downloadRes.statusCode === 200) {
                                // 图片下载成功后获取临时文件路径
                                const tempFilePath = downloadRes.tempFilePath;
                                console.log('图片临时路径',tempFilePath)
                                uni.uploadFile({
                                    url: 'https://admin.mindepoch.com:8089/wechat/AppletWeChatRegisterOrLogin',
                                    method: 'POST',
                                    filePath:tempFilePath,
                                    name: 'avatar',
                                    formData: {
                                        code: res.code,
                                        username: that.userName,
                                    },
                                    success: uploadRes => {
                                        uni.showToast({
                                            title: 'AppletWeChatRegisterOrLogin',
                                            icon: 'none'
                                        })
                                        console.log('上传成功uploadRes', uploadRes);
                                        console.log(JSON.parse(uploadRes.data))
                                        const data = JSON.parse(uploadRes.data)
                                        if(data.code===1){
                                            uni.showToast({
                                                title: '成功！',
                                                icon: 'none'
                                            });
                                            uni.setStorageSync('userName', that.userName);
                                            uni.setStorageSync('session_token', uploadRes.cookies[0].split(';')[0]); //保存cookie值
                                            uni.setStorageSync('wxUid', data.wxUid); //保存用户id
                                            uni.setStorageSync('openId', data.openId); //保存用户id
                                            that.showUserInfo = false //隐藏用户填写的表单
                                        }else{
                                            //失败
                                            // uni.showModal({
                                            //     title: '弹窗标题', // 弹窗的标题
                                            //     content: JSON.parse(uploadRes.data), // 弹窗的文本内容
                                            //     showCancel: true, // 是否显示取消按钮，默认为 true
                                            //     cancelText: '取消', // 取消按钮的文字，默认为"取消"
                                            //     cancelColor: '#000000', // 取消按钮的文字颜色
                                            //     confirmText: '确定', // 确定按钮的文字，默认为"确定"
                                            //     confirmColor: '#576B95', // 确定按钮的文字颜色
                                            //     success: function (res) {
                                            //         if (res.confirm) {
                                            //             console.log('用户点击确定');
                                            //         } else if (res.cancel) {
                                            //             console.log('用户点击取消');
                                            //         }
                                            //     },
                                            //     fail: function (err) {
                                            //         console.log('API 调用失败: ', err);
                                            //     }
                                            // });
                                            that.disabledSubmit = false
                                        }
                                    },
                                    fail: uploadErr => {
                                        // uni.showModal({
                                        //     title: '弹窗标题', // 弹窗的标题
                                        //     content: JSON.parse(uploadErr), // 弹窗的文本内容
                                        //     showCancel: true, // 是否显示取消按钮，默认为 true
                                        //     cancelText: '取消', // 取消按钮的文字，默认为"取消"
                                        //     cancelColor: '#000000', // 取消按钮的文字颜色
                                        //     confirmText: '确定', // 确定按钮的文字，默认为"确定"
                                        //     confirmColor: '#576B95', // 确定按钮的文字颜色
                                        //     success: function (res) {
                                        //         if (res.confirm) {
                                        //             console.log('用户点击确定');
                                        //         } else if (res.cancel) {
                                        //             console.log('用户点击取消');
                                        //         }
                                        //     },
                                        //     fail: function (err) {
                                        //         console.log('API 调用失败: ', err);
                                        //     }
                                        // });
                                        console.error('上传失败', uploadErr);
                                    }
                                })
                            }
                        },
                        fail: downloadErr => {
                            console.error('下载图片失败', downloadErr)
                            // uni.showModal({
                            //     title: '弹窗标题', // 弹窗的标题
                            //     content: JSON.stringify(downloadErr), // 弹窗的文本内容
                            //     showCancel: true, // 是否显示取消按钮，默认为 true
                            //     cancelText: '取消', // 取消按钮的文字，默认为"取消"
                            //     cancelColor: '#000000', // 取消按钮的文字颜色
                            //     confirmText: '确定', // 确定按钮的文字，默认为"确定"
                            //     confirmColor: '#576B95', // 确定按钮的文字颜色
                            //     success: function (res) {
                            //         if (res.confirm) {
                            //             console.log('用户点击确定');
                            //         } else if (res.cancel) {
                            //             console.log('用户点击取消');
                            //         }
                            //     },
                            //     fail: function (err) {
                            //         console.log('API 调用失败: ', err);
                            //     }
                            // });
                        }
                    });
                },
                fail(err){
                    console.log(err)
                    uni.showToast({
                        title: err.toString(),
                        icon: 'none'
                    })
                }
            })
        },
        onChooseAvatar(e) {
            const { avatarUrl } = e.detail 
            this.avatarUrl = avatarUrl
        },
        change(e) {
            return
            console.log(e)
            console.log('code',this.code)
            var that = this
            //此处需要处理 用户点击的是同意还是不同意
            if(this.clickArgee){
                //获取用户信息
                wx.getUserProfile({
                    withCredentials: true,
                    lang: 'zh_CN',
                    desc:'提升用户体验，减少用户操作',
                    success: (userRes) => {
                        console.log('userRes',userRes)
                        //用户头像传给后端
                        uni.downloadFile({
                            url: userRes.userInfo.avatarUrl,
                            success: downloadRes => {
                                if (downloadRes.statusCode === 200) {
                                    // 图片下载成功后获取临时文件路径
                                    const tempFilePath = downloadRes.tempFilePath;
                                    console.log(tempFilePath)
                                    // 将临时文件读取为ArrayBuffer
                                    uni.getFileSystemManager().readFile({
                                        filePath: tempFilePath,
                                        success: Buffer => {
                                            console.log('readRes',Buffer)
                                            uni.request({
                                                url: 'https://admin.mindepoch.com:8089/wechat/AppletWeChatRegisterOrLogin',
                                                method: 'POST',
                                                data: {
                                                    code: that.code,
                                                    username: userRes.userInfo.nickName,
                                                    avatar: Buffer
                                                },
                                                header: {
                                                    'Content-Type': 'application/x-www-form-urlencoded',
                                                    // 'Content-Type': 'multipart/form-data',
                                                },
                                                success: uploadRes => {
                                                    console.log('上传成功uploadRes', uploadRes);
                                                    if(uploadRes.data.code===1){
                                                        //用户头像上传失败
                                                        that.isBindPhone = res.data.isBindPhone
                                                        if(res.data.code===1){
                                                            //用户已注册
                                                            that.needDialog = false
                                                        }else{
                                                            that.needDialog = true
                                                        }
                                                    }else{
                                                        //提示用户头像上传失败
                                                        
                                                    }
                                                },
                                                fail: uploadErr => {
                                                    console.error('上传失败', uploadErr);
                                                }
                                            });
                                        },
                                        fail: readErr => {
                                            console.error('读取文件失败', readErr);
                                        }
                                    });
                                }
                            },
                            fail: downloadErr => {
                                console.error('下载图片失败', downloadErr);
                            }
                        });


                        
                        //微信用户注册或登录接口
                        // uni.request({
                        //     url: 'https://admin.mindepoch.com:8089/wechat/AppletWeChatRegisterOrLogin',
                        //     method: 'POST',
                        //     header: {
                        //         'Content-Type': 'application/x-www-form-urlencoded'
                        //     },
                        //     data: { 
                        //         code: this.code,
                        //         username: userRes.userInfo.nickName,
                        //         avatar: userRes.userInfo.avatarUrl
                        //     },
                        //     success: (res)=> {
                        //         console.log('success',res.data)
                        //         this.isBindPhone = res.data.isBindPhone
                        //         // if(res.data.code===1){
                        //         //     //用户已注册
                        //         //     this.needDialog = false
                        //         // }else{
                        //         //     this.needDialog = true
                        //         // }
                        //     },
                        //     fail: (err)=> {
                        //         console.log(err)
                        //     }
                        // })
                    },
                    fail: (err) => {
                        console.error('获取用户信息失败',err);
                    }
                });
            }if(this.clickNoArgee){

            }

        },
        open() {
			this.$refs.popup.open('bottom')
		},
		close() {
			this.$refs.popup.close()
		},
        close_noArgee() {
            this.clickNoArgee = true
            this.$refs.popup.close()
        },
        close_argee() {
            this.clickArgee = true
            this.$refs.popup.close()
        },
        //用户未注册的卡片点击事件
        handleNav(index) {
            // this.open()
        },
        NavTo(index) {
            if(index===0){
                uni.navigateTo({
                    url: `/pages/index/index`
                });
            }else{
                uni.showToast({
                    title: '敬请期待',
                    icon: 'none'
                });
            }
        },
        onSlideChange(swiper,index) {
            console.log(swiper,index)
            this.i = index
            // 你可以在这里获取当前的swiper索引
            const currentIndex = swiper.activeIndex;
            // 执行你想要的操作，比如更新页面标题
            // uni.setNavigationBarTitle('当前页: ' + (currentIndex + 1));
        },
        getAuth() {
            wx.getUserProfile({
                withCredentials: true,
                lang: 'zh_CN',
                desc:'提升用户体验，减少用户操作',
                success: function (userRes) {
                    console.log('userRes',userRes)
                    // var userInfo = userRes.userInfo;
                    // console.log("用户昵称为：" + userInfo.nickName);
                    // console.log("用户头像地址为：" + userInfo.avatarUrl);
                    // this.nickName = userInfo.nickName
                    // this.avatarUrl = userInfo.avatarUrl
                    // this.$globalData.userPhoto = userInfo.avatarUrl

                    // if(e.detail.code){
                    //     that.sendPhoneNumberToServer(e.detail.code,'no');
                    // }else{
                    //     that.sendPhoneNumberToServer(e.detail.code,'yes');
                    // }
                },
                fail: function () {
                    console.error('获取用户信息失败');
                }
            });
        },

        handleUserDestory() {
            uni.request({
                url: 'https://admin.mindepoch.com:8089/UnregisterUser',
                method: 'POST',
                header: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Cookie': `${uni.getStorageSync('session_token')}`,
                },
                data: { id: uni.getStorageSync('wxUid') },
                success:function(res) {
                    console.log(res)
                    uni.showToast({
                        title: '注销成功！',
                        icon: 'none'
                    });
                },
                fail:function(err) {
                    console.log(err)
                }
            })
        },

        // 获取手机号
        getPhoneNumber(e){
            console.log('e',e)
            var that = this
            wx.login({
                success(res) {
                    if (res.code) {
                        that.code = e.code
                        // 将 res.code 发送至后台服务器进行处理
                        uni.request({
                            url: 'https://admin.mindepoch.com:8089/wechat/AppletWeChatLogin',
                            method: 'POST',
                            header: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            },
                            data: { code: res.code },
                            success: function (response) {
                                console.log('登录成功', response);
                                that.OpenId = response.data.OpenId
                                // TODO: 根据后台返回的结果保存 openid、sessionKey 等信息
                                uni.getUserInfo({
                                    withCredentials: true,
                                    lang: 'zh_CN',
                                    success: function (userRes) {
                                        var userInfo = userRes.userInfo;
                                        console.log("用户昵称为：" + userInfo.nickName);
                                        console.log("用户头像地址为：" + userInfo.avatarUrl);
                                        that.nickName = userInfo.nickName
                                        that.avatarUrl = userInfo.avatarUrl
                                        that.$globalData.userPhoto = userInfo.avatarUrl
                                        // TODO: 将用户昵称和头像地址保存或上传至后台服务器
                                        if(e.detail.code){
                                            that.sendPhoneNumberToServer(e.detail.code,'no');
                                        }else{
                                            that.sendPhoneNumberToServer(e.detail.code,'yes');
                                        }
                                    },
                                    fail: function () {
                                        console.error('获取用户信息失败');
                                    }
                                });
                            }
                        })
                    } else {
                        console.error('登录失败！' + res.errMsg);
                    }
                }
            })
        },

        sendPhoneNumberToServer(code,bool) {
            // 将code、encryptedData和iv发送到后端API
            uni.request({
                url: 'https://admin.mindepoch.com:8089/wechat/RegisterAndLoginWXUserPhone',
                method: 'POST',
                data:{
                    username:this.nickName,
                    openid:this.OpenId,
                    phone_code:bool=="no"?code:'',
                    reject_binding:bool
                },
                header: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                success: (res) => {
                    console.log('success',res)
                    if (res.statusCode === 200) {
                        console.log('手机号码传递成功', res);
                        if(res.data.code===1){
                            this.$globalData.wxUid = res.data.wxUid
                            uni.setStorageSync('session_token', res.cookies[0].split(';')[0]); //保存cookie值
                            uni.setStorageSync('wxUid', res.data.wxUid); //保存用户id
                            uni.navigateTo({
                                url: `/pages/index/index`
                            });
                        }
                    } else {
                        console.log('服务器返回状态码异常', res.statusCode);
                    }
                },
                fail: (err) => {
                    console.log('发送失败', err);
                }
            });
        }
    }
}
</script>

<style scoped>
.wrapper{
    height: 100vh;
    width: 100vw;
}
.image {
	height: 720rpx;
	width: 520rpx;
    
    
}
.section{
    
}
.shadowBoard{
    /* 其他样式，如背景大小、位置等 */
    width: 100vw;
    height: 100vh;
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
    filter: blur(5px);
    z-index: -99;
    position: fixed;
    
}
.swiper{
    padding-top: 320rpx;
}
.CardContent{
    position: absolute;
    top:0;
    left: 50%;
    transform: translateX(-50%);
    height: 100%;
    width: 85%;
    color: #fff;
}
.card{
    position: relative;
    width: 100%;
    height: 100%;
}
.header1{
    font-size: 40rpx;
    margin-top: 20rpx;
    text-align: left;
}
.header2{
    position: absolute;
    bottom:40rpx;
    left: 0;
    font-size: 38rpx;
}
.sdsd{
    text-align: left;
}
.distence{
    margin-top: 20rpx;
}
.detail{
    font-size: 24rpx;
    max-height: 100rpx;
    line-height: 38rpx;
    background-color: #00000039;
    padding: 6rpx;
    border-radius: 10rpx;
    text-align: left;
    overflow-y: scroll;
}
.shadow{
    position: fixed;
    width: 100vw;
    height: 100vh;
    
}
.shadow>image{
    width: auto;
    height: 100%;
}
.btn{
    padding: 0 !important;
    margin: 0 !important;
    display: block;
    z-index: 99;
    border-radius: 24rpx;
    height: 720rpx;
    border: 1px solid #0000009a;
    box-shadow: 0 0 20rpx #fff;
}
.userInfoPression{
    background-color: #ffffff;
    height: 350rpx;
    border-radius: 20rpx 20rpx 0 0;
}
.mainInfo{

}
.infoHead{
    text-align: center;
    padding: 42rpx;
    font-weight: 700;
}
.infoFoot{
    display:flex;
    width: 100vw;
    position: absolute;
    bottom: 50rpx;
    left: 0;
}
.infoFoot>Button{
    width: 200rpx;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 32rpx;
    color: #fff;
    
}
.infoFoot>Button:nth-child(1){
    background-color: gray;
}
.infoFoot>Button:nth-child(2){
    background-color: #1AAD19;
}
.ttt{
    position: absolute;
    top:0;
    left: 0;
    z-index: 9;
    width: 100vw;
    height: 100vh;
    background-color: #ffffff;
}
.pisition{
    padding-top: 300rpx;
}
.avatar-wrapper{
    border: 1px solid rgb(192, 176, 176);
    width: 200rpx;
    height: 200rpx;
    margin-top: 25rpx;
}
.avatar{
    width: 150rpx;
    height: 150rpx;
    margin-top: 25rpx;
}
.weui-input{
    border: 1px solid rgb(123, 108, 108);
    margin-top: 300rpx;
    width: 50vw;
    height: 70rpx;
    border-radius: 12rpx;
    margin: 200rpx auto;
}
.tipUserHeader{
    text-align: center;
    margin-top: 20rpx;
    color: rgb(123, 108, 108);
}
.submit{
    width: 250rpx;
}
</style>