<template>
    <view>
        <u-toast ref="uToast" />
        <!-- #ifndef MP-WEIXIN  -->
        <view class="cu-modal" v-if="showLogin" :class="[{ show: showLogin }, modalType]" cathctouchmove @tap="hideModal">
            <view class="cu-dialog" @tap.stop style="background: none;overflow: visible;">
                <view class="modal-box">
                    <image class="head-bg" src="/static/images/login/nologin_bg.png" mode=""></image>
                    <view class="detail">
                        <view class="user-avatar">
                            <!-- #ifndef MP-TOUTIAO -->
                            <open-data type="userAvatarUrl"></open-data>
                            <!-- #endif -->
                            <!-- #ifdef MP-TOUTIAO -->
                            <image class="toutiao-logo" :src="logoImage"></image>
                            <!-- #endif -->
                            <!-- #ifdef H5 || APP-PLUS -->
                            <u-avatar :src="$store.state.config.shopLogo" size="large"></u-avatar>
                            <!-- #endif -->
                        </view>
                        <open-data class="user-name" type="userNickName"></open-data>
                        <view class="title2">为了提供更优质的服务</view>
                        <view class="title2">需要获取您的头像昵称</view>
                    </view>
                    <view class="btn-box y-f">
                        <!-- #ifdef MP-ALIPAY -->
                        <button class="cu-btn login-btn" @click="getALICode">授权并查看</button>
                        <!-- #endif -->
                        <!-- #ifdef MP-TOUTIAO -->
                        <button class="cu-btn login-btn" @click="ttLogin()">授权并查看</button>
                        <!-- #endif -->
                        <!-- #ifdef H5 || APP-PLUS -->
                        <button class="cu-btn login-btn" @click="toAccountLogin()">授权并查看</button>
                        <!-- #endif -->
                        <button class="cu-btn close-btn" @tap="closeAuth">暂不授权</button>
                    </view>
                </view>
            </view>
        </view>
        <!-- #endif  -->
        <!-- #ifdef MP-WEIXIN  -->
        <view class="cu-modal" v-if="showLogin" :class="[{ show: showLogin }, modalType]">
            <view class="cu-dialog" @tap.stop style="background: none;overflow: visible;">
                <view class="modal-box">
                    <view class="detail">
                        <view class="shopDesc">
                            <view class="cu-avatar sm round margin-left">
                                <u-image width="48rpx" height="48rpx" :src="shopLogo"></u-image>
                            </view>
                            <text class="shopName">
                                {{shopName||'登录授权'}}
                            </text>
                            <text class="get">
                                申请
                            </text>
                        </view>
                        <view class="title3">获取以下权限为您提供服务</view>
                        <view class="desc">
                            1、获取你的手机号提供更好的账户安全，物流，订单状态提醒等服务（在接下来微信授权手机号的弹窗中选择“允许”）<br />
                            2、使用我们的相关服务，需要将您的手机号授权给我们。
                        </view>
                        <!--服务协议-->
                        <view class="margin-tb agreement-checked-view">
                            <u-checkbox v-model="agreement" @change="checkboxChange" size="30" active-color="#19be6b"></u-checkbox>
                            <view class="text-black-view">
                                <text class="text-black">同意</text>
                                <text class="text-blue" @tap="goUserAgreementPage">《服务协议》</text>
                                <text class="text-black">与</text>
                                <text class="text-blue" @tap="goUserPrivacyPolicy">《隐私协议》</text>
                            </view>
                        </view>
                    </view>
                    <view class="btn-box-getPhoneNumber x-bc">
                        <button class="cu-btn bg-grey close-btn" @tap="closeAuth">取消</button>
                        <!-- #ifdef MP-WEIXIN -->
                        <button class="cu-btn login-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">确定</button>
                        <!-- #endif -->
                    </view>
                </view>
            </view>
        </view>
        <!-- #endif  -->
    </view>
</template>

<script>
    /**
     * 登录提示页
     * @property {Boolean} value=showLoginTip - 由v-model控制显示隐藏。
     * @property {Boolean} forceOauth - 小程序端特制的全屏登录提示。
     */
    import { articles } from '@/common/mixins/mixinsHelper.js'
    import { mapMutations, mapActions, mapState } from 'vuex';
    export default {
        name: 'coreCmsLoginModal',
        mixins: [articles],
        components: {},
        data() {
            return {
                agreement: true
            };
        },
        props: {
            value: {},
            modalType: {
                type: String,
                default: ''
            }
        },
        computed: {
            ...mapState({
                showLoginTip: state => state.showLoginTip,
                sessionAuthId: state => state.sessionAuthId,
                hasLogin: state => state.hasLogin,
            }),
            shopLogo() {
                return this.$store.state.config.shopLogo
            },
            shopName() {
                return this.$store.state.config.shopName;
            },
            showLogin: {
                get() {
                    return this.showLoginTip;
                },
                set(val) {
                    this.$store.commit('showLoginTip', val);
                }
            },
            sessionAuthIdTool: {
                get() {
                    return this.sessionAuthId;
                },
                set(val) {
                    this.$store.commit('sessionAuthId', val);
                }
            }
        },
        mounted() {
            const _this = this
            // #ifdef MP-WEIXIN
            var userInfo = this.$store.state.userInfo;
            //var token = this.$db.get('userToken');
            if (userInfo) {
                console.log("获取到用户数据");
            } else {
                _this.doToken();
            }
            // #endif
        },
        watch: {
            'hasLogin': {
                handler(newVal) {
                    console.log(newVal);
                    if (newVal == false) {
                        console.log("watch监听");
                        this.doToken();
                    }
                },
                deep: true,
                immediate: true,
            }
        },
        methods: {
            doToken() {
                const _this = this
                console.log("重新获取用户数据");
                _this.getCode(function (code) {
                    var data = {
                        code: code
                    }
                    _this.$u.api.onLogin(data).then(res => {
                        if (res.status) {
                            if (res.data.auth) {
                                _this.$db.set('userToken', res.data.auth.token)
                                _this.$store.commit('hasLogin', true);
                            }
                            if (res.data.user) {
                                _this.$store.commit('userInfo', res.data.user);
                            }
                            _this.sessionAuthIdTool = res.otherData;
                            console.log("成功后获取sessionAuthIdTool：" + _this.sessionAuthIdTool);
                        } else {
                            _this.sessionAuthIdTool = res.otherData;
                            console.log("失败后获取sessionAuthIdTool：" + _this.sessionAuthIdTool);
                        }
                    })
                })
            },
            // 勾选版权协议
            checkboxChange(e) {
                this.agreement = e.value;
            },
            // 隐藏登录弹窗
            hideModal() {
                this.showLogin = false;
            },
            // 去登录
            toAccountLogin() {
                this.showLogin = false;
                this.$u.route('/pages/login/loginByAccount/loginByAccount');
            },
            // 小程序，取消登录
            closeAuth() {
                this.showLogin = false;
                this.$u.toast('您已取消授权')
            },
            getCode: function (callback) {
                let _this = this
                uni.login({
                    // #ifdef MP-ALIPAY
                    scopes: 'auth_user',
                    // #endif
                    success: function (res) {
                        console.log(res);
                        if (res.code) {
                            return callback(res.code)
                        } else {
                            //login成功，但是没有取到code
                            _this.$refs.uToast.show({ title: '未取得code，请重试', type: 'error', })
                        }
                    },
                    fail: function (res) {
                        console.log(res);
                        _this.$refs.uToast.show({ title: '用户授权失败wx.login，请重试', type: 'error', })
                    }
                })
            },
            toLogin: function (data) {
                let _this = this
                _this.$u.api.loginByDecodeEncryptedData(data).then(res => {
                    if (res.status) {
                        //判断是否返回了token，如果没有，就说明没有绑定账号，跳转到绑定页面
                        if (res.data.token) {
                            //登陆成功，设置token，并返回上一页
                            _this.$db.set('userToken', res.data.token)
                            _this.$store.commit('hasLogin', true);
                            _this.$refs.uToast.show({ title: '登录成功', type: 'success', })
                            return false
                        } else {
                            // #ifdef MP-WEIXIN
                            _this.sessionAuthIdTool = res.data.sessionAuthId;
                            // #endif
                            // #ifndef MP-WEIXIN
                            _this.$u.route({ type: 'navigateTo', url: '/pages/login/loginBySMS/loginBySMS?sessionAuthId=' + res.data.sessionAuthId });
                            // #endif
                        }
                    } else {
                        _this.$refs.uToast.show({ title: '登录失败，请重试', type: 'error', })
                    }
                })
            },
            async getPhoneNumber(e) {
                let _this = this;
                if (e.mp.detail.errMsg == 'getPhoneNumber:ok') {
                    var data = {
                        sessionAuthId: _this.sessionAuthIdTool,
                        iv: e.mp.detail.iv,
                        encryptedData: e.mp.detail.encryptedData,
                    }
                    //有推荐码的话，带上
                    var invitecode = _this.$db.get('invitecode')
                    if (invitecode) {
                        data.invitecode = invitecode
                    }
                    _this.toGetPhoneNumber(data);
                } else {
                    _this.$u.toast('如未授权，您可尝试使用手机号+短信验证码登录');
                }
            },
            //实际的去登陆
            toGetPhoneNumber: function (data) {
                let _this = this
                _this.$u.api.loginByGetPhoneNumber(data).then(res => {
                    console.log(res);
                    if (res.status) {
                        //判断是否返回了token，如果没有，就说明没有绑定账号，跳转到绑定页面
                        if (res.data.token) {
                            //console.log("登陆成功，设置token，并返回上一页");
                            //登陆成功，设置token，并返回上一页
                            _this.$db.set('userToken', res.data.token)
                            _this.$store.commit('hasLogin', true);
                            _this.showLogin = false;
                            _this.$refs.uToast.show({ title: '登录成功', type: 'success', })
                            return false
                        }
                    } else if (res.status == false && res.code == 500) {
                        console.log("sessionId不正确，重载");
                        _this.$u.route({ type: 'switchTab', url: '/pages/index/default/default' });
                    } else {
                        _this.$u.toast('登录失败，请重试')
                    }
                })
            },
            // #ifdef MP-ALIPAY
            getALICode() {
                let that = this
                uni.login({
                    scopes: 'auth_user',
                    success: (res) => {
                        if (res.authCode) {
                            uni.getUserInfo({
                                provider: 'alipay',
                                success: function (infoRes) {
                                    if (infoRes.errMsg == "getUserInfo:ok") {
                                        let userInfo = {
                                            'nickname': infoRes.nickName,
                                            'avatar': infoRes.avatar
                                        }
                                        that.aLiLoginStep1(res.authCode, userInfo);
                                    }
                                },
                                fail: function (errorRes) {
                                    this.$u.toast('未取得用户昵称头像信息');
                                }
                            });
                        } else {
                            this.$u.toast('未取得code');
                        }
                    },
                    fail: function (res) {
                        this.$u.toast('用户授权失败my.login');
                    }
                });
            },
            aLiLoginStep1(code, userInfo) {
                let data = {
                    'code': code,
                    'userInfo': userInfo
                }
                this.$u.api.alilogin1(data).then(res => {
                    this.alipayNoLogin = false;
                    if (res.status) {
                        this.sessionAuthIdTool = res.data.sessionAuthId
                        //判断是否返回了token，如果没有，就说明没有绑定账号，跳转到绑定页面
                        if (!res.data.hasOwnProperty('token')) {
                            this.$u.route({ type: 'redirectTo', url: '/pages/login/loginBySMS/loginBySMS?sessionAuthId=' + res.data.sessionAuthId });
                        } else {
                            this.$db.set('userToken', res.data.token)
                            uni.navigateBack({
                                delta: 1
                            });
                        }
                    } else {
                        this.$u.toast(res.msg)
                    }
                })
            },
            // #endif
            // #ifdef MP-TOUTIAO
            ttLogin() {
                let that = this
                uni.login({
                    provider: 'toutiao',
                    success: (res) => {
                        //console.log(res);
                        if (res.errMsg == "login:ok") {
                            uni.getUserInfo({
                                provider: 'toutiao',
                                success: function (infoRes) {
                                    //console.log(infoRes);
                                    if (infoRes.errMsg == "getUserInfo:ok") {
                                        let code = res.code;
                                        let userInfo = {
                                            'nickname': infoRes.userInfo.nickName,
                                            'avatar': infoRes.userInfo.avatarUrl,
                                            'gender': infoRes.userInfo.gender,
                                            'language': infoRes.userInfo.language,
                                            'country': infoRes.userInfo.country,
                                            'city': infoRes.userInfo.city,
                                            'province': infoRes.userInfo.province
                                        }
                                        that.ttLoginStep(code, userInfo);
                                    }
                                },
                                fail: function (errorRes) {
                                    this.$u.toast('未取得用户昵称头像信息');
                                }
                            });
                        } else {
                            this.$u.toast('未取得code');
                        }
                    },
                    fail: function (res) {
                        this.$u.toast('用户授权失败my.login');
                    }
                });
            },
            ttLoginStep(code, userInfo) {
                let data = {
                    'code': code,
                    'userInfo': userInfo
                }
                this.$u.api.ttlogin(data).then(res => {
                    if (res.status) {
                        if (!res.data.hasOwnProperty('token')) {
                            this.$u.route({ type: 'redirectTo', url: '/pages/login/loginBySMS/loginBySMS?sessionAuthId=' + res.data.userId });
                        } else {
                            this.$db.set('userToken', res.data.token)
                            uni.navigateBack({
                                delta: 1
                            });
                        }
                    } else {
                        this.$u.toast(res.msg)
                    }
                })
            }
            // #endif
        }
    };
</script>

<style lang="scss">
    .modal-box { width: 610rpx; border-radius: 20rpx; background: #fff; position: relative; left: 50%; transform: translateX(-50%); padding-bottom: 30rpx; z-index: 11111; }
        .modal-box .head-bg { width: 100%; height: 210rpx; }
        .modal-box .detail { width: 100%; text-align: center; }
            .modal-box .detail .title1 { color: #46351b; font-size: 35rpx; font-weight: bold; }
            .modal-box .detail .title2 { font-size: 28rpx; color: #999; padding-top: 20rpx; }
            .modal-box .detail .title3 { color: #46351b; font-size: 35rpx; font-weight: bold; text-align: left; line-height: 35rpx; padding: 30rpx 0 30rpx 30rpx; }
            .modal-box .detail .desc { font-size: 24rpx; line-height: 40rpx; color: #333; margin: 0 30rpx 0rpx 30rpx; background: #f7f8fa; text-align: left; padding: 30rpx; }

    .shopDesc { padding: 30rpx 0rpx 0rpx 0rpx; text-align: left; }
        .shopDesc .shopName { margin-left: 20rpx; line-height: 40rpx; }
        .shopDesc .get { margin-left: 20rpx; line-height: 40rpx; }

    .user-avatar { width: 160rpx; height: 160rpx; overflow: hidden; margin: 0 auto; margin-bottom: 40rpx; }
    .user-name { font-size: 35rpx; font-family: PingFang SC; font-weight: bold; color: #845708; margin-bottom: 30rpx; }

    .modal-box .btn-box { margin-top: 80rpx; }
        .modal-box .btn-box .login-btn { width: 492rpx; height: 70rpx; background: linear-gradient(90deg, #e9b461, #eecc89); box-shadow: 0px 7rpx 6rpx 0px rgba(229, 138, 0, 0.22); border-radius: 35rpx; font-size: 28rpx; color: rgba(255, 255, 255, 0.9); }
        .modal-box .btn-box .close-btn { width: 492rpx; height: 70rpx; color: #e9b766; font-size: 26rpx; margin-top: 20rpx; background: none; }

    .modal-box .btn-box-getPhoneNumber { margin-top: 0rpx; padding: 0 30rpx; }
        .modal-box .btn-box-getPhoneNumber .login-btn { width: 45%; height: 70rpx; background: linear-gradient(90deg, #e9b461, #eecc89); box-shadow: 0px 7rpx 6rpx 0px rgba(229, 138, 0, 0.22); font-size: 28rpx; color: rgba(255, 255, 255, 0.9); }
        .modal-box .btn-box-getPhoneNumber .close-btn { width: 45%; height: 70rpx; color: #e9b766; font-size: 26rpx; background-color: #ededed; color: #ffffff; }


    .agreement-checked-view { position: relative; padding: 18.18rpx 0rpx 18.18rpx 30rpx; display: flex; align-items: center; margin: 10rpx 0; font-size: 24rpx; }
        .agreement-checked-view .coreshop-checked { transform: scale(0.7); }
    /*.agreement-checked-view .text-black-view { line-height: 47.27rpx; }*/
</style>
