var i = require("../../../../utils/util.js");
var ut=i;
var com = require("../../../../pages/giftpack/public/buy_com.js");
var e = getApp(),
  a = e.globalData.setting,
  os = a,
  t = e.request,
  d = e.globalData;
Page({
  data: {
    url: a.url, //接口网址
    iurl: a.imghost, //图片前缀网址
    getStorageID: '',
    getUserID: '',
    wareCard: [],
    // page: 0,
    // pageSize: 10,
    isEmpty: false,
    loadingType: 0, //定义加载方式 0---contentdown  1---contentrefresh 2---contentnomore
    contentText: {
      contentdown: '加载更多',
      contentrefresh: '加载中...',
      contentnomore: '已加载全部'
    },
    ismore: 0, //数据是否全部加载完成
    is_read: 0, //是否查询过我的礼包接口
    curpage: 1, //当前分页数
    pageSize: 10, //页大小
    total: 0, //总数量
    ad_data: null,
    first_leader: e.globalData.first_leader || 0, // 推荐人ID

      //门店相关
      ismend: 0,
      is_sec_mend: 0,
      sto_sele_name: "", //选中的门店名称
      sto_sele_id: "", //选中的门店id
      sto_sele_distr: "", //选择的门店的配送方式
      is_show_sto_cat: 1, //是否显示门店分类
      only_pk: null,
      all_sto: null,
      sec_sto: null, //选择了的门店分类
      pickpu_list: null, //读出的所有门店list
      def_pickpu_list: null, //一开始5个门店list
      sec_pick_index: 0, //第二级门店选择ID
      fir_pick_index: 0, //第一级门店选择ID
      all_pick_list: null,//所有的门店先记录起来

      select_store: 0, //选择更多
      index: 1,
      more_store: 0, //选择门店
      sort_store: 0, //门店分类
      choice_sort_store: 0, //选择分类门店
      new_user: 0, //新用户

      def_pick_store: null, // 默认的门店
      fir_def_store: null,  //客户默认的门店的
      lat: null, //维度
      lon: null, //经度

      is_get_local_ok: 0, //获取坐标是否完成
      region_name: "门店分类", //区域的名字
      is_gps: 1,
      open_ind_store: 0, //哪里打开的门店列表的控制属性
      default_store: {}, //创建添加默认门店地址的对象
      old_all_sto:null,
      store:0,
      openSpecModal:0,

      is_get_guide:0,
      keyword:'', //门店搜索
      sec_i:-1,//选中分类门店 下标

      sear_key:'',
      is_gift_buy:1,  //显示购买的备注

  },
  onLoad: function (options) {
    if(options.transfer){
      let obj=getApp().globalData.ts_trans_data;
      options= JSON.parse(JSON.stringify(obj));
      getApp().globalData.ts_trans_data=null;
 }

    var th=this;

    //定义第一次进入
    this.data.fir_in=1;

    this.setData({
      params: options,
      now:Date.parse(new Date()) / 1000,
    })

      getApp().getConfig2(function (e) {
          var json_d = JSON.parse(e.switch_list);
          th.setData({
              bconfig: e,
              sys_switch:json_d
          });
      })

  },
  init() {
    var th = this;
    let options = this.data?.params;
    this.setData({
      getStorageID: a.stoid,
      getUserID: d.user_id
    });
    var my_confirm = th.selectComponent("#my_confirm"); //组件的id
    my_confirm.open_cancel(0);
    //-- 获取分享人的ID --
    var first_leader = options.first_leader || getApp().globalData.first_leader;
    if (first_leader) {

      this.data.is_get_guide=1;
      this.setData({
        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
        }

          com.wait_for_store_config(th);
          com.set_user_mo_store(th,os);

      })
    }

    getApp().request.promiseGet("/api/weshop/ad/page?pid=902&store_id=" + os.stoid, {
      data: {
        enabled: 1
      }
    }).then(res => {
      if (res.data.code == 0 && res.data.data && res.data.data.pageData && res.data.data.pageData.length > 0) {
        var a = res.data.data.pageData;
        var tt = {
          'ad_code': os.imghost + a[0].ad_code,
          'media_link': '',
          'ad_weapplink': a[0].ad_weapplink,
          'bgcolor': a[0].bgcolor,
        };
        th.setData({
          ad_data: tt
        });
      }
    })
    this.getList();
  },
  onShow: function () {

      this.setData({submit:0})
      var th=this;

      //判断是不是第一次进入
      if(this.data.fir_in){
          this.data.fir_in=0;
      }else{
          //富友支付插件
          i.fy_back('',0);
          com.set_py_fir();


          if(th.data.ok_order_sn){
              //-- 通联的第三方支付的返回优化 --
              var money=th.data.payMoney;
              var back_url = "/packageF/pages/giftpack/payment/payment?money=" + money + "&order_sn=" +    th.data.ok_order_sn;

              ut.is_pay_ok(th.data.ok_order_sn,back_url,'none',function (){
                  if(!th.data.ok_order_sn) return false;
                  getApp().request.promiseGet("/api/weshop/marketing/my/giftbag/detail/get",
                      {data:{storeId:os.stoid,orderSn:th.data.ok_order_sn,userId:getApp().globalData.user_id}}).then(res=>{

                      th.data.ok_order_sn=null;

                      if(res.data.code==0 && res.data.data){
                          var item=res.data.data;
                          if(item.payState==1){
                              //支付支付，返回首页
                              ut.m_toast('支付成功');
                              setTimeout(()=>{
                                  getApp().goto(back_url);
                              },1000)

                          }else{
                              //支付支付，返回首页
                              ut.m_toast('支付失败');
                          }
                      }
                  })
              },null,null,1);

              th.data.ok_order_sn=null;
          }




      }



      getApp().check_can_share();

    //--先判断会员状态--
    getApp().is_Single_page(this, function () {
      var user_info = getApp().globalData.userInfo;
      if (user_info == null || user_info.mobile == undefined || user_info.mobile == "" || user_info.mobile == null) {
        getApp().goto('/packageE/pages/togoin/togoin');
        return false;
      }

      if(!th.data.is_get_guide) {
          com.wait_for_store_config(th);
          com.set_user_mo_store(th, os);
      }
      th.data.is_get_guide=0;

    })
    this.init();

    setTimeout(()=>{
        var my_confirm = th.selectComponent("#my_confirm"); //组件的id
    },2000)

  },
  //获取搜索门店输入的值
  input_store: function(e) {
    this.setData({
      keyword: e.detail.value
    })
  },
  //搜索门店
  searchfn(){
    let choice_sort_store = this.data.choice_sort_store
    if (choice_sort_store==0) {  //全局搜索
      let all_pick_list = this.data.all_pick_list
      let def_pickpu_list = this.data.def_pickpu_list
      let keyword = this.data.keyword
      if (keyword) {
        let arr=all_pick_list.filter( item =>{
          let i = item.pickup_name.indexOf(keyword)
          if (i > -1) {
            return true
          }else{
            return false
          }
        })
        if (arr && arr.length>0) {        
          if(this.data.is_show_sto_cat==1){
            this.setData({
              def_pickpu_list:arr
            })       
          }else{
            this.setData({
              only_pk:arr
            })     
          }
        }else{
          wx.showToast({
            title: '没有搜索到门店',
            icon: 'none',
            duration: 2000
          })
        }
      }else{
        if (this.data.is_show_sto_cat==1) {
          this.setData({
            def_pickpu_list:all_pick_list.slice(0,10)
          })       
        }else{
          this.setData({
            only_pk:all_pick_list
          })     
        }

      }
    }else{   //分类下搜索
      let sec_i=this.data.sec_i
      let all_sto = this.data.all_sto
      let old_all_sto = this.data.old_all_sto
      if (!old_all_sto) {
        this.setData({
          old_all_sto:JSON.parse(JSON.stringify(all_sto))
        })
      }
      let sec_sto= this.data.sec_sto
      let sec_arr = this.data.old_all_sto[sec_i].s_arr
      let keyword = this.data.keyword
      let text='sec_sto.s_arr'
      if (keyword) {
        let arr=sec_arr.filter( item =>{
            let i = item.pickup_name.indexOf(keyword)
            if (i > -1) {
              return true
            }else{
              return false
            }
        })
        if (arr && arr.length>0) {
          this.setData({
            [text]:arr
          })                
        }else{
          wx.showToast({
            title: '没有搜索到门店',
            icon: 'none',
            duration: 2000
          })
        }
      }else{
        if(this.data.old_all_sto){
          this.setData({
            [text]: this.data.old_all_sto[sec_i].s_arr
          })
        }else{
          this.setData({
            [text]: all_sto[sec_i].s_arr
          })
        }     

      }


    }
  },
  //购买礼包
  GetBuyPrice: function (e) {

    var th = this;
    var index = e.currentTarget.dataset.index; //活动id
    var sele_g=th.data.wareCard[index];
    this.data.payMoney=sele_g.payMoney;

    th.setData({sele_g:sele_g,buyType:2,})
    if(sele_g.is_pickup){
        if(sele_g.pickup_list && th.data.def_pick_store){
           com.check_def_pk(th);
        }
        com.get_sto(th,os)
        th.setData({
            openSpecModal:1
        })
    }else{

        if(this.data.submit) return false;

        var my_confirm = th.selectComponent("#my_confirm"); //组件的id
        my_confirm.open(
            "是否确定购买该礼包",
            "取消",
            "确定",
            function () {
                my_confirm.open_cancel(0);
            },
            function () {
                my_confirm.open_cancel(0);
                com.buy_libao(th)
            }

        )
    }





  },
  // 积分兑换
  GetBuyIntegral: function (e) {
      var th = this;
      var index = e.currentTarget.dataset.index; //活动id
      var sele_g=th.data.wareCard[index];
      th.setData({sele_g:sele_g, buyType:1,})
      if(sele_g.is_pickup){
          if(sele_g.pickup_list && th.data.def_pick_store){
              com.check_def_pk(th);
          }
          com.get_sto(th,os)
          th.setData({
              openSpecModal:1
          })
      }else {

          if(this.data.submit) return false;

          var my_confirm = th.selectComponent("#my_confirm"); //组件的id
          my_confirm.open(
              "是否确定兑换该礼包",
              "取消",
              "确定",
              function () {
                  my_confirm.open_cancel(0);
              },
              function () {
                  my_confirm.open_cancel(0);
                  com.buy_libao(th)
              })
      }

  },
  //免费领取
  GetFree: function (e) {

      var th = this;
      var index = e.currentTarget.dataset.index; //活动id
      var sele_g=th.data.wareCard[index];
      th.setData({sele_g:sele_g, buyType:3,})

      if(sele_g.is_pickup){
          if(sele_g.pickup_list && th.data.def_pick_store){
              com.check_def_pk(th);
          }
          com.get_sto(th,os)
          th.setData({
              openSpecModal:1
          })
      }else {
          if(this.data.submit) return false;

          var my_confirm = th.selectComponent("#my_confirm"); //组件的id
          my_confirm.open(
              "是否确定领取该礼包",
              "取消",
              "确定",
              function () {
                  my_confirm.open_cancel(0);
              },
              function () {
                  my_confirm.open_cancel(0);
                  com.buy_libao(th)
              })
      }
  },

  getList: function (e) {

    if(this.data.ismore) return false;
    if(this.data.searching) return false;
    this.data.searching=1;

    wx.showLoading({
      title: '加载中.',
    })

    var th = this;
    let r_q={
      storeId: th.data.getStorageID, //商家ID
      userId: th.data.getUserID, //用户ID
      page: th.data.curpage,
      pageSize: th.data.pageSize,
      is_share:0
    };

    if(this.data.sear_key){
        r_q.key_str=this.data.sear_key;
    }

    getApp().request.get('/api/weshop/marketing/giftbag/page', {
      isShowLoading: true,
      data: r_q,
      success: function (res) {

        th.data.searching=0;
        
        if (res.data.code == 0) {
          th.data.curpage++;
          var arr1 = th.data.wareCard;
          var arr2 = res.data.data.pageData;
          for (let j = 0; j < arr2.length; j++) {
              arr2[j].starTime1=Date.parse(new Date(arr2[j].starTime.replace(/-/g, "/")))/1000
          }

          var arr3 = [...arr1, ...arr2];
          var ismore = 0;
          if (arr3.length == res.data.data.total) ismore = 1
          th.setData({
            wareCard: arr3,
            total: res.data.data.total,
            ismore: ismore,
            is_read: 1,
            is_get:1
          }), wx.stopPullDownRefresh(); //停止下拉刷新

        } else {
          th.setData({
            is_read: 1,
            ismore: 1,
            is_get:1
          })
        }

        wx.hideLoading();

      }
    })

  },
  //销毁界面跳转
  redirectTo: function (e) {
    var th = this;
    var url = e.currentTarget.dataset.url;
    //销毁跳转
    wx.redirectTo({
      url: url
    });
  },
  //不销毁界面跳转
  navigateTo: function (e) {
    var th = this;
    var url = e.currentTarget.dataset.url;
    getApp().goto(url);

  },
  //下拉事件
  onReachBottom: function () {
    var th = this;
    if (th.data.total <= th.data.pageSize) return;
    if (th.data.ismore) return;

    th.getList();
  },
  //图片失败，默认图片
  bind_bnerr2: function (e) {
    var _errImg = e.target.dataset.errorimg;
    var _errObj = {};
    _errObj[_errImg] = "/miniapp/images/default_g_img.gif";
    this.setData(_errObj) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ; 
  },
  goto: function (e) {
    var th = this;
    var url = e.currentTarget.dataset.url;
    getApp().goto(url);
  },

  onShareAppMessage: function (e) {
    getApp().globalData.no_clear=1;
    var curPage = this;
    var pagePath = curPage.route; //当前页面url
    if (pagePath.indexOf('/') != 0) {
      pagePath = '/' + pagePath;
    }
    pagePath += "?first_leader=" + this.data.getUserID;
    return {
      title: "专享礼包",
      path: pagePath,
    }
  },

    // 分享朋友圈
    onShareTimeline() {
        getApp().globalData.no_clear=1;

        var user_id=getApp().globalData.user_id;
        if(!user_id) user_id=0;

        return {
            title: '专享礼包',
            imageUrl: this.data.ad_data.ad_code,
            query: 'first_leader='+user_id
        }
    },



    //--- 设置一下默认库存的数量 ----
    set_def_storage(ee) {
        var that = this, th = this;
        that.data.fir_def_store = ee;
        that.setData({
            def_pick_store: ee,
            sto_sele_name: ee.pickup_name,
            sto_sele_id: ee.pickup_id,
            sto_sele_distr: ee.distr_type
        })
    },
    // 选择门店
    choice_store: function (ee) {
      this.setData({
        keyword:''
      })
        //--先判断会员状态--
        var 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;
        }

        var th = this;
        var ind = ee.currentTarget.dataset.ind;
        var bconfig = th.data.bconfig;

        //如果开启了，则不在选择门店
        if(this.data.sys_switch.is_pricing_open_store && getApp().globalData.pk_store){
            return false;
        }

        if (!th.data.only_pk && !th.data.def_pickpu_list) {
            getApp().confirmBox("门店库存不足", null, 25000, !1);
            return false;
        }

        if (th.data.only_pk && !th.data.only_pk.length) {
            getApp().confirmBox("门店库存不足", null, 25000, !1);
            return false;
        }
        if (th.data.def_pickpu_list && !th.data.def_pickpu_list.length) {
            getApp().confirmBox("门店库存不足", null, 25000, !1);
            return false;
        }


        if (bconfig && bconfig.is_sort_storage) {
            wx.getLocation({
                type: 'gcj02',
                success: function (res) {

                    th.data.lat = res.latitude;
                    th.data.lon = res.longitude;
                    th.data.is_get_local_ok = 1;
                    th.setData({
                        is_gps: 1
                    });
                    //th.onShow();
                    com.get_sto(th,os);
                },
                fail: function (res) {
                    //th.onShow();
                    th.data.is_get_local_ok = 1;
                    com.get_sto(th,os);
                    if (res.errCode == 2) {
                        th.setData({
                            is_gps: 0
                        });
                        if (th.data.is_gps == 0) {
                            getApp().confirmBox("请开启GPS定位", null, 25000, !1);
                        }
                    } else {
                        th.setData({
                            is_gps: "3"
                        });
                    }

                }
            })
        } else {
            th.data.is_get_local_ok = 1;
            com.get_sto(th,os);
        }

        if (ind != undefined && ind != null) {
            this.setData({
                open_ind_store: ind,
                store: 1,
                openSpecModal: !1,
                openSpecModal_pt: !1,
                openSpecModal_flash_normal: !1,
            })
        } else {
            this.setData({
                store: 1,
                openSpecModal: !1,
                openSpecModal_pt: !1,
                openSpecModal_flash_normal: !1

            })
        }
    },
    //关闭选择门店
    close_popup: function (e) {
        var th = this;
        this.setData({
            store: 0,
            choice_sort_store: 0,
            sort_store: 0,
            fir_pick_index: 0,
            sec_pick_index: 0
        })

        var openindstore = this.data.open_ind_store;
        if (openindstore == 1) {
            th.setData({
                openSpecModal: !0,
                openSpecModal_ind: openindstore,
            });
        } else if (openindstore == 2) {
            th.setData({
                openSpecModal: !0,
                openSpecModal_ind: openindstore,
            });
        }
        else if (openindstore == 4) { //4就是拼团
            th.setData({
                openSpecModal_pt: 1,      //打开拼团购买界面
                store: 0,                 //关闭门店
                choice_sort_store: 0,     //关闭门店2级
                sort_store: 0,             //关闭门店2级
            });
        }
        else {
            th.setData({
                store: 0,
                choice_sort_store: 0,
                sort_store: 0
            })
        }


    },

    //选择更多门店
    more_store: function () {
        this.setData({
            sort_store: 1
        });
    },
    // 返回按钮
    returns: function () {
        this.setData({
            sort_store: 0,
            choice_sort_store: 0
        });
    },
    //---选择分类门店---
    choice_sort_store: function (e) {
        var index = e.currentTarget.dataset.index;
        var region_name = e.currentTarget.dataset.region;
        var item = this.data.all_sto[index];
        this.setData({
            region_name: region_name,
            sort_store: 0,
            choice_sort_store: 1,
            sec_sto: item,
            sec_i:index,
            sec_pick_index: 0
        });
    },

    choose_for_store_fir: function (e) {
        var index_c = e.currentTarget.dataset.ind;
        var th = this;
        th.setData({
            fir_pick_index: index_c
        })

    },

    //确定def_pick为选择的门店
    sure_pick: function (e) {
        var th = this;
        var item = null;
        var openindstore = th.data.open_ind_store;

        if (th.data.choice_sort_store == 0) {
            var index = th.data.fir_pick_index;
            if (th.data.is_show_sto_cat == 1) {
                item = th.data.def_pickpu_list[index];
            } else {
                item = th.data.only_pk?th.data.only_pk[index]:null; //当没有门店分类的时候
            }

        } else {
            var index = th.data.sec_pick_index;
            item = th.data.sec_sto.s_arr[index];
        }

        if(!item) return false;

        if (!th.data.sele_g) return false;

            th.setData({
                def_pick_store: item,
                sto_sele_name: item.pickup_name,
                sto_sele_id: item.pickup_id,
                sto_sele_distr: item.distr_type,
                store: 0,
                choice_sort_store: 0,
                fir_pick_index: 0,
                openSpecModal: !0,
            });


    },
    //---点击二级之后的选择---
    choose_for_store: function (e) {
        var index_c = e.currentTarget.dataset.ind;
        var th = this;
        th.setData({
            sec_pick_index: index_c,
            fir_pick_index: index_c
        })

    },
    //把选择的门店设置成默认的门店def_pick
    set_def_pick: function (e) {
        var th = this;
        var item = null;
        if (th.data.choice_sort_store == 0) {
            var index = th.data.fir_pick_index;
            if (th.data.is_show_sto_cat == 1) {
                item = th.data.def_pickpu_list[index];
            } else {
                item = th.data.only_pk?th.data.only_pk[index]:null; //当没有门店分类的时候
            }
        } else {
            var index = th.data.sec_pick_index;
            item = th.data.sec_sto.s_arr[index];
        }

        if(!item) return false;

        th.setData({
                def_pick_store: item,
                sto_sele_name: item.pickup_name,
                sto_sele_id: item.pickup_id,
                sto_sele_distr: item.distr_type,
                store: 0,
                choice_sort_store: 0,
                openSpecModal: !0,
            });

        var user_id=getApp().globalData.user_id;
        var def_pickup_id = item.pickup_id;
        getApp().request.put('/api/weshop/users/update', {
            data: {
                user_id: user_id,
                def_pickup_id: def_pickup_id
            },
            success: function (res) {
                if (res.data.code == 0) {
                    if (th.data.choice_sort_store == 0) th.setData({
                        fir_pick_index: 0
                    });
                    getApp().globalData.pk_store = item;
                } else {
                    getApp().my_warnning("设置默认门店地址失败", 0, th)
                }

            }
        });



    },
    closeSpecModal: function () {
        this.setData({openSpecModal: 0});
    },

    buy_libao:function () {
        com.buy_libao(this)
    },

    search_lb(){
       this.data.curpage=0;
       this.searching=0;  
       this.setData({ismore:0,is_get:0,wareCard:[]});
       this.getList(); 
    },

    input_sear(e){
       let value = e.detail;
       this.data.sear_key=value;
    }

})