<script>
export default {
    data() {
        return {};
    },
    globalData: {
        userInfo: null,

        // ip: 'https://test.renminshitang.com.cn/daotian/api_dev',
        ip: 'https://test.renminshitang.com.cn/daotian/api_dev',

        // ip: 'http://localhost:8001',
        sessionId: '',

        header: {
            'content-type': 'application/x-www-form-urlencoded',
            appId: 'wxb0c590fd696b79be',
            'g-open-env': 'MP_MINI',
            Authorization: '',
            Cookie: ''
        },

        headers2: {
            'content-type': 'multipart/form-data',
            appId: 'wxb0c590fd696b79be',
            'g-open-env': 'MP_MINI',
            Authorization: '',
            Cookie: ''
        },

        headers: {
            'content-type': 'application/x-www-form-urlencoded',
            appId: 'wxb0c590fd696b79be',
            'g-open-env': 'MP_MINI',
            Authorization: '',
            Cookie: ''
        },

        userLoginTokenInfo: {
            tel: '',
            //用户电话
            token: '' //用户token
        },

        isLogin: false,

        //是否登录
        loginUserInfo: {
            id: '',
            userName: '',
            tel: '',
            imgSrc: ''
        },

        lng: '',
        lat: '',
        autoLoginTag: 0,

        //是否是自动登录，0否、1是
        isScanQRCodes: 0,

        //是否是扫码进来的，0否、1是
        hasUserInfo: 0,

        //是否有用户授权信息
        agencyStatus: 0,

        //是否是代理
        openId: '',

        unionid: '',
        isCommission: 0,

        //是否计算佣金，0否、1是
        user: {},

        //用户信息
        serviceInfo: {},

        // 客服电话
        version: null,

        loginKey: '',
        appId: 'wxb0c590fd696b79be',

        isEmptyCheck: function (str) {
            if (str == null || str == '' || str == 'null' || str == 'undefined' || typeof str == 'undefined') {
                return true;
            }
            return false;
        },

        isNotEmptyCheck: function (str) {
            return !this.isEmptyCheck(str);
        },

        logout: function () {
            var that = this;
            return new Promise(function (reslove, reject) {
                try {
                    uni.removeStorageSync('loginUserTokenInfo');
                    that.autoLoginTag = 0;
                    that.sessionId = '';
                    that.loginUserInfo = {};
                    that.userLoginTokenInfo = {};
                    that.headers.Cookie = '';
                    that.headers2.Cookie = '';
                    that.header.Authorization = '';
                    that.headers.Authorization = '';
                    that.headers2.Authorization = '';
                    that.isLogin = false;
                    that.hasUserInfo = 0;
                    reslove();
                } catch (e) {
                    console.log('CatchClause', e);
                    console.log('CatchClause', e);
                    console.log('退出登录失败');
                    console.log(e);
                    reject();
                }
            });
        },

        load: function (text) {
            uni.showLoading({
                title: text,
                mask: true
            });
        },

        hideLoad: function () {
            uni.hideLoading();
        },

        showTips: function (_that, msg) {
            /*_that.setData({
      popErrorMsg: msg,
      pop: 1,
    });
    setTimeout(() => {
      _that.setData({
        popErrorMsg: '',
        pop: 0,
      });
      return;
    }, 2000)*/

            uni.showToast({
                icon: 'none',
                title: msg,
                duration: 3000
            });
        },

        setLoginUserTokenInfo: function (tel, token) {
            var that = this;
            return new Promise(function (resolve, reject) {
                try {
                    that.userLoginTokenInfo.tel = tel;
                    that.userLoginTokenInfo.token = token;
                    // debugger
                    uni.setStorageSync('loginUserTokenInfo', that.userLoginTokenInfo);
                    that.appLoginByTel(resolve, reject);
                } catch (e) {
                    console.log('CatchClause', e);
                    console.log('CatchClause', e);
                    console.log('设置登录信息错误');
                    console.log(e);
                    reject();
                }
            });
        },

        appLoginByTel: function (resolve, reject) {
            var that = this;
            var channelContactId = '';
            try {
                var value = uni.getStorageSync('fromQrCodeChannelContactId');
                if (value) {
                    console.log('fromQrCodeChannelContactId：======', value);
                    channelContactId = value;
                }
            } catch (e) {
                console.log('CatchClause', e);
                console.log('CatchClause', e);
                console.log('获取缓存设置的参数错误：', e);
            }
            var agencyUserId = '';
            try {
                var value = uni.getStorageSync('storageSyncAgencyUserId');
                if (value) {
                    console.log('storageSyncAgencyUserId======', value);
                    agencyUserId = value;
                }
            } catch (e) {
                console.log('CatchClause', e);
                console.log('CatchClause', e);
                console.log('获取缓存设置的参数错误：', e);
            }
            uni.request({
                url: that.ip + '/appLoginByTelYiShouDan',
                data: {
                    tel: that.userLoginTokenInfo.tel,
                    autoLoginTag: that.autoLoginTag,
                    isScanQRCodes: that.isScanQRCodes,
                    channelContactId: channelContactId,
                    agencyUserId: agencyUserId,
                    openId: that.openId,
                    unionid: that.unionid,
                    loginKey: that.loginKey,
                    appId: that.appId
                },
                header: {
                    'content-type': 'application/json'
                },
                success: function (res) {
                    console.log(res);
                    if (res.data.status == 200) {
                        that.user = res.data.data.user;
                        // that.globalData.user.idauth = 0;
                        that.sessionId = res.data.data.sessionId;
                        that.headers.Cookie = 'JSESSIONID=' + res.data.data.sessionId;
                        that.headers2.Cookie = 'JSESSIONID=' + res.data.data.sessionId;
                        that.headers.Authorization = 'Bearer ' + res.data.data.token;
                        that.headers2.Authorization = 'Bearer ' + res.data.data.token;
                        that.agencyId = res.data.data.agencyId;
                        that.isLogin = true;
                        that.read = res.data.data.read;
                        that.userLoginTokenInfo.tel = res.data.data.tel;
                        that.userLoginTokenInfo.token = res.data.data.token;
                        that.hasUserInfo =
                            res.data.data.imgSrc != '' &&
                            res.data.data.imgSrc != null &&
                            res.data.data.imgSrc != undefined &&
                            res.data.data.nickName != '' &&
                            res.data.data.nickName != null &&
                            res.data.data.nickName != undefined
                                ? 1
                                : 0;
                        that.loginUserInfo = res.data.data;
                        uni.setStorageSync('loginUserTokenInfo', that.userLoginTokenInfo);
                        console.log('readySet');
                        uni.showToast({
                            title: '登录成功',
                            icon: 'success',
                            duration: 2000
                        });
                        that.getServiceInfo().then(() => {
                            console.log('getServiceInfo');
                        });
                        console.log('appLoginByTel+++++++++++++++++++++++++++++++++++++++++++');
                        resolve();
                    } else {
                        uni.showToast({
                            icon: 'none',
                            title: res.data.msg,
                            duration: 2000
                        });
                        reject();
                    }
                    if (that.userLoginCallback) {
                        that.userLoginCallback(res);
                    }
                    console.log('login====result=======1');
                    console.log(that);
                    console.log('login====result=======2');
                }
            });
        },

        /**
         * 获取客户经理信息
         *
         *
         */
        getServiceInfo() {
            let that = this;
            console.log('fromLogin');
            return new Promise((resolve, reject) => {
                uni.request({
                    url: that.ip + '/costumer/manager',
                    header: that.headers,
                    success(res) {
                        console.log(res);
                        if (res.data.status == 200) {
                            that.serviceInfo = res.data.data;
                            console.log(that.serviceInfo);
                            if (that.serviceInfo.workPhone) {
                                let tel = that.serviceInfo.workPhone;
                                let num1 = tel.slice(0, 3);
                                let num2 = tel.slice(3, 7);
                                let num3 = tel.slice(7, 11);
                                that.serviceInfo.tel = num1 + '-' + num2 + '-' + num3;
                                console.log(that.serviceInfo.tel);
                            }
                            resolve(true);
                        }
                    }
                });
            });
        },

        getLoginUserTokenInfo: function () {
            var that = this;
            // debugger;
            return new Promise((resloveOutter, rejectOutter) => {
                try {
                    var value = uni.getStorageSync('loginUserTokenInfo');
                    console.log(value);
                    if (value) {
                        that.userLoginTokenInfo = value;
                        // console.log(that.isNotEmptyCheck(that.globalData.userLoginTokenInfo.token));
                        if (that.isNotEmptyCheck(that.userLoginTokenInfo.token)) {
                            let token = that.userLoginTokenInfo.token;
                            that.header.Authorization = 'Bearer ' + token;
                            that.headers2.Authorization = 'Bearer ' + token;
                            that.headers.Authorization = 'Bearer ' + token;
                            console.log(that.headers);
                            uni.request({
                                url: that.ip + '/checkToken',
                                method: 'GET',
                                header: that.headers,
                                data: {
                                    loginKey: that.loginKey
                                },
                                success: function (res) {
                                    console.log(res);
                                    if (res.data.status == 200) {
                                        if (uni.getStorageSync('messageClick' + res.data.data.id)) {
                                            console.log('messageClick' + res.data.data.id);
                                        } else {
                                            uni.setStorageSync('messageClick' + res.data.data.id, false);
                                        }
                                        that.isLogin = true;
                                        that.test = 'b';
                                        that.user = res.data.data.user;
                                        // that.globalData.user.idauth = 0;

                                        that.loginUserInfo = res.data.data;
                                        console.log(that.loginUserInfo);
                                        that.getServiceInfo().then(() => {
                                            console.log('getServiceInfo');
                                        });
                                        if (that.userLoginCallback) {
                                            that.userLoginCallback(res);
                                        }
                                        let loginKeyTmp = that.loginKey;
                                        resloveOutter(loginKeyTmp);
                                    } else {
                                        //已过期
                                        that.autoLoginTag = 1;
                                        // that.appLoginByTel();
                                        // that.globalData.isLogin = false;
                                        return new Promise(function (resolve, reject) {
                                            try {
                                                that.appLoginByTel(resolve, reject);
                                            } catch (e) {
                                                console.log('CatchClause', e);
                                                console.log('CatchClause', e);
                                                console.log('设置登录信息错误');
                                                console.log(e);
                                                reject();
                                            }
                                        });
                                        rejectOutter();
                                    }
                                }
                            });
                            // console.log(that.globalData.isLogin);
                        } else if (that.isNotEmptyCheck(that.userLoginTokenInfo.tel)) {
                            that.autoLoginTag = 1;
                            // that.appLoginByTel();

                            return new Promise(function (resolve, reject) {
                                try {
                                    that.appLoginByTel(resolve, reject);
                                } catch (e) {
                                    console.log('CatchClause', e);
                                    console.log('CatchClause', e);
                                    console.log('设置登录信息错误');
                                    console.log(e);
                                    reject();
                                }
                            });
                            rejectOutter();
                        }
                    } else {
                        console.log('nologinInfo');
                        if (that.userLoginCallback) {
                            that.userLoginCallback();
                        }
                        rejectOutter();
                    }
                } catch (e) {
                    console.log('CatchClause', e);
                    console.log('CatchClause', e);
                }
            });
        },

        onTabItemTap(e) {
            console.log(123);
            console.log(e);
            let that = this;
            if (!that.isLogin) {
                //   wx.showModal({
                //     title: '提示',
                //     content: '账号尚未登录，请先登录账号',
                //     success: res => {
                //       if (res.confirm) {
                uni.navigateTo({
                    url: '/pages/login/login'
                });
                //       } else if (res.cancel) {
                //         wx.reLaunch({
                //           url: '/pages/main/homePage'
                //         })
                //       }
                //     }
                //   })
            }
        },

        dialog: function (title, content, btxt) {
            uni.showModal({
                title: title,
                content: content,
                showCancel: false,
                confirmColor: '#0dcc91',
                confirmText: btxt,
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        },

        agencyId: '',
        read: '',
        test: ''
    },
    // "permission": {
    //   "scope.userLocation": {
    //     "desc": "你的位置信息将用于小程序位置接口的效果展示"
    //   }
    // },
    onLaunch() {
        let that = this;
        const envVersion = uni.getAccountInfoSync().miniProgram.envVersion;
        // export let baseUrl =  ""
        // 判断当前环境

        console.log(envVersion);
        if (envVersion === 'develop') {
            console.log('当前是开发环境');
            that.globalData.ip = 'https://test.renminshitang.com.cn/daotian/api_dev';
            that.globalData.agencyId = '2743';
            // that.globalData.ip = 'https://daotian.matripe.com.cn'
        } else if (envVersion === 'trial') {
            console.log('当前是体验环境');
            that.globalData.ip = 'https://test.renminshitang.com.cn/daotian/api_dev';
            that.globalData.agencyId = '2743';
        } else if (envVersion === 'release') {
            console.log('当前是正式环境');
            that.globalData.ip = 'https://daotian.matripe.com.cn';
            that.globalData.agencyId = '3087';
            // baseUrl = "https://test.renminshitang.com.cn/zhuchangtong/api_dev"
        }
        uni.hideShareMenu();
        Array.prototype.logResult = function (data) {
            console.log('Array');
            return data;
        };
        const updateManager = uni.getUpdateManager();
        updateManager.onCheckForUpdate(function (res) {
            console.log('onCheckForUpdate====', res);
            // 请求完新版本信息的回调
            if (res.hasUpdate) {
                console.log('res.hasUpdate====');
                updateManager.onUpdateReady(function () {
                    uni.showModal({
                        title: '更新提示',
                        content: '新版本已经准备好，是否重启应用？',
                        confirmColor: '#ff4400',
                        success: function (res) {
                            console.log('success====', res);
                            // res: {errMsg: "showModal: ok", cancel: false, confirm: true}
                            if (res.confirm) {
                                // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
                                updateManager.applyUpdate();
                            }
                        }
                    });
                });
                updateManager.onUpdateFailed(function () {
                    // 新的版本下载失败
                    uni.showModal({
                        title: '已经有新版本了哟~',
                        content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
                        confirmColor: '#ff4400'
                    });
                });
            }
        });
        // 获取小程序版本
        const miniProgram = uni.getAccountInfoSync();
        console.log(miniProgram);
        this.globalData.version = miniProgram.miniProgram.version || '1.1.1';
        that.globalData.getServiceInfo().then(() => {
            console.log('getServiceInfo');
        });

        // 展示本地存储能力
        const { statusBarHeight, platform } = uni.getSystemInfoSync();
        const { top, height } = uni.getMenuButtonBoundingClientRect();
        console.log(statusBarHeight);
        console.log(uni.getMenuButtonBoundingClientRect());
        console.log(top, height);
        // 状态栏高度
        uni.setStorageSync('statusBarHeight', statusBarHeight);
        // 胶囊按钮高度 一般是32 如果获取不到就使用32
        uni.setStorageSync('menuButtonHeight', height ? height : 32);
        // 胶囊按钮信息
        uni.setStorageSync('menuButtonInfo', uni.getMenuButtonBoundingClientRect());

        // 判断胶囊按钮信息是否成功获取
        if (top && top !== 0 && height && height !== 0) {
            const navigationBarHeight = (top - statusBarHeight) * 2 + height;
            // 导航栏高度
            uni.setStorageSync('navigationBarHeight', navigationBarHeight);
        } else {
            uni.setStorageSync('navigationBarHeight', platform === 'android' ? 48 : 40);
        }
        const logs = uni.getStorageSync('logs') || [];
        logs.unshift(Date.now());
        uni.setStorageSync('logs', logs);
        this.globalData.getLoginUserTokenInfo();

        // 登录
        uni.login({
            success: (res) => {
                // 发送 res.code 到后台换取 openId, sessionKey, unionId
                // this.appLoginByTel()
            }
        });
        // 引入云开发
        // wx.cloud.init({
        // 	env: "cloud1-2gnvowo5e7ab00ec",
        // });
    }
};
</script>
<style>
@import './app.css';
</style>
