<template>
    <view>
        <u-popup :show="loginPopupShow" mode="bottom" :round="10" @close="closeLogin" zIndex="999998">
            <view class="f__login">
                <view class="loginLoading" v-if="isLoading">
                    <u-loadmore status="loading" loadingText="正在登录..."></u-loadmore>
                </view>
                <view class="title">请先登录~</view>
                <view class="text">用户登录后可享受更好的服务体验</view>
                <view class="loginButton" v-if="!isPhoneLogin">
                    <!-- #ifdef MP-WEIXIN -->
                    <!-- <button class="button" @click="onAuthorization" :style="{background:PrimaryColor}">微信授权登录</button> -->
                    <button class="button marginT" open-type="getPhoneNumber" @getphonenumber="decryptPhoneNumber"
                        :style="{ background: PrimaryColor }">微信手机号登录</button><!-- 此功能需微信认证 -->
                    <!-- #endif -->
                    <button class="button" @click="closeLogin" style="background:#fff;margin-top:24rpx;"
                        :style="{ border: '2rpx solid ' + PrimaryColor, color: PrimaryColor }">
                        暂不登录
                    </button>
                </view>

            </view>
        </u-popup>
        <f-loading></f-loading>
    </view>
</template>
<script>
import fLoading from "@/components/f-loading/loading.vue"
import uPopup from "@/uni_modules/uview-ui/components/u-popup/u-popup.vue";
import uLoadmore from "@/uni_modules/uview-ui/components/u-loadmore/u-loadmore.vue";
import { mapState, mapMutations } from 'vuex';
import HttpRequest from '@/common/httpRequest'
import HttpConfig from '@/common/config'

// #ifdef MP
import { getPhoneInfo, getUserInfo } from './f-login.js';
// #endif
import { getCurrentRouter } from '@/common/login.js';
import store from '@/store/index.js'

var clear;
export default {
    components: {
        uPopup,
        uLoadmore,
        fLoading
    },
    name: 'f-login',
    computed: {
        ...mapState(['loginPopupShow']),
    },
    data() {
        return {
            // #ifndef MP-ALIPAY
            PrimaryColor: '#1fba1a', //主题色
            // #endif
            readonly: false,
            codeText: '获取验证码',
            phone: '', //号码
            vCode: '', //验证码
            code: '',  //uni.login获取的code
            currentRouter: '',
        };
    },
    watch: {
        loginPopupShow: {
            handler(val) {
                console.log(val)
            },
            deep: true
        },
    },
    created() {
        this.currentRouter = getCurrentRouter()
    },
    methods: {
        ...mapMutations(['setLoginPopupShow', 'setUserInfo']),
        //个人信息授权登录
        onAuthorization(e) {
            // #ifdef MP-WEIXIN
            this.closeLogin();
            this.$store.commit('setShowWxLogin', true) //打开微信新授权组件
            // #endif
        },
        //授权手机号登录
        decryptPhoneNumber(e) {
            console.log(e, '授权手机号')
            store.commit("setLoadingShow", true);
            var that = this
            // #ifdef MP-WEIXIN
            if (e.detail.errMsg == 'getPhoneNumber:ok') {
                if (e.detail.iv) {
                    var userInfo = e.detail;
                    // userInfo.code = that.code
                    // this.closeLogin();
                    //请去getPhoneInfo方法中使用您的接口绑定信息
                    getPhoneInfo(userInfo, res => {
                        console.log("-------------", res)


                        store.commit('setUserInfo', userInfo)
                        let userInfo = {
                            ...res,
                            token: true,//token用于判断是否登录
                        }

                        //调用登录接口 获取token

                        let phone = res.phone
                        const extConfig = uni.getAccountInfoSync();
                        uni.login({
                            success: (ras) => {
                                HttpRequest.post(HttpConfig.weChatLogin, {
                                    jsCode: ras.code,
                                    mobile: phone,
                                    appId: extConfig.miniProgram.appId,
                                }, "json", null, false).then(ress => {
                                    console.log(ress, '获取token')
                                    const obj = ress.data
                                    let userInfo = {
                                        ...obj,
                                        token: true,//token用于判断是否登录
                                    }
                                    store.commit('setUserInfo', userInfo)

                                    // this.setUserInfo(userInfo)

                                    setTimeout(() => {
                                    })
                                })
                            },
                        })

                        //生成token
                        this.setUserInfo(userInfo)
                        store.commit("setLoadingShow", false);
                        setTimeout(() => {
                            uni.showToast({
                                title: '登录成功',
                                icon: 'none'
                            });

                            this.closeLogin();
                        }, 100)
                    });
                } else {
                    // 授权失败请使用验证码登录
                    store.commit("setLoadingShow", false);

                    this.isPhoneLogin = true
                    uni.showToast({
                        title: '请使用手机号登录',
                        icon: 'none'
                    });
                }
            } else {
                // this.closeLogin()
            }
            // #endif


        },
        // 支付宝拒绝
        onAuthError(e) {
            uni.showToast({
                title: '您已拒绝授权~',
                icon: 'none'
            });
        },
        closeLogin() {
            console.log('closeLogin')
            this.setLoginPopupShow(false);
            // #ifdef APP-PLUS || H5
            this.isLoading = false
            this.isPhoneLogin = true//是否显示验证码登录
            // #endif
            // #ifndef APP-PLUS || H5
            this.isLoading = false
            this.isPhoneLogin = false//是否显示验证码登录
            // #endif
        },
        // 自动静默登录----获取code
        // 静默登录：就是已经登录过的用户，被迫下线。调用此接口快速登录
        getLoginByUnion() {
            console.log("自动静默登录--自定义接口--")
            var that = this
            uni.login({
                success(res) {
                    console.log(res, "获取code")
                    that.code = res.code
                    let httpData = {
                        code: res.code,
                    }
                    // uni.$u.http.post('您的接口', httpData).then(res => {
                    setTimeout(() => {
                        // 自动静默登录失败--打开手动登录
                        that.isLoading = false
                    }, 500)
                    // }).catch(()=>{
                    //     // 自动静默登录失败--打开手动登录
                    //     that.isLoading = false
                    // })
                }
            })
        },
        //验证码按钮文字状态
        getCodeState() {
            const _this = this;
            this.readonly = true;
            this.codeText = '60S后重新获取';
            var s = 60;
            clear = setInterval(() => {
                s--;
                _this.codeText = s + 'S后重新获取';
                if (s <= 0) {
                    clearInterval(clear);
                    _this.codeText = '获取验证码';
                    _this.readonly = false;
                }
            }, 1000);
        },
        //获取验证码
        getVcode() {
            console.log('getVcode')
            if (this.readonly) {
                uni.showToast({
                    title: '验证码已发送~',
                    icon: 'none'
                });
                return;
            }
            if (this.phone == '') {
                uni.showToast({
                    title: '请输入手机号~',
                    icon: 'none'
                });
                return;
            }
            const phoneRegular = /^1\d{10}$/;
            if (!phoneRegular.test(this.phone)) {
                uni.showToast({
                    title: '手机号格式不正确~',
                    icon: 'none'
                });
                return;
            }
            let httpData = {}
            // 获取验证码接口
            // uni.$u.http.post('您的接口', httpData).then(res => {
            this.getCodeState(); //开始倒计时
            // })
        },
        // 手机号登录
        onSubmit() {
            if (this.phone == '') {
                uni.showToast({
                    title: '请输入手机号~',
                    icon: 'none'
                });
                return;
            }
            const phoneRegular = /^1\d{10}$/;
            if (!phoneRegular.test(this.phone)) {
                uni.showToast({
                    title: '手机号格式不正确~',
                    icon: 'none'
                });
                return;
            }
            if (this.vCode == '') {
                uni.showToast({
                    title: '请输入验证码~',
                    icon: 'none'
                });
                return;
            }
            let httpData = {};
            // uni.$u.http.post('您的接口',httpData).then(res => {
            uni.showToast({
                title: '登录成功~',
                icon: 'none'
            });
            // });
        }







    }
};
</script>

<style lang="scss" scoped>
.f__login {
    padding: 48rpx 32rpx;
    border-radius: 18rpx 18rpx 0 0;
    z-index: 99;
    position: relative;

    .loginLoading {
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(255, 255, 255, .95);
        z-index: 999;
        /* #ifndef APP-NVUE */
        display: flex;
        /* #endif */
        flex-direction: row;
        justify-content: center;
        align-items: center;
    }

    .logo {
        width: 90rpx;
        height: 90rpx;
        border-radius: 18rpx;
        overflow: hidden;

        .img {
            width: 90rpx;
            height: 90rpx;
        }
    }

    .title {
        font-size: 40rpx;
        font-weight: bold;
        margin-top: 24rpx;
    }

    .text {
        font-size: 24rpx;
        color: #666;
        margin-top: 16rpx;
    }

    .loginButton {
        margin-top: 56rpx;

        .button {
            color: #fff;
            width: 100%;
            height: 92rpx;
        }

        .marginT {
            margin-top: 24rpx;
        }
    }

    .tips {
        margin-top: 24rpx;
        /* #ifndef APP-NVUE */
        display: flex;
        /* #endif */
        flex-direction: row;
        justify-content: space-between;
        align-items: center;

        .left {
            /* #ifndef APP-NVUE */
            display: flex;
            /* #endif */
            flex-direction: row;
        }

        .goBuy {
            font-size: 24rpx;
            /* margin-left: 16rpx; */
            background: none;
            /* #ifndef APP-NVUE */
            display: flex;
            /* #endif */
            flex-direction: row;
            justify-content: flex-start;
            padding: 0;
            margin: 0;
            color: #1fba1a;
        }
    }
}

.loginPhone {
    .form-row {
        position: relative;
        border-bottom: 1rpx solid #e8e8e8;
        line-height: 1;
        margin-top: 24rpx;

        .input {
            font-size: 34rpx;
            line-height: 102rpx;
            height: 94rpx;
            width: 100%;
            box-sizing: border-box;
            font-size: 30rpx;
            padding: 0;
            font-weight: bold;
        }

        .getvcode {
            font-size: 26rpx;
            height: 80rpx;
            color: #333;
            line-height: 80rpx;
            background: #eee;
            min-width: 188rpx;
            text-align: center;
            border-radius: 8rpx;
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            right: 0;
            z-index: 11;

            &.forhidden {
                background: #eee;
                color: #cccccc;
            }
        }
    }

    .submit {
        margin-top: 60rpx;
        color: #fff;
        width: 100%;
        border: none;
    }
}
</style>
