var t = getApp(),
    a = t.request,
    os = t.globalData.setting,
    ut = require("../../../utils/util.js"),
    com = require("../../../utils/common.js");
var regeneratorRuntime = require('../../../utils/runtime.js');
const rq = require("../../../utils/request.js");
var appd = getApp().globalData;

Page({
    data: {
        url: os.imghost,
        temp_id: 0,
        goodsGroupArr: [],
        pulscardname: '',
        rfmName: '成长值',

        byquan: 0,
        yuer: 0,
        udata: {},

        is_assistance: 0, //助力活动
        b_gift:null,       //生日礼包
        toji: null,          //统计相关

        userInfo:null,
        enableMeiye:null,

        is_show_recommend:false,
    },

    onLoad: function (e) {
        var th = this;
        this.data.temp_id = e.scene;
        if (!this.data.temp_id) wx.showModal({title: "未读取到模板ID",})

        var first_leader = e.first_leader;
        if (first_leader) {
            //--  user_id代过来免登录 --
            getApp().globalData.first_leader = first_leader;
            //调用接口判断是不是会员
            getApp().request.promiseGet("/api/weshop/shoppingGuide/get/" + os.stoid + "/" + first_leader, {}).then(res => {
                if (res.data.code == 0) {
                    getApp().globalData.guide_id = res.data.data.id;
                    getApp().globalData.guide_pick_id = res.data.data.pickup_id
                }
            })
        }
        //判断有没有登陆
        setTimeout(() =>{
            if (!getApp().globalData.userInfo) {
                getApp().goto('/packageE/pages/togoin/togoin');
            }
        },1500)

    },

    async onShow() {
        getApp().check_can_share();
        var th = this;

        if(!th.data.userInfo){
            this.data.userInfo =getApp().globalData.userInfo;
        }

        /*-----统计-----*/
        getApp().request.get("/api/weshop/order/waitlist", {
            isShowLoading: 0,
            data: {
                user_id: getApp().globalData.user_id,isdel:0
            },
            success: function (su) {
                th.setData({
                    toji: su.data.data,
                });
            }
        })

        /*-------系统是否开通等级卡，会员是等级卡-----*/
        getApp().getConfig2(function (e) {
            var t_swi = e.switch_list;
            if (t_swi) t_swi = JSON.parse(t_swi)
            if (t_swi) {
                th.setData({sys_switch: t_swi});
                var user_tool = [];
                if (t_swi.usertool) user_tool = JSON.parse(t_swi.usertool);
                th.setData({c_list: user_tool});

                if (parseInt(t_swi.rank_switch) == 2) {
                    var userInfo = th.data.userInfo;
                    if (userInfo && userInfo.card_field != null && userInfo.card_field != undefined && userInfo.card_field != "") {
                        var now = ut.gettimestamp();
                        var str = userInfo.card_expiredate;
                        var end = new Date(str);
                        end = Date.parse(end) / 1000;
                        //---判断是不是有过期---
                        if (now < end) {
                            th.setData({
                                is_dengji: 1
                            })
                        } else {
                            th.setData({
                                is_dengji: 3
                            })
                        }
                    } else {
                        th.setData({
                            is_dengji: 2
                        })
                    }
                }
            }
        })

        //--我的权益初始化是否有打勾,--
        getApp().request.get("/api/weshop/users/grade/vip/init/get", {
            data: {
                storeId: os.stoid
            },
            success: function (rs) {
                if (rs.data.code == 0 && rs.data.data.isBool) {
                    th.setData({is_init: 1});
                    /*-----获取会员权益列表-----*/
                    rq.get("/api/weshop/users/grade/vipprivilegeinfo/page", {
                        isShowLoading: 0,
                        data: {
                            storeId: os.stoid,
                            pageSize: 100
                        },
                        success: async function (res) {

                            //判断有没有值，没有值返回
                            if (!ut.ajax_ok(res)) return false;

                            var arr_data = res.data.data.pageData;
                            var gid = null,
                                g_qy_list = null,
                                cz_vals = 0,
                                need_money = 0,
                                backClass = null,
                                GradeName = '';

                            var app_d = getApp().globalData;

                            //获取成长值
                            await getApp().request.promiseGet("/api/weshop/users/grade/aftervipinfo/get", {
                                data: {
                                    storeId: os.stoid,
                                    userId: app_d.user_id
                                }
                            }).then(res => {
                                if (res.data.code == 0 && res.data.data) {
                                    gid = res.data.data.GradeId;
                                    var cz_val = res.data.data.GradeSum;
                                    cz_vals = parseInt(cz_val);
                                    GradeName = res.data.data.GradeName;
                                }
                                //th.setData({ cz_val: cz_vals, GradeName: res.data.data.GradeName, is_init: is_init, gradeId: gid});
                            })
                            var obj = {
                                cz_val: cz_vals,
                                GradeName: GradeName,
                                gradeId: gid,
                                is_grad_get: 1
                            };

                            //  获取最大值
                            await getApp().request.promiseGet("/api/weshop/users/grade/vipgradeinfo/page", {
                                data: {
                                    storeId: os.stoid
                                }
                            }).then(res => {
                                if (res.data.data)
                                    backClass = res.data.data.pageData;
                                if (backClass) {
                                    var full_cz_val = backClass[backClass.length - 1].BuyGradeSum;
                                    obj.full_cz_val = full_cz_val
                                }
                            })

                            //--会员权益中心页的修改--
                            for (var i in backClass) {
                                var im = backClass[i];
                                if (cz_vals < im.BuyGradeSum && need_money == 0) {
                                    need_money = im.BuyGradeSum;
                                    obj.need_money = need_money;
                                    obj.nextGradeName=im.GradeName;
                                    break;
                                }
                            }

                            //获取当前等级的特权
                            await getApp().request.promiseGet("/api/weshop/users/grade/privilegeform/list/page", {
                                data: {
                                    storeId: os.stoid,
                                    GradeId: gid,
                                    userId: app_d.user_id,
                                    pageSize: 100
                                }
                            }).then(res => {
                                if (res.data.data)
                                    g_qy_list = res.data.data.pageData;
                            });

                            for (var i in arr_data) {
                                var item = arr_data[i];
                                var FromId = th.check_is_has_qy(item, g_qy_list);
                                arr_data[i].ishas = 0;
                                if (FromId) {
                                    arr_data[i].ishas = 1;
                                    arr_data[i].FromId = FromId;
                                }
                            }
                            arr_data.sort(function (a, b) {
                                return b.ishas - a.ishas
                            })

                            //4个4个一组
                            var arr = new Array();
                            for (var i = 0; i < arr_data.length; i += 4) {
                                arr.push(arr_data.slice(i, i + 4));
                            }
                            //th.setData({ qy_list: arr, need_money: need_money});
                            obj.qy_list = arr;
                            obj.old_qy_list = arr_data;
                            th.setData(obj);
                            obj.is_init = 1;
                            th.setData({qy_data: obj})
                        }
                    })
                }
            }
        })

        this.puls_user();
        this.getVison();

        //-----获取线下会员的预存款和优惠券的数量-----
        getApp().request.get("/api/weshop/users/getinfo/" + os.stoid + "/" + getApp().globalData.user_id, {
            isShowLoading: 0,
            success: function (su) {
                if (su.data.code == 0 && su.data.data) {
                    var data = su.data.data;
                    if (!data) data = {};
                    data.cashcount = parseInt(data.cashcount);
                    th.setData({
                        udata: data,
                    });
                }
            }
        })

        //-----获取会员提现金额-----
        getApp().request.get("/api/weshop/withdrawals/summoney", {
            isShowLoading: 0,
            data: {
                user_id: getApp().globalData.user_id,
                store_id: os.stoid,
                status: 0
            },
            success: function (su) {
                if (su.data.code == 0) {

                    let user = getApp().globalData.userInfo;
                    var yuer = parseFloat(user.user_money - user.frozen_money - su.data.data.summoney).toFixed(2);
                    th.setData({
                        txmon: su.data.data.summoney,
                        yuer: yuer
                    });
                }
            }
        })

        /*-----获取会员包邮券的数量-----*/
        getApp().request.get("/api/weshop/userfeemail/page", {
            isShowLoading: 0,
            data: {
                user_id: getApp().globalData.user_id,
                store_id: os.stoid,
                pageSize: 1,
                isuse: 0
            },
            success: function (su) {
                if (su.data.code == 0) {
                    th.setData({
                        byquan: parseInt(su.data.data.total)
                    });
                }
            }
        });


        // 判断是否开启美业
        getApp().promiseGet('/api/weshop/store/getTabSys/' + os.stoid, {}).then(res => {
            if (res.data.code == 0) {
                th.setData({
                    enableMeiye: res.data.data.EnableMeiye,
                });
            };
        });

        //判断一下是不是助力活动
        this.is_assistance();
        //获取工具
        await this.init_user_tool();
        //获取一下生日相关
        this.birthday();

        //获取自定义模板
        await this.init_load();

        //自定义组件一定要等到页面加载完了，才来调用selectComponnent
        setTimeout(function () {

            th.setData({ is_show_recommend:true })
            if (getApp().globalData.user_id) getApp().requestCardNum(th);
            var goods_list = th.selectComponent("#goods_recommend"); //组件的id

            if(goods_list){
                goods_list.init();
                goods_list.get_list();
            }

        }, 1500)

    },

    //获取商品模块实例
    newGoodsGroup() {
        let arr = []
        if (this.data.template_arr.length == 0) {
            return
        }
        this.data.template_arr.map((item, index) => {
            if (item.ename == 'goodsGroup') {
                arr.push(`goodsGroup${index}`)
            }
        })
        if (arr.length > 0) {
            this.setData({
                goodsGroupArr: arr
            })
            arr.map(item => {
                let a = '.' + item
                this[item] = this.selectComponent(a);
            })
        }
    },
    //当隐藏的时候就关闭计时器
    onHide: function () {

    },
    //同步初始加载
    async init_load() {
        var th = this;
        //因为营销版本的功能包含了自定义模板的功能，是同时的
        //读取全局是否有弄自定义模板
        await getApp().request.promiseGet("/api/weshop/store_module/get/" + th.data.temp_id + "/8", {1: 1}).then(res => {
            var data = res.data.data;
            if (data) {
                var temp_data = data;
                wx.setNavigationBarTitle({
                    title: temp_data.page_title,
                });
                var t_arr = JSON.parse(temp_data.json_str);

                let obj={
                    share_title: temp_data.page_title,
                    template_arr: t_arr,
                    isTemplate: 1,
                    bgcolor_t: temp_data.bkcolor
                };

                setTimeout(() => {
                    th.newGoodsGroup()
                }, 1000)

                //---如果有设定顶部的颜色的时候--
                if (temp_data.top_color && temp_data.top_color != 'null') {
                    var top_w_color = "#ffffff";
                    if (temp_data.top_word_color) {
                        top_w_color = temp_data.top_word_color
                    }
                    wx.setNavigationBarColor({
                        frontColor: top_w_color, // 必写项
                        backgroundColor: temp_data.top_color, // 必写项
                    })
                    obj.topwColor=top_w_color;
                    obj.topbgColor=temp_data.top_color;
                }

                th.setData(obj);

            }
        })
    },

    onPullDownRefresh: function (e) {

    },


    onShareAppMessage: async function (e) {
        var th = this;
        getApp().globalData.no_clear = 1;
        getApp().getConfig(await function (e) {
            th.setData({
                store_config: e
            })
        }.bind(this))

        var url = `pages/template/index?sence=` + this.data.temp_id;
        var userInfo = getApp().globalData.userInfo;
        //是分销商才带
        if (userInfo) {
            url += "&first_leader=" + userInfo.user_id;
        }

        var ob = {
            title: this.data.share_title,
            path: url,
            //imageUrl:this.data.url+this.data.store_config.store_logo,
        };
        return ob;
    },

    /**
     * 用户分享朋友圈
     */
    async onShareTimeline() {

        var th = this;
        getApp().globalData.no_clear = 1;
        getApp().getConfig(await function (e) {
            th.setData({
                store_config: e
            })
        }.bind(this))
        var {share_title, temp_id, store_config} = this.data;
        var url = `sence=${temp_id}`;

        var userInfo = getApp().globalData.userInfo;
        //是分销商才带
        if (userInfo) {
            url += "&first_leader=" + userInfo.user_id;
        }

        var ob = {
            title: share_title,
            query: url,
            //imageUrl:this.data.url+store_config.store_logo,
        };
        console.log(ob);
        return ob;
    },

    //---加载更多是靠这个函数----
    onReachBottom: function () {
        if (getApp().globalData.func_list) {
            for (let i in getApp().globalData.func_list) {
                let item = getApp().globalData.func_list[i];
                item.re_show();
            }
        }

        //自定义时商品自动加载更多
        let goodsGroupArr = this.data.goodsGroupArr
        if (this.data.isTemplate && goodsGroupArr.length > 0) {
            goodsGroupArr.map(item => {
                this[item].automore()
            })
        }

        var e = getApp().globalData.userInfo;
        if (e != undefined && e != null && e.mobile) {
            var goods_list = this.selectComponent("#goods_recommend"); //组件的id
            goods_list.init();
            setTimeout(function () {
                goods_list.get_list();
            }, 300)
        }

    },

    //-----Plus会员获取-----------
    puls_user: function () {
        var th = this;
        getApp().request.get("/api/weshop/plus/vip/mem/list", {
            data: {
                storeId: os.stoid,
                userId: getApp().globalData.user_id,
            },
            success: function (su) {
                if (su.data.code == 0) {
                    var cardname = su.data.data[0].MemCardName;
                    th.setData({
                        pulscardname: cardname
                    });
                }
            }
        });
    },

    //判断会员是后有改服务项目
    check_is_has_qy: function (item, g_qy_list) {
        if (!g_qy_list) return false;

        for (var i in g_qy_list) {
            var iter = g_qy_list[i];
            if (iter.FormId == item.Id) return g_qy_list[i].FormId;
        }
        return false;
    },

    //获取会员权益等级是否升级
    getVison() {
        let isRfm = wx.getStorageSync('isRfm')
        if (isRfm) {
            this.setData({
                rfmName: '综合分'
            })
        } else {
            rq.get(`/api/weshop/users/grade/vip/getSysPara?storeId=${os.stoid}&classInfo=IsUpRMF`, {
                success: (res) => {
                    console.log('会员权益等级升级查询-------');
                    console.log(res);
                    if (res.data.code == 0 && res.data.data && res.data.data.IsBool) {
                        this.setData({
                            rfmName: '综合分'
                        })
                        wx.setStorageSync('isRfm', true)
                    }
                }
            })
        }
    },


    //-- 初始话按钮图标,服务与工具的优化 ---
    init_user_tool: async function () {
        var d_list = null;
        //读取user_tool按钮图标
        await getApp().promiseGet("/api/weshop/userTool/page?pageSize=100&store_id=" + os.stoid, {}).then(res => {
            if (ut.ajax_ok(res)) {
                d_list = res.data.data.pageData;
            }
        })

        if (!d_list) return false;
        //过滤掉分销关闭的
        let distribut_end_time = await getApp().user_tools_endTime(2);//过滤掉分销到期的
        await getApp().promiseGet("/api/weshop/storeDistribut/get/" + os.stoid, {}).then(rs => {
            if (rs.data.code == 0 || !rs.data.data) {
                var is_ok = 1;

                if (!distribut_end_time) {
                    is_ok = 0;
                } else if (!rs.data.data) {
                    is_ok = 0;
                } else {
                    var dis = rs.data.data;
                    if (!dis || dis.switch == 0) {
                        is_ok = 0;
                    }
                }

                for (var i in d_list) {
                    if (d_list[i].name == '我的分销' && !is_ok) {
                        d_list.splice(i, 1);
                    }
                }
            }
        })

        //判断有没有开AI测肤
        await getApp().promiseGet("/api/weshop/wx/weappSkin/get/" + os.stoid, {}).then(rs => {
            if (rs.data.code != 0 || !rs.data.data) {
                for (var i in d_list) {
                    if (d_list[i].name == 'AI测肤') {
                        d_list.splice(i, 1);
                    }
                }
            }
        })
        this.setData({user_tool: d_list});
    },

    // 判断助力活动是不是存在
    is_assistance: function () {
        var th = this, r = Math.random() * 100;
        getApp().promiseGet("/api/weshop/marketing/help/act/judge", {
            data: {
                storeId: os.stoid,
                userId: getApp().globalData.user_id,
                r: r,
            }
        }).then(res => {
            var code = res.data.code;
            if (code == 0) {
                th.setData({
                    is_assistance: 1
                });
            } else {
                th.setData({
                    is_assistance: 0
                });
            }
        })
    },

    // 判断生日营销的页面是不是存在
    birthday: function () {
        var th = this;
        getApp().request.get("/api/weshop/marketing/birthday/act/judge", {
            data: { storeId: os.stoid, userId: getApp().globalData.user_id },
            success: function (res) {
                var code = res.data.code;
                if (code == 0) {
                    var giftbagid = res.data.data.giftBagId;
                    var actId = res.data.data.id;
                    var actImg = res.data.data.actImg;
                    th.setData({  b_gift:{ giftbagid: giftbagid, actId: actId, actImg: actImg } });
                }

            }
        })
    },


});