var t = require("setting.js"), o = require("./utils/auth.js"), a = require("./utils/request.js"), e = require("./utils/common.js"), ut = require("./utils/util.js");
var os = t;
var regeneratorRuntime = require('./utils/runtime.js');
var api = require("./api/api.js");
var wxlog = require("./utils/wxlog.js");
var md5 = require("./utils/md5.min.js");


//公共方法和变量
App({

    def_list: [
        {
            "weappurl": "pages/index/index/index",
            "nav_name": "首页",
            "src": t.imghost + "/miniapp/images/bar/index.png",
            "src_sele": t.imghost + "/miniapp/images/bar/index_on.png",
        },
        {
            "weappurl": "pages/goods/categoryList/categoryList",
            "nav_name": "分类",
            "src": t.imghost + "/miniapp/images/bar/fl.png",
            "src_sele": t.imghost + "/miniapp/images/bar/fl_on.png"
        },
        {
            "weappurl": "pages/distribution/distribution",
            "nav_name": "分销",
            "src": t.imghost + "/miniapp/images/bar/fx.png",
            "src_sele": t.imghost + "/miniapp/images/bar/fx_on.png"
        },
        {
            "weappurl": "pages/cart/cart/cart",
            "nav_name": "购物车",
            "src": t.imghost + "/miniapp/images/bar/car.png",
            "src_sele": t.imghost + "/miniapp/images/bar/car_on.png"
        },
        {
            "weappurl": "pages/user/index/index",
            "nav_name": "我的",
            "src": t.imghost + "/miniapp/images/bar/user.png",
            "src_sele": t.imghost + "/miniapp/images/bar/user_on.png"
        }
    ],


    globalData: {
        cartGoodsNum: 0,       //购物车总数量
        isTabBar: false,
        isIpx: false,   //适配IPhoneX
        url: "",
        setting: t,
        wechatUser: null,
        userInfo: null,
        config: null,   //门店参数
        config2: null,  //门店配置
        code: null,
        user_id:null, //6520509,//6520491,// 6519913,//6520352
        // user_id:6520314,// qa-6519858,//
        // user_id:14148118,// qa-6519858,//
        buy_now: null,
        picklist: null,    //门店列表
        wuliuprice: null, //物流价格表
        wuliu: null,      //物流公司
        baddr: null,
        mobile: null,    //记录手机
        getu: null,       //记录会员信息
        sessionKey: null,//记录会员信息
        openid: null,    //记录会员信息
        to_group: null,      //参团传递的数据
        wxapp_buy_obj: null, //微信小程序购买的Object
        pk_store: null,      //选择的门店
        first_leader: null,  //分享会员ID
        guide_id: null,      //分享导购ID
        windowWidth: 0,        //整个窗体的宽度
        room_id: null,        //直播间分享的房间ID
        room_goods_id: null,  //直播间分享的商品ID
        fail_url: new Map(),
        sp_scene: null,

        navBarHeight:44,    //默认高度44
        is_pc:0,            //是不是在pc端打开小程序
        is_get_login:0
    },
    auth: o,
    request: a,
    onLaunch: function (option) {
       
        //初始化美图测肤插件
        // var plugin = requirePlugin('mtSkinSdk');
        // params.login_id = wx.getStorageSync('login_id') || '' // 可将登录id缓存下来，方便下次进入小程序直接获取
        // plugin.setConfig(pluginGD)
        if(option) this.globalData.scene=option.scene;
        console.log(option,'登陆场景');

        // wx.hideTabBar();
        this.initExt();
        // this.overShare()

        //检查更新
        this.checkUpdateVersion();

        wx.removeStorageSync('ukey');
        wx.removeStorageSync('api_token');

        var t = this.globalData.setting;
        //console.log(t)
        t.resourceUrl = t.url + "/template/mobile/rainbow";
        var clientWidth = wx.getSystemInfoSync().windowWidth;
        var rpxR = 750 / clientWidth;
        var calc = wx.getSystemInfoSync().windowHeight * rpxR;
        this.globalData.heigth = calc;
        this.globalData.windowWidth = clientWidth;

        var app = this;
        if (!app.globalData.userInfo) {
            // var user = wx.getStorageSync("userinfo");
            // if (user && user.user_id) {
            //
            //     //--生成会员 --
            //     app.promiseGet("/api/weshop/users/get/" + user.store_id + "/" + user.user_id, {}).then(res => {
            //
            //         app.globalData.is_get_login=1;
            //
            //         if (res.data.code == 0) {
            //
            //             user = res.data.data;
            //             //-- 小程序会员被解绑了,就要清空会员 --
            //             if (user['is_weappuser'] == 0) {
            //                 user = null;
            //                 app.globalData.userInfo = null;
            //                 app.globalData.user_id = 0;
            //             } else {
            //                 app.globalData.userInfo = user;
            //                 app.globalData.user_id = user.user_id;
            //
            //                 //调用接口判断是不是会员
            //                 app.promiseGet("/api/weshop/shoppingGuide/get/" + os.stoid + "/" + user.user_id, {}).then(res => {
            //                     if (res.data.code == 0) {
            //                         getApp().globalData.guide_id = res.data.data.id;
            //                     }
            //                 })
            //                 app.promiseGet("/api/weshop/users/getAndUpdateUser/" +user.store_id + "/" + user.user_id, {})
            //
            //             }
            //             wx.setStorageSync("userinfo", user);
            //         } else {
            //             user = null;
            //             app.globalData.userInfo = null;
            //             app.globalData.user_id = 0;
            //             wx.setStorageSync("userinfo", null);
            //         }
            //     })
            // }
            // if(app.globalData.user_id){  //-- 启用默认的user_id --
            //
            //     app.promiseGet("/api/weshop/users/get/" + app.globalData.setting.stoid + "/" + app.globalData.user_id,{}).then(res=>{
            //         app.globalData.is_get_login=1;
            //         if(res.data.code==0){
            //             app.globalData.userInfo = res.data.data;
            //             wx.setStorageSync("userinfo",app.globalData.userInfo);
            //             //刷一下导购
            //             app.promiseGet("/api/weshop/users/getAndUpdateUser/" +app.globalData.setting.stoid + "/" + app.globalData.user_id, {})
            //             //调用接口判断是不是会员
            //             app.promiseGet("/api/weshop/shoppingGuide/get/" + os.stoid + "/" + res.data.data.user_id, {}).then(rs => {
            //                 if (rs.data.code == 0) {
            //                     app.globalData.guide_id = rs.data.data.id;
            //                     app.globalData.guide_pick_id = rs.data.data.pickup_id
            //                 }
            //             })
            //         }
            //     })
            // }
            // else {
                 //--拿下code--
                 wx.login({
                    success: function (o) {
                        var dd = {
                            js_code: o.code,
                            store_id: os.stoid,
                        };
                        //-- 导购会员ID --
                        if (app.globalData.guide_id) {
                            dd.guide_id = app.globalData.guide_id;
                        }

                        app.request.get("/api/weshop/users/openidandkey", {
                            data: dd,
                            success: function (e) {
                                //说明会员是有wx.login运行拿了一下是不是会员
                                app.globalData.is_get_login=1;

                                if (e.data.code == 0) {
                                    //如果有会员的话,没有sessionKey
                                    if (!e.data.data.sessionKey) {
                                        // getApp().showWarning("登录成功");

                                        app.globalData.userInfo = e.data.data;
                                        app.globalData.user_id = e.data.data.user_id;
                                        app.globalData.openid = e.data.data.weapp_openid;
                                        //把会员的信息存在内存
                                        wx.setStorageSync("userinfo", e.data.data);
                                        //刷一下导购
                                        app.promiseGet("/api/weshop/users/getAndUpdateUser/" +app.globalData.setting.stoid + "/" + app.globalData.user_id, {})
                                        //调用接口判断是不是会员
                                        app.promiseGet("/api/weshop/shoppingGuide/get/" + os.stoid + "/" + e.data.data.user_id, {}).then(res => {
                                            if (res.data.code == 0) {
                                       
                                                app.globalData.guide_id = res.data.data.id;
                                                app.globalData.guide_pick_id = res.data.data.pickup_id;
                                               
                                               
                                            }
                                        })


                                    }
                                }
                            }
                        })
                    }
                })
            //}
        }

        wx.getSystemInfo({
            success: (res) => {
                // console.log(res)
                let modelmes = res ? res.model : null; //手机品牌
                console.log('手机品牌', modelmes)
                if (modelmes && modelmes.indexOf('iPhone X') != -1) {　　//XS,XR,XS MAX均可以适配,因为indexOf()会将包含'iPhone X'的字段都查出来
                    this.globalData.isIpx = true
                }

                if (res["platform"].toLowerCase()=== 'ios') {
                    this.globalData.is_iPhone=1;
                }

                /*-- 判断是不是PC端打开的 */
                if (res && ["windows", "mac"].some((v) => v === res["platform"])) {
                    app.globalData.is_pc=1;
                    this.globalData.navBarHeight =0
                }else{
                    this.globalData.navBarHeight = 44 + res.statusBarHeight
                }


            },
        })
        this.globalData.menuInfo = wx.getMenuButtonBoundingClientRect() || {}

        var th = this;
        var pages = getCurrentPages();             //获取加载的页面
        var currentPage = pages[pages.length - 1];  //获取当前页面的对象

        if (!th.globalData.wxapp_buy_obj) {
            var turl = "/api/weshop/storeconfig/get/" + th.globalData.setting.stoid;
            th.promiseGet(turl, {}).then(res => {
                var o = res;
                if (o.data.code == 0) {
                    th.globalData.config2 = o.data.data;
                    //有配置成要验证过期，因为过期的小程序没有办法审核
                    if (th.globalData.config2 && th.globalData.config2.is_overdue) {

                        //要开始验证，小程序有没有购买和过期
                        if (!currentPage || currentPage.route.indexOf('error/error') == -1 || currentPage.route.indexOf('index/index') == -1) {
                            var tt = this.globalData.wxapp_buy_obj;
                            if (!tt) {
                                this.get_isbuy(function () {
                                    tt = th.globalData.wxapp_buy_obj;
                                    if (tt && tt.isout == 1) {
                                        th.promiseGet('/api/weshop/store/get/' + t.stoid, {}).then(res => {

                                            if (!th.err_going) {
                                                wx.reLaunch({
                                                    url: "/packageD/pages/error/error?msg=该商城已到期，暂停浏览1！\r\n可联系:" + res.data.data.store_tel,
                                                });
                                            }
                                        })
                                    }
                                    else if (tt && tt.isbuy == 0) {

                                        if (!th.err_going) {
                                            wx.reLaunch({
                                                url: "/packageD/pages/error/error?msg=还未购买小程序",
                                            });
                                        }

                                    }

                                })
                            }
                        }
                    }
                }
            })

        }
        else {
            var tt = th.globalData.wxapp_buy_obj;
            if (tt && tt.isout == 1) {
                th.promiseGet('/api/weshop/store/get/' + t.stoid, {}).then(res => {
                    if (!th.err_going) {
                        wx.reLaunch({
                            url: "/packageD/pages/error/error?msg=该商城已到期，暂停浏览1！\r\n可联系:" + res.data.data.store_tel,
                        });
                    }
                })
            }
            else if (tt && tt.isbuy == 0) {
                if (!th.err_going) {
                    wx.reLaunch({
                        url: "/packageD/pages/error/error?msg=还未购买小程序",
                    });
                }

            }
        }

        //获取一下门店的基本信息
        this.getConfig();

        //获取视频号场景
        if(!this.globalData.sp_scene) {
            var th = this;
            var turl = "/api/weshop/manager/managerConfig/get";
            this.promiseGet(turl, {}).then(res => {
                if (res.data.code == 0) {
                    th.globalData.sp_scene = res.data.data.weapp_scenelist;
                }
            })
        }

    },

    //获取订阅消息模板id
    async get_template_id(id){
    if (!id) { return ''}
    let os = this.globalData.setting;
    let res = await this.promiseGet("/api/wx/weappSendlist/page", {
      data: {
        store_id: os.stoid,
        typeids: id
      }
    })
    let resdata = res.data.data.pageData
    if (res.data.code == 0 && resdata.length > 0) {
      let template_id = []
      // let template_id = res.data.data.pageData[0].template_id;
      try {
        resdata.map(item=>{
          template_id.push(item.template_id)
        })
      } catch (error) {}
      return template_id
    }else{
      return []
    }
  },

    //---初始化第三方----
    initExt: function () {
        var tt = t;
        console.log("initExt");
        console.log(11);
        var t = wx.getExtConfigSync(), o = this.globalData.setting;
        console.log(t);
        t.appName ? (o.appName = t.appName, o.stoid = t.stoid) : tt = 1;

    },

    //首页的第一次登录
    getUserFir(t) {
        var s = this;
        if (o.isAuth()) {
            "function" == typeof t && t(s.globalData.userInfo, s.globalData.wechatUser);
        } else {
            if (!o.isAuth()) return o.wxLogin_fir(t);
            if (null == s.globalData.userInfo) {
                return o.wxLogin_fir(t);
            }
        }
    },

    getUserInfo: function (t, n, i) {
        var s = this;
        if (o.isAuth()) "function" == typeof t && t(s.globalData.userInfo, s.globalData.wechatUser); else {
            if (!o.isAuth()) return o.auth(t);
            if (null == s.globalData.userInfo) {
                return o.auth(t);
            }
        }
    },
    //----------------获取配置参数--------------------
    getConfig: function (t, o) {
        var e = this;
        if (!e.globalData.setting.stoid) {
            t(null);
            return false;
        }
        if (this.globalData.config == undefined) this.globalData.config = null;
        this.globalData.config ? "function" == typeof t && t(this.globalData.config) : e.requestGet("/api/weshop/store/get/" + e.globalData.setting.stoid, {
            success: function (o) {
                console.log('getConfig', o);
                if (o.data.code == 0) {
                    e.globalData.config = o.data.data, "function" == typeof t && t(e.globalData.config);
                }
            }
        });
    },
    //----------------获取配置参数--------------------
    getConfig2: function (t, o) {
        var e = this;
        if (!e.globalData.setting.stoid) {
            t(null);
            return false;
        }
        this.globalData.config2 && !o ?
            "function" == typeof t && t(this.globalData.config2) : a.get("/api/weshop/storeconfig/get/" + e.globalData.setting.stoid, {
                success: function (o) {
                    console.log('getConfig2');
                    if (o.data.code == 0) {
                        e.globalData.config2 = o.data.data, "function" == typeof t && t(e.globalData.config2);
                    }
                }
            });
    },

    //----------------获取商家开启的物流--------------------
    getwuliu: function (t, o) {
        this.globalData.wuliu = null;
        var th = this, st = this.globalData.setting;
        //获取物流不缓存
        a.get("/api/weshop/storeshipping/list", {
            data: { store_id: st.stoid, status: 1, pageSize: 2000 },
            success: function (o) {
                console.log('getwuliu');
                console.log(o);
                if (o.data.code == 0 && o.data.data && o.data.data.pageData && o.data.data.pageData.length > 0) {
                    var arr = o.data.data.pageData;
                    console.log(arr);
                    arr.forEach(function (item, index) {
                        arr[index].code = item.shipping_code; arr[index].name = item.shipping_name;
                    })
                    th.globalData.wuliu = arr, "function" == typeof t && t(arr);
                }
            }
        });
    },

    //----------------获取物流价格表--------------------
    getwuliuprice: function (t, o) {
        var e = this, th = e, st = this.globalData.setting;
        //获取物流不缓存
        a.get("/api/weshop/shippingarea/list", {
            data: { store_id: st.stoid, pageSize: 2000 },
            success: function (o) {
                console.log('getwuliuprice');
                console.log(o);
                if (o.data.code == 0) {
                    var arr = o.data.data.pageData;
                    console.log(arr);
                    if (arr.length > 0) {
                        for (var i = 0; i < arr.length; i++) {
                            arr[i].code = arr[i].shipping_code;
                            if (arr[i].json_config != "" && arr[i].json_config != undefined && arr[i].json_config != null)
                                arr[i].config = JSON.parse(arr[i].json_config);
                        }
                    }
                    th.globalData.wuliuprice = o.data.data, "function" == typeof t && t(e.globalData.wuliuprice);
                }
            }
        });
    },
    //----------------设置立即购买数组--------------------
    set_b_now: function (d) { this.globalData.buy_now = d; },
    get_b_now: function () { return this.globalData.buy_now },

    getPrevPageData: function (t) {
        void 0 === t && (t = 1);
        var o = getCurrentPages();
        return o[o.length - t - 1].data;
    },
    showLoading: function (t, o) {
        void 0 === o && (o = 1500), wx.showToast({
            title: "加载中",
            icon: "loading",
            duration: o,
            mask: !0,
            complete: function () {
                "function" == typeof t && setTimeout(t, o);
            }
        });
    },
    showSuccess: function (t, o, a) {
        void 0 === a && (a = 1e3), wx.showToast({
            title: t,
            icon: "success",
            duration: a,
            mask: !0,
            complete: function () {
                "function" == typeof o && setTimeout(o, a);
            }
        });
    },
    showWarning: function (t, o, a, e) {
        !a && (a = 1500), void 0 === e && (e = !0), wx.showToast({
            title: t,
            mask: e,
            duration: a,
            icon: 'error',
            // image: "/images/gt.png",
            complete: function () {
                "function" == typeof o && setTimeout(o, a);
            }
        });
    },

    confirmBox: function (t, o) {
        wx.showModal({
            title: t,
            showCancel: !1,
            complete: function () {
                "function" == typeof o && o();
            }
        });
    },

    //----------获取所有的门店------------
    get_allsto(func) {
        var th = this;
        if (this.globalData.picklist != null) {
            "function" == typeof func && func(th.globalData.picklist);
        } else {
            th.request.get("/api/weshop/pickup/page", {
                data: { store_id: th.globalData.setting.stoid, pageSize: 600 },
                success: function (da) {
                    //设置门店
                    //th.setData({ allsto: da.data.data.pageData });
                    th.globalData.picklist = da.data.data.pageData;
                    "function" == typeof func && func(th.globalData.picklist);
                }
            })
       }
    },

    //同步化，在调用的时候要await
    async get_isbuy(func) {
        var th = this
        var stoid = os.stoid;

        await this.promiseGet("/store/storemoduleendtime/page?store_id=" + stoid + "&type=5", {}).then(res => {
            var o = res;
            if (o.data.code == 0) {
                var ob = { isout: 0, isbuy: 1 };
                var arr = o.data.data.pageData;
                var isbuy = 0;
                //----如果数组不为空----
                if (arr.length > 0) {
                    arr.forEach(function (val, ind) {
                        if (val.is_sy == 0 && val.type == 5) {
                            isbuy = 1;
                            var now = ut.gettimestamp();
                            if (now > val.end_time) ob.isout = 1;
                            return false;
                        }
                    })
                }
                ob.isbuy = isbuy;
                th.globalData.wxapp_buy_obj = ob;
                if (func) {
                    func();
                }
            }
        })
    },
    //获取场景值 判断是否是单页面
    is_Single_page(_this, func) {
        let scene = wx.getLaunchOptionsSync().scene;
        //--判断是否是单页面--
        if (scene !== 1154) {
            typeof func == "function" && func.bind(_this)();
        } else {
            return false;
        }
        // return  scene == 1154? false:true;
    },


    //--同步化，在调用的时候要await,获取商家config--
    async getConfig_ays() {
        if (this.globalData.config != null) return false;
        var th = this;
        await api.get_config(this.globalData.setting.stoid).then(res => {
            var o = res;
            if (o.data.code == 0) {
                th.globalData.config = o.data.data;
            }
        })
    },

    //----智能跳转，判断 非tabBar,tabBar页面的跳转----
    goto: function (url) {
        var arr = getCurrentPages();
        if (arr.length > 8) {
            arr.splice(0, 2);
        }
        var arr_tabbar = ["/pages/index/index/index",
            "/pages/goods/categoryList/categoryList",
            "/pages/goods/categoryList/categoryList?type=2",
            "/pages/goods/categoryList/categoryList?type=1",
            "/pages/cart/cart/cart", "/pages/user/index/index",
            "/pages/distribution/distribution"];

         for(var i in arr_tabbar){
              var ck_url=arr_tabbar[i];
              if (("/"+url).indexOf(ck_url) != -1) {
                  if (url.indexOf("categoryList?type=1") != -1) this.globalData.cat_type = 1;
                  if (url.indexOf("categoryList?type=2") != -1) this.globalData.cat_type = 2;
                  wx.reLaunch({ url: url, })  //跳到tabbar页
                  return;
              }
          }
        if (arr_tabbar.indexOf(url) != -1) {
            if (url.indexOf("categoryList?type=1") != -1) this.globalData.cat_type = 1;
            if (url.indexOf("categoryList?type=2") != -1) this.globalData.cat_type = 2;
            wx.reLaunch({ url: url, })  //跳到tabbar页

        } else {
            if (getCurrentPages().length > 9) {
                wx.redirectTo({ url: url, })  //跳到非tabbar页
            } else {
                wx.navigateTo({ url: url, })  //跳到tabbar页
            }
        }

    },
    re_to(url){
        wx.redirectTo({ url: url, })  //跳到非tabbar页
    },

    //显示提示，word提示内容，type 0失败，提示   1成功
    my_warnning(word, type, that, width) {
        var warn = that.selectComponent("#warn"); //组件的id
        warn.open(word, type, width);
        return 1;
    },

    //获取会员门店
    get_user_store: function (func) {
        var th = this;
        this.getConfig2(function (conf) {

            var is_pricing_open_store=0;
            var is_regstores=0;
            var is_guide_storage=0;
            if (conf.switch_list) {
                var t_swi = JSON.parse(conf.switch_list);
                //--购买门店是否默认登记门店--
                is_regstores=t_swi.is_regstores;
                is_pricing_open_store=t_swi.is_pricing_open_store;
                is_guide_storage=t_swi.is_guide_storage;
            }

            //---空会员的情况---
            if (!th.globalData.userInfo) {
                //没有导购门店 和 没有开启默认导购
                if(!th.globalData.guide_pick_id || !is_guide_storage) {
                    return func(null);
                }
            }
            if (!th.globalData.pk_store) {
                var pick_id = 0;

                //-- 如果有导购的时候，后台有默认门店只能是导购的门店的时候 --
                if(th.globalData.guide_pick_id && is_guide_storage){
                    pick_id = th.globalData.guide_pick_id
                }else {

                    //-- 如果是区域价格提现，现在注册门店是默认 --
                    if (is_pricing_open_store) {

                        //查找会员的注册的地址
                        if (th.globalData.userInfo.pickup_id) {
                            pick_id = th.globalData.userInfo.pickup_id;
                            th.globalData.is_dj_pk = 1;
                        }
                        //先找一个会员是否有设置默认的地址
                        else if (th.globalData.userInfo.def_pickup_id) {
                            pick_id = th.globalData.userInfo.def_pickup_id
                        }

                    } else {
                        //先找一个会员是否有设置默认的地址
                        if (th.globalData.userInfo.def_pickup_id) {
                            pick_id = th.globalData.userInfo.def_pickup_id
                        }
                        //查找会员的注册的地址
                        else if (th.globalData.userInfo.pickup_id && is_regstores) {
                            pick_id = th.globalData.userInfo.pickup_id
                        }
                    }
                }



                //---如果会员没有设置默认门店，同时也没有再注册的时候选择门店--
                if (pick_id == 0) return func(null);

                //返回门店的数量
                th.get_pk_num(function (num) {
                    //获取用户注册时候的门店,这个门店不能关闭，同时这个门店的分类不能关闭
                    th.request.get("/api/weshop/pickup/get/" + os.stoid + "/" + pick_id, {
                        data: {},
                        success: function (res) {
                            th.globalData.pk_store = null;
                            if (res.data.code == 0 && res.data.data && res.data.data.isstop == 0 && res.data.data.is_pos == 1) {

                                //--门店的数量大于10个才要关心门店的分类有没有关闭--
                                if (res.data.data.category_id && num > 10) {
                                    th.request.get("/api/weshop/storagecategory/get/" + os.stoid + "/" + res.data.data.category_id, {
                                        data: {},
                                        success: function (ee) {
                                            if (ee.data.code == 0 && ee.data.data) {
                                                if (ee.data.data.is_show == 1) {
                                                    th.globalData.pk_store = res.data.data;
                                                    func(th.globalData.pk_store);
                                                } else {
                                                    //看一下有没有显示的门店分类
                                                    getApp().request.get("/api/weshop/storagecategory/page", {
                                                        data: {
                                                            store_id: os.stoid,
                                                            is_show: 1,
                                                            pageSize: 1,
                                                        },
                                                        success: function (ee) {
                                                            if (ee.data.code == 0) {
                                                                if (ee.data.data && ee.data.data.pageData && ee.data.data.pageData.length > 0) {
                                                                    func(null);
                                                                } else {
                                                                    th.globalData.pk_store = res.data.data;
                                                                    func(th.globalData.pk_store);
                                                                }
                                                            } else {
                                                                th.globalData.pk_store = res.data.data;
                                                                func(th.globalData.pk_store);
                                                            }
                                                        }
                                                    })
                                                }
                                            } else {
                                                func(null);
                                            }
                                        }
                                    })
                                } else {
                                    th.globalData.pk_store = res.data.data;
                                    func(th.globalData.pk_store);
                                }
                            } else {
                                func(null);
                            }
                        }
                    })

                })

            } else {
                if(th.globalData.pk_store.is_no_dis){
                    th.globalData.pk_store.is_no_dis=0;
                }
                func(th.globalData.pk_store);
            }
        })
    },

    //-- 获取门店的数量 --
    get_pk_num: function (func) {
        this.request.get("/api/weshop/pickup/page", {
            data: { page: 1, pageSize: 1, isstop: 0, store_id: os.stoid },
            success: function (res) {
                if (res.data.code == 0) {
                    func(res.data.data.total); //门店数量
                }
            }
        });
    },
    //-------获取购物车数量----------
    requestCardNum: function (th) {
        if (!this.globalData.user_id) return false;
        var that = this;
        this.request.get("/api/weshop/cart/page", {
            isShoeLoading: false,
            data: {
                store_id: this.globalData.setting.stoid,
                user_id: this.globalData.user_id,
                state: 0,
                is_gift: 0,
                pageSize: 300
            },
            success: function (e) {
                var num = 0;
                if (e.data.data && e.data.data.pageData) {
                    for (var i = 0; i < e.data.data.pageData.length; i++) {
                        num += e.data.data.pageData[i].goods_num;
                    }
                }
                //-- 读取服务卡的数量 --
                that.promiseGet("/api/weshop/cartService/page", {
                    data: {
                        store_id: that.globalData.setting.stoid,
                        user_id: that.globalData.user_id,
                    }
                }).then(res => {

                    for (var i = 0; i < res.data.data.pageData.length; i++) {
                        num += res.data.data.pageData[i].goods_num;
                    }

                    that.globalData.cartGoodsNum = num;
                    th.data.up_dating = 0
                    th.getTabBar().setData({ cartGoodsNum: num });
                })

            }
        });
    },


    //---    最多十秒  ---
    waitfor_login(func){

        if(getApp().globalData.user_id){
            func();
        }else {
            var n = 0;
            var that=this;
            if (!this.globalData.is_get_login) {
                var inter = setInterval(function () {
                    n++;
                    if (that.globalData.is_get_login) {
                        clearInterval(inter);
                        func();
                    }
                    if (n > 80) {
                        clearInterval(inter);
                        func();
                    }
                }, 100);
            }else{
                func();
            }
        }


    },

    //------定时等待某个值,有值才进行运算--------
    waitfor: function (page, key, pop_value, func) {
        var n = 0;
        if (!page.data[key]) {
            page.data[key] = setInterval(function () {
                console.log(page.data[key]); n++;
                if (pop_value) {
                    clearInterval(page.data[key]);
                    func();
                }
                if (n > 15) clearInterval(page.data[key]);
            }, 1000);
        }
    },

    //------定时等待某个值,有值才进行运算--------
    waitfor2: function (page, key, pop_value_key, func) {
        var n = 0;
        if (!page.data[key]) {
            page.data[key] = setInterval(function () {
                console.log(page.data[key]); n++;
                if (page.data[pop_value_key] && Object.keys(page.data[pop_value_key]).length > 0) {
                    clearInterval(page.data[key]);
                    func();
                }
                if (n > 15) {
                    clearInterval(page.data[key]);
                    func();
                }
            }, 1000);
        }
    },


    //清空登录时候缓存的值
    onHide: function () {
        var th = this;
        setTimeout(function () {
            console.log("app onhide");
            console.log(th.globalData.no_clear);
            if (!th.globalData.no_clear) {
                th.globalData.is_test = 0;
                th.globalData.guide_id = null;                     //导购清空
                th.globalData.first_leader = null;                 //分享的会员清空
                th.globalData.wuliu = null;                        //关闭要把物流清空
                th.globalData.room_id = null;                      //关闭要把房间号关闭
                th.globalData.room_goods_id = null;                //关闭要把物流清空
                th.globalData.config2 = null;                      //清除config2的缓存
                th.globalData.config = null;                       //清除config的缓存
                th.globalData.gr_index = 0;                        //商品分组的序列
                th.globalData.pk_store = null;
                th.globalData.wxapp_buy_obj = null;
                th.globalData.dis_buy_obj = null;   //等级卡的购买记录
                th.globalData.storeFooter = null;   //底部的导航
                th.globalData.full_screen = null;   //全屏
                th.globalData.guide_pick_id = null;   //分享导购门店的优化
                th.globalData.fuiou_pay = null;   //分享导购门店的优化
            } else {
                th.globalData.no_clear = 0;
            }
        }, 600)

    },

    clear_word: function (word) {

        var str = word;
        let reg = /([^\u0020-\u007E\u00A0-\u00BE\u2E80-\uA4CF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFFEF\u0080-\u009F\u2000-\u201f\u2026\u2022\u20ac\r\n])|(\s)/g,
            indexArr = reg.exec(str);
        if (str.match(reg)) {
            str = str.replace(reg, '');
        }
        return str;
    },

    getPageIndex: function (curPage) {

        var pagePath = curPage.route; //当前页面url
        if (pagePath.indexOf('/') != 0) {
            pagePath = '/' + pagePath;
        }

        var index = 0;

        if (this.globalData.custum_data) {
            var itemList = this.globalData.custum_data.data;
            itemList = JSON.parse(itemList);
            for (var i in itemList) {
                var item = itemList[i]
                if (pagePath.indexOf(item.weappurl) != -1) {
                    index = i; break;
                }
            }

        } else {
            var itemList = this.def_list;
            for (var i in itemList) {
                var item = itemList[i]
                if (pagePath.indexOf(item.weappurl) != -1) {
                    index = i; break;
                }
            }
        }
        return index;

    },

        
    //---promise的使用get,data里面加一个参数，不需要默认带----
    promiseGet: function (url, data) {

        var th=this;


        if (url.indexOf("http") == -1) url = this.globalData.setting.url + url;
        return new Promise((resolve, reject) => {

        th.ck_api_token((api_tk)=>{
            data.isShowLoading && wx.showLoading();
            //增加门店id和配送方式
            //is_no_def不需要默认参数

            var url1=url;
            var arr_in_url=ut.getParams(url1);

            var header={ "content-type": "application/x-www-form-urlencoded" };
            var now=ut.gettimestamp();

            var new_data={...arr_in_url,...data.data};
            var tk=a.set_req_sign(new_data,url1,now,api_tk);
            if(tk){
            header.reqtime=now;
            header.token=tk;
            header.ukey=api_tk.userkey
            }

            wx.request({
            url,
            method: 'GET',
            header: header,
            data: data.data,
            success(res) {
                data.isShowLoading && wx.hideLoading();
                resolve(res);
            },
            fail(err) { data.isShowLoading && wx.hideLoading(); reject(err); }
            })
        })


        })
    },


    //---promise的使用get----
    requestGet: function (url, data) {

        var url1=url;
        var arr_in_url=ut.getParams(url1);
        if (url.indexOf("http") == -1) url = this.globalData.setting.url + url;

        this.ck_api_token((api_tk)=> {

        data.isShowLoading && wx.showLoading();

        var header= {"content-type": "application/x-www-form-urlencoded"};
        var now=ut.gettimestamp();

        var new_data={...arr_in_url,...data.data};
        var tk=a.set_req_sign(new_data,url1,now,api_tk);

        if(tk){
            header.reqtime=now;
            header.token=tk;
            header.ukey=api_tk.userkey
        }

        wx.request({
            url,
            method: 'GET',
            header:header,
            data: data.data,
            success(res) {
            data.isShowLoading && wx.hideLoading();
            data.success(res);
            },
            fail(err) {
            data.isShowLoading && wx.hideLoading();
            if (data.fail) data.fail(err);
            }
        })
        })
    },


    // 判断是否登录
    isLogin() {
        return new Promise(function (resolve, reject) {
            let user_info = getApp().globalData.userInfo;
            if (user_info == null || user_info.mobile == undefined || user_info.mobile == "" || user_info.mobile == null) {
                wx.navigateTo({
                    url: '/packageE/pages/togoin/togoin',
                })
                return false;
            } else {
                resolve(user_info);
            };
        });
    },


    checkUpdateVersion() {
        //判断微信版本是否 兼容小程序更新机制API的使用
        if (wx.canIUse('getUpdateManager')) {
            //创建 UpdateManager 实例
            const updateManager = wx.getUpdateManager();
            if (!updateManager || !updateManager.onCheckForUpdate) {
                return false;
            }
            //检测版本更新
            updateManager.onCheckForUpdate(function (res) {
                console.log('是否获取版本');
                // 请求完新版本信息的回调
                if (res.hasUpdate) {
                    //监听小程序有版本更新事件
                    updateManager.onUpdateReady(function () {

                        //TODO 新的版本已经下载好，调用 applyUpdate 应用新版本并重启 （ 此处进行了自动更新操作）
                        updateManager.applyUpdate();
                    })
                    updateManager.onUpdateFailed(function () {
                        // 新版本下载失败
                        wx.showModal({
                            title: '已经有新版本喽~',
                            content: '请您删除当前小程序，到微信 “发现-小程序” 页，重新搜索打开哦~',
                        })
                    })
                }
            })
        } else {
            //TODO 此时微信版本太低（一般而言版本都是支持的）
            wx.showModal({
                title: '溫馨提示',
                content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
            })
        }
    },

    //重复函数，统一调用，
    pre_img(path) {
        this.globalData.no_clear = 1;
        wx.previewImage({
            //将图片预览出来
            urls: [path]
        });
    },
    //b是数组，t是wxml元素返回的
    pre_img2(b, t) {
        this.globalData.no_clear = 1;
        wx.previewImage({
            current: b[t.currentTarget.dataset.id],
            urls: b
        });
    },



    //联系客服的3个函数
    con_wx(th){
        var url=th.data.sys_switch.weapp_customertype_url;
        var id=th.data.sys_switch.weapp_customertype_appid;
        this.globalData.no_clear=1;
        wx.openCustomerServiceChat({
            extInfo: { url: url },
            corpId: id,
            success(res) { }
        })
    },
    con_Service(){
        var th=this;
        var oss= this.globalData.setting;
        this.getConfig(function(t) {
            if (t.store_tel == undefined) {
                th.request.get("/api/weshop/store/get/" + oss.stoid, {
                    isShowLoading: 1,
                    data: {},
                    success: function (rs) {
                        th.globalData.config = rs.data.data;
                        if (rs.data.data.store_tel == null && rs.data.data.store_tel == undefined) {
                            wx.showToast({
                                title: "商家未设置电话",
                                icon: 'none',
                                duration: 3000
                            })
                            return false;
                        }
                        th.globalData.no_clear = 1;
                        wx.makePhoneCall({ phoneNumber: rs.data.data.store_tel, })
                    }
                })
            } else {
                th.globalData.no_clear = 1;
                wx.makePhoneCall({ phoneNumber: t.store_tel, })
            }
        });
    },

    user_tools_endTime(type,func) {
        //调用接口判断商家工具有没有过期
        return this.request.promiseGet("/store/storemoduleendtime/page?store_id=" + os.stoid + "&type=" + type + "", {}).then(res => {
            if (res.data.code == 0) {
                var arr = res.data.data.pageData;
                if (arr.length > 0) {
                    var item = arr[0];
                    if (item.is_sy == 0) {
                        var now = Date.parse(new Date()); now = now / 1000;
                        if (item.end_time < now) {

                           if(func){
                               func(0)
                               return false;
                           }
                           return 0
                        }
                        if(func){
                            func(1)
                            return false;
                        }

                        return 1;
                    }
                }
            }
        })
    },

    com_call(self) {
        self.getTel()
            .then(() => {
                if (self.data.store_tel) {
                    wx.showModal({
                        title: '联系客服',
                        content: '客服热线:' + self.data.store_tel,
                        confirmText: '拨打',
                        success(res) {
                            if (res.confirm) {
                                getApp().globalData.no_clear = 1;
                                wx.makePhoneCall({
                                    phoneNumber: self.data.store_tel,
                                })
                            };
                        },
                    });
                }
                else{
                  wx.showModal({
                    content: '商家未设置客服热线',
                    showCancel: 0,
                   
                });
                }
            });
    },

    //检验能不能分享
    check_can_share(th) {

        var userinfo=wx.getStorageSync("userinfo");
        if (!this.globalData.user_id && !userinfo) {
            wx.hideShareMenu();
            if(th) th.setData({isLogin:0 })


        }
        else{
            if(th) th.setData({isLogin:1 })
            wx.showShareMenu({
                withShareTicket: true,
                menus: ["shareAppMessage", "shareTimeline"],
            });
        }
    },

    //--- 判断是不是皮肤的商品的公共函数 ---
    check_skin_face(options,type,goods_id){
         if(options.skinface_id){
             this.globalData.skinface_id=options.skinface_id;
             var stoid=this.globalData.setting.stoid;
             var user_id=this.globalData.user_id;
             if(!user_id) return false;
			 //点击量的
			 this.request.promisePost("/api/weshop/face/skinGoodsBrowse/save",{
			     data:{
			         store_id:stoid,
                     goods_id:goods_id,
                     user_id:user_id,
                     addtime:ut.gettimestamp(),
                     skinface_id:options.skinface_id,
                     goods_type:type
                 }
             }).then(res=>{})
         }
    },
    //判段是不是视频号
    is_sp_hao:function () {
        if(!this.globalData.scene) return false;
        if(this.globalData.sp_scene.indexOf(this.globalData.scene)==-1) return false;
        return true;
    },

    is_distribut:async function (th){
        var isok=1;
        var dis=null;
        await this.promiseGet("/api/weshop/storeDistribut/get/"+os.stoid,{}).then(rs=>{
            dis=rs.data.data;
            if( dis && dis.switch==0){
                isok=0;
            }
        })
        if(!isok)	return false;
        await this.promiseGet("/store/storemoduleendtime/page?store_id=" +os.stoid + "&type=2",{}).then(rs=>{
            if(rs.data.code==0){
                var arr = rs.data.data.pageData;
                if (arr.length > 0) {
                    var item=arr[0];
                    if(item.is_sy==0){
                        var now = Date.parse(new Date());now = now / 1000;
                        if(item.end_time<now) {
                            isok=0;
                        }
                    }
                }else{
                    isok=0;
                }
            }
        })
        if(!isok) return false;
        //dis.is_yongjin_dk=1;
        th.data.dis_config=dis;
        //如果有开启佣金抵扣
        if(th.data.dis_config.is_yongjin_dk && this.globalData.userInfo.is_distribut){
            th.setData({can_commission:1});
        }
    },

    //获取佣金的比例
    get_commission2(dis_config,gd_data,goods_num) {
        var fir_num=0;
        var sec_num=0;
        var thi_num=0;
        if(dis_config.pattern==1){
            fir_num=(gd_data.fir_rate || 0)*goods_num;
            sec_num=(gd_data.sec_rate || 0)*goods_num;
            thi_num=(gd_data.thi_rate || 0)*goods_num;
        }else{
            fir_num=parseFloat((gd_data.commission || 0) *goods_num*(dis_config.firstRate || 0)/100).toFixed(2);
            sec_num=parseFloat((gd_data.commission || 0)*goods_num*(dis_config.secondRate || 0)/100).toFixed(2);
            thi_num=parseFloat((gd_data.commission || 0)*goods_num*(dis_config.thirdRate || 0)/100).toFixed(2);
        }

        if(getApp().globalData.userInfo.is_distribut){
            var pattern = dis_config.pattern;         // 分销模式
            var first_rate = dis_config.first_rate;      // 一级比例
            var second_rate = dis_config.second_rate;    // 二级比例
            var third_rate = dis_config.third_rate;      // 三级比例

            if(this.globalData.userInfo.first_leader){
                return parseFloat(parseFloat(fir_num).toFixed(2));
            }else{
                return parseFloat((parseFloat(fir_num)+parseFloat(sec_num)+parseFloat(thi_num)).toFixed(2));
            }
        }
    },
    //获取佣金的比例
    get_commission(first_money,second_money,third_money,th) {
        if(getApp().globalData.userInfo.is_distribut){
            var pattern = th.data.dis_config.pattern;         // 分销模式
            var first_rate = th.data.dis_config.first_rate;      // 一级比例
            var second_rate = th.data.dis_config.second_rate;    // 二级比例
            var third_rate = th.data.dis_config.third_rate;      // 三级比例

            if(this.globalData.userInfo.first_leader){
                return parseFloat(parseFloat(first_money).toFixed(2))
            }else{
                return parseFloat((parseFloat(first_money)+parseFloat(second_money)+parseFloat(third_money)).toFixed(2));
            }
        }
    },

    // 保存图片到手机
    savePic(th) {
        console.log('保存图片');
        var self = th;
        // 获取用户的当前设置，返回值中有小程序已经向用户请求过的权限
        this.getSetting().then((res) => {
            // 判断用户是否授权了保存到相册的权限，如果没有发起授权
            if (!res.authSetting['scope.writePhotosAlbum']) {
                this.authorize().then(() => {
                    // 同意授权后保存下载文件
                    this.saveImage(self.data.shareImgPath,th)
                        .then(() => {
                            self.setData({
                                showPoster: false
                            });
                        });
                })
            } else {
                // 如果已经授权，保存下载文件
                this.saveImage(self.data.shareImgPath)
                    .then(() => {
                        self.setData({
                            showPoster: false
                        });
                    });
            }

        })
    },

    // 获取用户已经授予了哪些权限
    getSetting() {
        return new Promise((resolve, reject) => {
            wx.getSetting({
                success: res => {
                    resolve(res)
                }
            })
        })
    },
    // 发起首次授权请求
    authorize() {
        // isFirst 用来记录是否为首次发起授权，
        // 如果首次授权拒绝后，isFirst赋值为1
        let isFirst = wx.getStorageSync('isFirst') || 0;
        return new Promise((resolve, reject) => {
            wx.authorize({
                scope: 'scope.writePhotosAlbum',
                // 同意授权
                success: () => {
                    resolve();
                },
                // 拒绝授权,这里是用户拒绝授权后的回调
                fail: res => {
                    if (isFirst === 0) {
                        wx.setStorageSync('isFirst', 1);
                        wx.showToast({
                            title: '保存失败',
                            icon: 'none',
                            duration: 1000
                        })
                    }
                    console.log('拒绝授权');
                    reject();
                }
            })
        })
    },
    // 保存图片到系统相册
    saveImage(saveUrl,th) {
        var self = th;
        return new Promise((resolve, reject) => {
            wx.saveImageToPhotosAlbum({
                filePath: saveUrl,
                success: (res) => {
                    wx.showToast({
                        title: '保存成功',
                        duration: 1000,
                    });
                    self.setData({
                        showPlaybill: 'true'
                    });
                    resolve();
                },
                fail: () => {
                    wx.showToast({
                        title: '保存失败',
                        duration: 1000,
                    });
                }
            })
        })
    },

    //文本换行 参数：1、canvas对象，2、文本 3、距离左侧的距离 4、距离顶部的距离 5、6、文本的宽度
    draw_Text: function (ctx, str, leftWidth, initHeight, titleHeight, canvasWidth, unit, lineNum) {
        var lineWidth = 0;
        var lastSubStrIndex = 0; //每次开始截取的字符串的索引
        var han = 0;
        for (let i = 0; i < str.length; i++) {
            if(lineNum) {
                if(han == lineNum) return;
            };
            if (han == 2) return;
            //lineWidth += ctx.measureText(str[i]).width;
            lineWidth += ut.measureText(str[i], 21.3 * unit);
            if (lineWidth > canvasWidth) {
                han++;

                if (han == 2 || han == lineNum)
                    ctx.fillText(str.substring(lastSubStrIndex, i) + '...', leftWidth, initHeight); //绘制截取部分
                else
                    ctx.fillText(str.substring(lastSubStrIndex, i), leftWidth, initHeight);

                initHeight += 22; //22为字体的高度
                lineWidth = 0;
                lastSubStrIndex = i;
                titleHeight += 20;
            }
            if (i == str.length - 1) { //绘制剩余部分
                ctx.fillText(str.substring(lastSubStrIndex, i + 1), leftWidth, initHeight);
            }
        };
    },

    //跳转视频号
    openChannelsActivity(obj){
      if (!obj.finderUserName) {
        wx.showToast({
          title: '参数缺少，跳转失败',
          duration: 2000,
      });
      }
      console.log('视频号参数：')
      console.log(obj)
      if (obj.video_type==1) {  //1是直播 2 是 视频
        wx.getChannelsLiveInfo({
          finderUserName:obj.finderUserName,
          success:(res)=>{
            let {feedId ,status,nonceId} = res
            if (true || status == 2) {
              wx.openChannelsLive({
                finderUserName:obj.finderUserName,
                feedId,
                nonceId,
                success:()=>{
                  console.log('进入直播间成功')
                },
                fail:(error)=>{
                  console.log('进入直播间失败')
                  console.log(error)
                }
              })
            }
          },
          fail:(error)=>{
            console.log('跳转失败1')
            console.log(error)    
            wx.showModal({
              title: '提示',
              content: '获取直播失败：'+error.err_code,
              showCancel:false,
              success (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                } else if (res.cancel) {
                  console.log('用户点击取消')
                }
              }
            })   
          }
        })
      }else{
        wx.openChannelsActivity({
          finderUserName:obj.finderUserName,
          feedId:obj.feedId,
          success:()=>{
            console.log('跳转成功')
          },
          fail:(error)=>{
            console.log('跳转失败')
            console.log(error)      
          }
        })
      }
    },

    //--- 统一跳转到物流的优化 ---
    go_wuliu(e){
        var url=e.currentTarget.dataset.url;
        var order_id=e.currentTarget.dataset.order_id;
        var conf=null;
        var th=this;
        var stoid=this.globalData.setting.stoid;
        var user_id=this.globalData.user_id;

        this.getConfig2(async function (e){
            if(e && e.switch_list)  conf=JSON.parse(e.switch_list);
            if(conf && conf.express_searchtype==1){
                //在此通过调用api来查询微信快递服务详情
                //必须用预览才能测试这个功能，无法在工具端模拟
                url="/packageF/pages/wuliu/wuliu?order_id="+order_id;
            }
            th.goto(url);

        })
    },

     //--- 统一跳转到物流的优化 ---
     async check_go_fw(goods_id,func){

      var user_id=this.globalData.user_id?this.globalData.user_id:0;
      var flag=null;
      //判断拼团的---会员身份--
      await this.promiseGet("/api/weshop/teamlist/pageteam/2", {
          data: {
              store_id: os.stoid,
              is_end: 0,
              is_show: 1,
              user_id: user_id,
              pageSize: 1000,
              goods_id:goods_id
          }
      }).then(res => {
          let pd_list = res.data.data.pageData;
          if (res.data.code == 0 && pd_list.length > 0) {
              flag = pd_list.find(pd => {
                  return  pd.goods_type==1;
              })
          }
      })

      var url= "/packageH/pages/goodsInfo/goodsInfo?goods_id="+goods_id;
      if(flag){
          url='/packageA/pages/serviceCard_pd/goodsInfo/goodsInfo?goods_id='+goods_id+'&prom_type=6&prom_id='+flag.id;
      }
      if(func){
          func(flag,url)
      }else{
          this.goto(url);
      }


  },
    //-- 如果是新会员没有地址的时候，自提的时候可以不用管 --
    is_no_addr(th,exp_type){
        exp_type=parseInt(exp_type+'');
        if ( [0,2].indexOf(exp_type)>-1 && th.data.user_addr == null) {
            th.setData({ submit: 0});
            return true;
        }
        return false;
      },
    //---- 判断是不是虚拟商品  -----
    is_virtual(gd){
        if(gd.is_virtual==2) return true;
        return false;
    },

    /**
     *
     * @param gd  商品
     * @param act 活动
     * @param get_type 0默认  1是加和减的时候
     */
    get_limit_qty(gd,act,get_type){
        var islimit=gd.erp_islimit;        //是不是限购
        var limittype=gd.erp_limittype;    //不低于0、倍数1
        var limitqty=gd.erp_limitqty;      //起购量

        //-- 如果有活动的时候,就直接返回1 --
        if(act){
            return 1;
            //islimit=act.islimit;
            //limittype=act.limittype;
            //limitqty=act.limitqty;
        }
        //-- 不是限购的时候，返回1--
        if(!islimit) return 1;
        //-- 默认的时候 --
        if(!get_type) return limitqty;
        //不低于的时候，加减的时候
        if(!limittype) return 1;
        //倍数，加减的时候
        return limitqty;
    },

    //获取商品是不是有促销活动
    async get_has_cx_act(gid){
        var url = '/api/weshop/activitylist/listGoodActInfo2New';
        var req_d = {
            "store_id":this.globalData.setting.stoid,
            "goods_id": gid,
            "user_id":this.globalData.user_id,
        }
        var res= await this.promiseGet(url,{data:req_d});
        var cx_arr=[];
        if (res.data.code == 0 && res.data.data && res.data.data.length > 0) {
            var arr = res.data.data;
            cx_arr=arr.filter(function (e) {
                return e.s_time < ut.gettimestamp() && [3,5,7,10].indexOf(e.prom_type)>-1;
            })
        }
        return  cx_arr;
    },

    get_has_cx_act2(act_arr){
        var cx_arr=[];
        if(act_arr && act_arr.length)
            cx_arr=act_arr.filter(function (e) {
                return e.s_time < ut.gettimestamp() && [3,5,7,10].indexOf(e.prom_type)>-1;
            })
        return cx_arr;
    },

   //-- 获取判断注册成功后，是跳转等级卡，还是新人有礼 --
   async go_to_page(is_reg,func){
      if(!is_reg) {
          func();
          return false;
      }
      //如果是从企业专属导购跳过来的话，就要返回专属导购处理页面
      let qyzsdg = wx.getStorageSync('qyzsdg')  //如果是专属导购
      if (qyzsdg) {
        wx.reLaunch({
          url: `/packageE/pages/qy/contactMe/contactMe?scene=${qyzsdg}`,
        })
        return
      }

       //新判断新人有礼
       var res= await getApp().request.promiseGet("/api/weshop/marketing/newpeople/act/judge", {
           data: {
               storeId: os.stoid,
               userId: this.globalData.user_id
           }
       });

       if (res.data.code == 0) {
           var actid = res.data.data.id; //活动id
           var giftBagId = res.data.data.giftBagId; //礼包id
           var new_nav = "/packageF/pages/giftpack/newvipgift/newvipgift?actId=" + actid + '&' + 'actType=' + 1 + '&' + 'giftBagId=' + giftBagId;
           wx.redirectTo({
               url:new_nav
           })
           return false;
       }

       //如果已经是等级卡了就跳过
       if(this.globalData.userInfo.card_field){
           //没有等级卡和新人有礼的时候
           if(func)  func();
           return  false;
       }

       var dj_buy=await getApp().promiseGet("/store/storemoduleendtime/page?store_id=" + this.globalData.setting.stoid+ "&type=3", {});
       var ob = { isout: 0, isbuy: 0 };
       if (dj_buy.data.code == 0) {
           var arr = dj_buy.data.data.pageData;
           //----如果数组不为空----
           if (arr.length > 0) {
               arr.forEach(function (val, ind) {
                   if (val.is_sy == 0 || val.is_sy == 1) {
                       ob.isbuy = 1;
                       var now = ut.gettimestamp();
                       if (now > val.end_time) ob.isout = 1;
                       return false;
                   }
               })
           }
       }

       //-- 获取等级卡,直接去买等级卡 --
       if(ob.isbuy && !ob.isout){
           //-- 获取等级卡购买的数量 --
           var conf=await getApp().promiseGet("/api/weshop/storeconfig/get/" + this.globalData.setting.stoid, {});
           //-- 获取等级卡的会员已经购买的数量 ---
           var dj=await getApp().promiseGet("/api/weshop/users/getUserCard/" + this.globalData.setting.stoid, {});
           var dj_num=0;
           if(dj.data.code==0){
               dj_num=dj.data.data?dj.data.data:0;
           }

           var sw_list= conf.data.data.switch_list;
           if(sw_list){
               sw_list=JSON.parse(sw_list);
           }


           if (sw_list && sw_list.rank_switch==2 && conf.data.code == 0 && conf.data.data.dj_num>0 && conf.data.data.dj_num>dj_num) {
               var nav = "/pages/user/plus/plus";
               wx.redirectTo({
                   url:nav
               })
               return false;
           }
       }
       //没有等级卡和新人有礼的时候
       if(func)  func();
   },

   //content是映射的标题，goods_content是富文本的内容,
   //a是wxpares插件 e是common.js th是页面的指针
   async deal_iframe(a,e,content,goods_content,th){

       if (goods_content == null) goods_content = "";
       //-----商品详情---
       if (!goods_content) goods_content = "  ";

       //用内存对象
       var ob={text:''};
       if(goods_content){
            ob.text=goods_content;
            await this.deal_iframe_next(ob)
       }
       a.wxParse(content, "html", ut.format_content(ob.text), th, 6);
       e.wxParseAddFullImageUrl(th, content);

    
   },

   async deal_iframe_next(ob){
       for(let i = 1; i > 0; i++){
            //如果没有iframe语句的时候，就跳出循环
            if(ob.text.indexOf('<iframe')<0) break
            var start=ob.text.indexOf('<iframe');
            var end=ob.text.indexOf('</iframe>');
            //截取iframe的dom元素
            var str=ob.text.substring(start, end+9);

            var arr = str.split('vid=');
            var arrs = arr[1].split('"');
            /*	console.log("截取&前面的的"+arrs[0]);*/
            var vipid = arrs[0];

            //-- 用vipid调用接口，转换视频 --
            var url = "https://vv.video.qq.com/getinfo?vid=" + vipid + "&platform=101001&charge=0&otype=json";
            var res=await getApp().promiseGet(url,{})
            if(res && res.data){
               var dataJson = res.data.replace(/QZOutputJson=/, '') + "qwe";
               var dataJson1 = dataJson.replace(/;qwe/, '');
               var data = JSON.parse(dataJson1);
               if (data.vl != undefined) {
                   var host1 = data['vl']['vi'][0];
                   var host2=host1['ul']['ui'];
                   var len=host2.length-1;
                   var host= host2[len]['url'];

                   var fn = data.vl.vi[0].fn;
                   var fvkey = data.vl.vi[0].fvkey;
                   /* console.log("有参数吗"+fn+"有参数吗"+fvkey);*/
                   var wxapp_url = host + fn + '?vkey=' + fvkey;
                   var frame='<video src="'+wxapp_url+'" controls="controls"></video>';
                   ob.text=ob.text.replaceAll(str,frame)
               }
               continue;
            }else{
              break;
            }
       }
   },

   //从staff_id获取线上导购列表
   async get_guide_from_staff(staff_id,func) {
        let guide=null;
        //获取导购
        await this.promiseGet("/api/weshop/shoppingGuide/getStaffIdInfo", {
            data: {
                store_id:this.globalData.setting.stoid,
                StaffId:staff_id
            },
        }).then(res => {
            if(res && res.data.code==0 && res.data.data && res.data.data.is_bind && res.data.data.bind_user_id){
               guide=res.data.data
            }
        })

        if(guide) {
            //guide.beauty_strengths = "美妆小能手";
            //获取导购绑定的会员的信息
            await this.promiseGet("/api/weshop/users/get/" + this.globalData.setting.stoid + "/" + guide.bind_user_id, {
                data: {},
            }).then(res => {
                if (res && res.data.code == 0 && res.data.data) {
                    guide.head_pic = res.data.data.head_pic;
                }
            })
        }
        if(func){
            func(guide);
        }
    },

    customer_chat(goods_id,type){
        var url = "/packageG/pages/customer_chat/customer_chat?goods_id="+goods_id;
        if(type)
            url += "&type=1";
        this.goto(url);
    },


    
  //判断有没有获取到api_token
  ck_api_token(func){
    var api_token = wx.getStorageSync('api_token');
    var api_token_time = wx.getStorageSync('api_token_time');
    //token有存在本地的时候
    if(api_token){
      //判断有没有超出token的时间，超出的话就要重头拿token
      var now=ut.formar_day();
      if(now!=api_token_time){
        //调用接口获取token
        this.get_api_token(func);
        return false;
      }
      func(api_token);
      return  false;
    }
    this.get_api_token(func);
  },

  //获取api_token
  get_api_token(func){

    var api_token = wx.getStorageSync('api_token');
    var api_token_time = wx.getStorageSync('api_token_time');
    //token有存在本地的时候
    if(api_token){
      //判断有没有超出token的时间，超出的话就要重头拿token
      var now=ut.formar_day();
      if(now==api_token_time){
        if(func)  func(api_token);
        return false;
      }
    }

    if(this.globalData.get_tking){
       setTimeout(()=>{
           this.get_api_token(func);
       },1000)
       return false;
    }

    this.globalData.get_tking=1;
    var th=this;
    var ukey = wx.getStorageSync('ukey');
    if(!ukey){
      var url = th.globalData.setting.url + '/api/weshop/store/geStoreKey';
      var data={
        store_id:th.globalData.setting.stoid
      }
      var token1=md5(JSON.stringify(data)).toUpperCase();

      console.log('tk1_fir:'+token1);
      console.log('tk1_fir1:'+'GETSTOREKEY'+token1+th.globalData.setting.environment_key);

      var str = md5('GETSTOREKEY'+token1+th.globalData.setting.environment_key).toUpperCase();
      data.token=str;

      wx.request({
        url: url,
        data: JSON.stringify(data),
        method: "POST",
        header: {
          'content-type': 'application/json'
        },// 设置请求的 header
        success: function (res) {
          if(res.data.code==0){
            wx.setStorageSync("ukey", res.data.data.ukey);
            th.get_api_token2(func);
          }else{
            th.confirmBox(res.data.msg)
          }
        },
        fail: function (res) {
          ut.m_toast('网络繁忙，请稍后重试');
        }
      })
      return false;
    }

    this.get_api_token2(func);

  },

  get_api_token2(func){
    var th=this;
    var ukey = wx.getStorageSync('ukey');
    var dd_json={
      store_id:th.globalData.setting.stoid,
      ukey:ukey
    }

    var ty= new Date();
    var c="-";

    var m=ty.getMonth() + 1;
    if(m<10) m="0"+m;
    var day=ty.getDate();
    if(day<10) day="0"+day;

    var nday=ty.getFullYear() +c+m+c+day;

    //console.log('tk1_str:'+JSON.stringify(dd_json));
    var tk1=md5(JSON.stringify(dd_json)).toUpperCase();
    //console.log(tk1)
    var tk2_str='GETAPITOKEN'+tk1+nday+th.globalData.setting.environment_key;
    //console.log("tk2_str:"+tk2_str);
    var tk2=md5(tk2_str).toUpperCase();
    //console.log(tk1)
    var url = th.globalData.setting.url + '/api/weshop/store/getApiToken';
    var data1={
      'store_id':th.globalData.setting.stoid,
      'ukey':ukey,
      'token':tk2
    }
    wx.request({
      url: url,
      data: JSON.stringify(data1),
      method: "POST",
      header: {
        'content-type': 'application/json'
      },// 设置请求的 header
      success: function (res) {
        if(res.data.code==0){
          //记录当天，隔天就要重新刷新
          var now=ut.formar_day();
          var api_token =res.data.data;
          wx.setStorageSync('api_token',api_token);
          wx.setStorageSync('api_token_time',now);
          th.globalData.get_tking=0;
          if(func) func(api_token);
        }else{
          getApp().confirmBox(res.data.msg)
        }
      },
      fail: function (res) {
        ut.m_toast('网络繁忙，请稍后重试');
      }
    })

  }





});

    
