// pages/login/login.js
var app = getApp();
const util = require('../../utils/util.js');
const WebIM = require("../../utils/WebIM")["default"];
const CusBase64 = require('../../utils/base64.js');

Page({
    /**
     * 页面的初始数据
     */
    data: {
        imgPath: app.globalData.imgPath,
        phone: '',
        vCode: '',
        sendText: '发送验证码',
        timer: null,
        disabled: false,
        grant_type: "password",
        longitude: null,
        latitude: null,
        showPwd: false,
        loginType: '密码登录'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //清空聊天记录
        wx.getStorageInfo({
            success: (res) => {
                let storageKeys = res.keys;
                let myName = wx.getStorageSync('myUsername');
                storageKeys.forEach((item) => {
                    // console.info(item);
                    if (myName && item.indexOf(myName) >= 0) {
                        wx.removeStorageSync(item);
                    }
                });
            },
        });

        //获取页面栈
        let pages = getCurrentPages();
        if (pages.length > 1) {
            wx.reLaunch({
                url: '../login/login',
            });
        }

        if (options && options.scene) {
            util.get({
                url: '/api/wechat/getQrCodeParams?key=' + options.scene,
                success: (res) => {
                    console.info(res);
                    if (res.data.code != 200) {
                        wx.hideLoading();
                        util.toast(res.data.msg);
                    } else {
                        // 扫码加群
                        if ('GROUP' == res.data.data.type) {
                            wx.hideLoading();
                            wx.setStorageSync('groupId', res.data.data.groupId);
                            if (!wx.getStorageSync('Authorization')) {
                                wx.showModal({
                                    content: '您需要先登录，才可加入群聊',
                                    showCancel: false
                                });
                            }
                        }
                        // 扫码连接WIFI
                        else if ('WIFI' == res.data.data.type) {
                            let wifi = res.data.data.wifi;
                            let password = res.data.data.password;
                            this.connectWifi(wifi, password);
                        }
                    }
                }
            });
        }
    },

    /**
     * 手机号赋值
     */
    setPhone: function (e) {
        this.setData({
            phone: e.detail.value
        });
    },

    /**
     * 验证码赋值
     */
    setVcode: function (e) {
        this.setData({
            vCode: e.detail.value
        });
    },

    /**
     * 获取验证码
     */
    getVerifyCode: function () {
        let that = this;
        let disabled = that.data.disabled;
        if (disabled) {
            return;
        }
        let phone = that.data.phone;
        if (!phone) {
            util.toast('请输入手机号', 'error');
            return false;
        }
        let reg = /1[3-9]\d{9}/;
        if (!reg.test(phone)) {
            util.toast('手机号格式有误', 'error');
            return false;
        }
        if (!that.data.longitude || !that.data.latitude) {
            that.getUserLocation(() => {
                that.sendMessage();
            });
            return false;
        }

        that.sendMessage();
    },

    /**
     * 发送短信验证码
     */
    sendMessage() {
        let that = this;
        that.setData({
            sendText: '60s后再次发送',
            disabled: true
        });
        // 再次发送短信时间倒计时
        that.timeTask();

        util.post({
            url: '/api/sms/sendSms/' + that.data.phone + '/' + that.data.longitude + '/' + that.data.latitude,
            success: (res) => {
                wx.hideLoading();
                //console.info(res);
                if (res.data.code != 200) {
                    util.toast(res.data.msg);
                    clearInterval(that.data.timer);
                    that.setData({
                        sendText: '发送验证码',
                        disabled: false
                    });
                } else {
                    util.toast(res.data.msg);
                }
            },
        });
    },

    /**
     * 60s倒计时定时器
     */
    timeTask: function () {
        let that = this;
        let i = 60;
        let timer = setInterval(function () {
            i--;
            if (i < 1) {
                that.setData({
                    sendText: '发送验证码',
                    disabled: false
                });
                clearInterval(timer);
            } else {
                that.setData({
                    sendText: i + 's后再次发送'
                });
            }
        }, 1000);
        that.setData({
            timer: timer
        });
    },

    /**
     * 登录系统
     */
    loginSys: function (e) {
        let that = this;
        let values = e.detail.value;
        if (!values.phone) {
            util.toast('请输入手机号', 'error');
            return false;
        }
        let reg = /1[3-9]\d{9}/;
        if (!reg.test(values.phone)) {
            util.toast('手机号格式有误', 'error');
            return false;
        }
        if (!values.code) {
            util.toast('请输入验证码', 'error');
            return false;
        }
        values.type = 'CAPTCHA';


        if (!that.data.longitude || !that.data.latitude) {
            that.getUserLocation(() => {
                values.longitude = that.data.longitude;
                values.latitude = that.data.latitude;
                that.login(values);
            });
            return false;
        }

        values.longitude = that.data.longitude;
        values.latitude = that.data.latitude;
        that.login(values);
    },

    /**
     * 登录
     * @param {*} datas 
     */
    login: function (datas) {
        let that = this;
        util.post({
            url: '/login/mobile',
            header: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            data: datas,
            success: (res) => {
                wx.hideLoading();
                if (res.data.code != 200) {
                    util.toast(res.data.msg);
                } else {
                    wx.setStorageSync('Authorization', res.data.data.Authorization);
                    that.getUserInfo();
                }
            }
        });
    },

    /**
     * 登录验证通过后获取用户信息和角色信息
     */
    getUserInfo: function () {
        let that = this;
        util.get({
            url: '/sys/userInfoAndRole',
            success: (res) => {
                wx.hideLoading();
                if (res.data.code != 200) {
                    util.toast(res.data.msg);
                } else {
                    let datas = res.data.data;
                    wx.setStorageSync('userInfo', datas);
                    wx.setStorageSync('roleInfo', datas.roleList[0]);
                    wx.setStorageSync('myUsername', datas.phone);
                    app.conn.open({
                        // apiUrl: WebIM.config.apiURL,
                        user: datas.phone,
                        pwd: CusBase64.CusBASE64.encoder(datas.phone),
                        grant_type: that.data.grant_type,
                        appKey: WebIM.config.appkey
                    });
                }
            }
        });
    },

    /**
     * 微信获取手机号快捷登录
     */
    getPhoneNumber: function (res) {
        let that = this;
        if (res.detail.errMsg == 'getPhoneNumber:ok') {
            if (!res.detail.code) {
                util.toast('请升级微信版本');
                return;
            }
        } else {
            wx.showModal({
                content: '您拒绝了授权，将无法进入小程序，请授权之后再进入!!!',
                showCancel: false,
                confirmText: '返回授权'
            });
            return;
        }

        if (!that.data.longitude || !that.data.latitude) {
            that.getUserLocation(() => {
                that.login({
                    code: res.detail.code,
                    type: 'QUICK',
                    longitude: that.data.longitude,
                    latitude: that.data.latitude,
                });
            });
            return false;
        }

        that.login({
            code: res.detail.code,
            type: 'QUICK',
            longitude: that.data.longitude,
            latitude: that.data.latitude,
        });
    },

    /**
     * 清理本地数据缓存
     */
    cleanWxStorage: function () {
        wx.clearStorage({
            success: (res) => {
                console.info('清理本地数据缓存', res);
            },
        });
    },

    /**
     * 获取用户当前定位
     */
    getUserLocation: function (callBack) {
        let that = this;
        wx.getSetting({
            success: (res) => {
                console.info('getSetting', res);
                if (res.authSetting['scope.userLocation'] == undefined) {
                    wx.authorize({
                        scope: 'scope.userLocation',
                        success: (res) => {
                            console.info(res);
                            that.getLocation(callBack);
                        },
                        fail: (err) => {
                            console.info(err);
                        }
                    });
                } else if (res.authSetting['scope.userLocation'] == true) {
                    that.getLocation(callBack);
                } else {
                    wx.showModal({
                        content: '请开启相关权限,以便更好地体验小程序',
                        success: (res) => {
                            if (res.confirm) {
                                wx.openSetting({
                                    success: (res) => {
                                        console.info('openSetting', res.authSetting)
                                        if (res.authSetting['scope.userLocation']) {
                                            util.toast('授权成功');
                                            that.getLocation(callBack);
                                        } else {
                                            util.toast('用户未授权');
                                        }
                                    }
                                });
                            }
                        }
                    });
                }
            }
        });
    },

    /**
     * 获取定位坐标
     */
    getLocation: function (callBack) {
        let that = this;
        wx.getLocation({
            type: 'gcj02',
            success: function (res) {
                console.info('getLocation', res);
                that.setData({
                    latitude: res.latitude,
                    longitude: res.longitude
                });
                callBack();
            }
        });
    },

    /**
     * 连接WIFI
     */
    connectWifi: function (wifi, password) {
        // 获取设备系统类型
        wx.getSystemInfo({
            success: (res) => {
                console.info(res);
                if (!res.wifiEnabled) {
                    wx.hideLoading();
                    util.toast('请打开WIFI功能');
                    return;
                }
                // 1、初始化Wi-Fi模块
                wx.startWifi({
                    success: (res) => {
                        console.info('startWifi', res);
                        if (res.errMsg == 'startWifi:ok') {
                            // 4、连接Wi-Fi
                            wx.connectWifi({
                                SSID: wifi,
                                password: password,
                                success: (res) => {
                                    wx.hideLoading();
                                    console.info('connectWifi', res);
                                    if (res.errMsg == 'connectWifi:ok') {
                                        util.toast('WIFI连接成功', 'success');
                                    } else {
                                        util.toast(res.errMsg);
                                    }
                                },
                                fail: (e) => {
                                    wx.hideLoading();
                                    console.info(e);
                                    util.toast('WIFI连接失败');
                                }
                            });
                        } else {
                            wx.hideLoading();
                            util.toast(res.errMsg);
                        }
                    },
                    fail: (e) => {
                        wx.hideLoading();
                        console.info(e);
                        util.toast('初始化WiFi模块失败');
                    }
                });
            },
            fail: (e) => {
                wx.hideLoading();
                util.toast('获取设备系统类型失败');
            }
        });
    },

    /**
     * 点击切换登录方式
     */
    changeType: function () {
        let f = this.data.showPwd;
        if (f) {
            this.setData({
                showPwd: false,
                loginType: '密码登录'
            });
        } else {
            this.setData({
                showPwd: true,
                loginType: '验证码登录'
            });
        }
    }

})