// packageA//pages/distribution/commision/commision.js
const app = getApp();
let self = null;
var os = app.globalData.setting,
  ut = require("../../../../utils/util.js");


Page({

  /**
   * 页面的初始数据
   */
  data: {
    isInputFocus: false,//记录搜索输入框是否聚焦
    inputVal: '',//记录搜索输入框的内容
    isSort: false,//控制排序开关状态，true开启排序
    isDescending: false, //isDescending降序，ascending升序
    imghost: '',
    url: os.imghost,
    tabArr: ['最新', '销量', '评论', '价格'],
    currentTabIndex: 0,
    isShowRow: false,//控制视图切换状态
    isHiddenDropdown: true,//控制筛选下拉菜单显隐
    list: [],
    isLoading: false, // 检测是否已经发送请求,防止重复发送请求
    noMore: false, // 检测是否有更多数据,true为没有更多数据,false为还有数据
    pageNum: 1, // 当前页数
    rank_switch: false,
    card_field: "",
    card_name: "",
    max_card_field: "",
    card_list: null,
    isAll: true,
    is_no_plus:1,
    default_img: '/miniapp/images/default_g_img.gif',
    is_distribut:0, //是否是分销
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    console.log("-- shop：load --");
    console.log(options);

    wx.setNavigationBarTitle({
      title: "我的小店",
    });

    self = this;//保存全局指针
    app.isLogin().then(function (data) {//进入页面前已经授权登录成功
      self.setData({
        userInfo: data,
      });
    });
    //从别人的分享的跳转过来
    var first_leader = decodeURIComponent(options.first_leader);
    if (first_leader && first_leader != 'undefined') {

      console.log("-- shop：load2 --");
      console.log("-- shop：load3 --"+first_leader);

      getApp().globalData.first_leader = first_leader;
      this.data.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
        }
      })


      getApp().request.get("/api/weshop/users/get/" + os.stoid + "/" + first_leader, {
        isShowLoading: false,
        data: { r: Math.random() },
        success: function (e) {
          if (e.data.code == 0) {
            self.setData({
              userInfo2: e.data.data,
            });
          };

        },
      });

    }

    if (options && options.brand_id) {
      this.setData({
        brand_id: options.brand_id,
        is_router:true
      })
      // this.getData(true, '/api/weshop/users/distribut/pagemyshop', this.data.currentQuery);
    }
    if (options && options.nation_id) {
      this.setData({
        nation_id: options.nation_id,
        is_router:true
      })
      // this.getData(true, '/api/weshop/users/distribut/pagemyshop', this.data.currentQuery);
    }

    getApp().promiseGet("/api/weshop/storeDistribut/get/"+os.stoid,{}).then(rs=>{
      var dis=rs.data.data;
      if( dis){
        self.setData({storeDistribut:dis})
      }
    })


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    getApp().check_can_share();

    //自己登录的
    if (app.globalData.userInfo && !this.data.first_leader) {
      if (!this.data.isLogin) {
        this.setData({
          userInfo: app.globalData.userInfo,
          imghost: app.globalData.setting.imghost,
          isLogin: true,
          currentQuery: {
            store_id: app.globalData.setting.stoid,
            user_id: app.globalData.user_id,
            isnewwhere:1
          },
        });
        !this.data.is_router&&this.initData();
        this.data.is_router&&this.getData(true,"/api/weshop/users/distribut/pagemyshop?orderType=desc",this.data.currentQuery);
        let total=wx.getStorageSync('total');
        let newListTotal=wx.getStorageSync('newListTotal');
        if(total>0&&newListTotal>0){
          this.setData({
            total,
            newListTotal
          })
        }
      };
    }
    //被人分享点击开的
    else if (this.data.first_leader) {
      console.log(11);
      this.setData({
        imghost: app.globalData.setting.imghost,
        currentQuery: {
          store_id: app.globalData.setting.stoid,
          user_id: this.data.first_leader,
        },
        isLogin: true,
      });
      console.log('fenxiang');
      // 请求数据
      this.getData(true, '/api/weshop/users/distribut/pagemyshop', this.data.currentQuery);
      // 新品
      app.request.promiseGet('/api/weshop/users/distribut/pagemyshop?type=2', {
        data: self.data.currentQuery,
      }).then(res => {
        self.setData({
          newList: res.data.data,
        });
      });
      // 广告banner
      app.request.promiseGet("/api/weshop/ad/page", {
        data: {
          pid: 401,
          enabled: 1,
          store_id: app.globalData.setting.stoid,
        }
      }).then(res => {
        if (res.data.code == 0 && res.data.data) {
          let item = res.data.data.pageData[0];
          if (item && item.ad_code) {
            self.setData({
              ad_img: item.ad_code,
            });
          };
        };
      });
    }
    var th = this;
    //更新一下会员的信息
    if (getApp().globalData.user_id) {
      if (getApp().globalData.userInfo['is_distribut']) {
        th.setData({ is_distribut: 1 })
      }
      getApp().request.get("/api/weshop/users/get/" + os.stoid + "/" + getApp().globalData.user_id, {
        isShowLoading: false,
        success: function (e) {
          getApp().globalData.userInfo = e.data.data;
          getApp().getConfig2(function (e) {
            var swithc_list = e.switch_list;
            var sw_arr = JSON.parse(swithc_list);
            //---如果后台有开等级卡的开关---
            if (sw_arr.rank_switch && sw_arr.rank_switch == "2") {
              th.setData({
                rank_switch: true
              });
              //---回调卡的列表---
              th.getPlusCardType(function (ob) {
                th.setData({
                  card_list: ob.card_list
                });
                var ti = setInterval(function () {
                  var user = getApp().globalData.userInfo;
                  if (!user) return false;
                  clearInterval(ti);
                  if (user.card_field && user['card_expiredate']) {
                    var str = user['card_expiredate'].replace(/-/g, '/');
                    var end = new Date(str);
                    end = Date.parse(end) / 1000;
                    var now = ut.gettimestamp();
                    //--- 判断是等级会员，且在有效期范围内 ---
                    if (user.card_field && now < end) {
                      var card_name = ob.name_map.get(user.card_field);
                      if (card_name && card_name.length > 4) card_name = card_name.substring(0, 8);
                      th.setData({
                        card_field: user.card_field,
                        card_name: card_name,
                        card_list: ob.card_list
                      });
                    }
                  }
                }, 500)
              })
            }
          })
        }
      })
      //调用接口判断商家plus有没有过期
      getApp().request.promiseGet("/store/storemoduleendtime/page?store_id=" + os.stoid + "&type=3", {}).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) {
                th.setData({ is_no_plus: 0 })
              }
            }
          }
        }
      })
    }

    if (app.globalData.key_word) {
      this.setData({
        inputVal: app.globalData.key_word,
      })
      this.search();
    };
  },
  //初始化数据
  initData() {
    
    // 全部商品
    app.request.promiseGet('/api/weshop/users/distribut/pagemyshop?orderType=desc', {
      data: this.data.currentQuery,
    }).then(res => {
      wx.setStorageSync('total', res.data.data.total);
      this.setData({
        total: res.data.data.total,
        list:res.data.data.pageData,
      });
    });
    // 新品
    app.request.promiseGet('/api/weshop/users/distribut/pagemyshop?type=2&orderType=desc', {
      data: this.data.currentQuery,
    }).then(res => {
      wx.setStorageSync('newListTotal', res.data.data.total);
      this.setData({
        newListTotal: res.data.data.total,
      });
    });
    
    // 广告banner
    app.request.promiseGet("/api/weshop/ad/page", {
      data: {
        pid: 401,
        enabled: 1,
        store_id: app.globalData.setting.stoid,
      }
    }).then(res => {
      if (res.data.code == 0 && res.data.data) {
        let item = res.data.data.pageData[0];
        if (item && item.ad_code) {
          this.setData({
            ad_img: item.ad_code,
          });
        };
      };
    });
    // }
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('onun');
    app.globalData.key_word = null;
    app.globalData.nid = null;
    app.globalData.bid = null;
    // wx.removeStorageSync(key);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let url = '';
    if (this.data.isAll) {
      url = '/api/weshop/users/distribut/pagemyshop';
    } else {
      url = '/api/weshop/users/distribut/pagemyshop?type=2';
    };
    this.scrollToLower(url, this.data.currentQuery);
  },

  /**
   * 用户点击右上角分享
   *--点击分享事件--分享我的小店
   *--*/
  onShareAppMessage: function (t) {

    getApp().globalData.no_clear=1;
    var th = this;
    var title = "我的小店";

    if(this.data.storeDistribut){
      title=this.data.storeDistribut.distributSharetitle;
      title+=" "+this.data.storeDistribut.distributShareremark;
    }

    var user_id = this.data.first_leader;
    if (!user_id) {
      user_id = getApp().globalData.user_id
    }
    var url = "/packageA/pages/distribution/shop/shop?scene=" + user_id;
    if (getApp().globalData.user_id) {
      url += "&first_leader=" + getApp().globalData.user_id;
    }

    var ob = {
      title: title,path: url,
    };
    return ob;

  },

  /**
   * 点击下拉菜单
   */
  clickDropdown() {
    this.setData({
      isHiddenDropdown: !this.data.isHiddenDropdown,
    });
  },

  /**
   * 点击遮罩层
   */
  clickMask() {
    this.setData({
      isHiddenDropdown: true,
    });
  },

  /**
   * 选择下拉菜单项
   */
  selectDropdown(e) {
    let currentIndex = e.target.dataset.index;
    this.setData({
      isHiddenDropdown: true,
      currentSelect: this.data.dropdownArr[currentIndex],
    });
  },

  /**
   * 搜索输入框聚焦
   */
  inputFocus() {
    this.setData({
      isInputFocus: true,
    });
  },


  /**
   * 搜索输入框失焦
   */
  inputBlur() {
    this.setData({
      isInputFocus: false,
    });
  },

  /**
   * 获取搜索输入框输入的内容
   */
  input(e) {
    this.data.inputVal = e.detail.value;
  },

  /**
   * 搜索输入框清空内容
   */
  inputClear() {
    let inputVal = this.data.inputVal;
    console.log('input', inputVal);
    if (inputVal) {
      this.setData({
        inputVal: '',
      });
    };
  },

  /**
   * 搜索输入框聚焦
   */
  search() {
    let data = this.data.currentQuery;
    data.key = this.data.inputVal;
    delete data.page;
    delete data.brand_id;
    delete data.nation_id;
    this.setData({
      currentTabIndex: this.data.currentTabIndex,
      isSort: false,
      isDescending: false,
      currentQuery: data,
      pageNum: 1,
    });
    this.getData(true, '/api/weshop/users/distribut/pagemyshop', data);
    app.globalData.key_word=null;
  },

  /**
   * 点击排序
   */
  clickSort(e) {
    let data = this.data.currentQuery;
    // data.orderField = 'shop_price';
    data.orderField = 'final_price';
    if (data.page) {
      delete data.page;
    };
    if (!this.data.isSort) {
      this.setData({
        isSort: true,
      });
      data.orderType = 'asc';
    } else {
      this.setData({
        isDescending: !this.data.isDescending,
      });

      if (this.data.isDescending) {
        data.orderType = 'desc';
      } else {
        data.orderType = 'asc';
      };

    };
    console.log('当前参数:', data);

    this.setData({
      currentQuery: data,
      noMore: false,
    });

    // 请求数据
    this.getData(true, '/api/weshop/users/distribut/pagemyshop', data);
  },

  /**
   * 点击视图切换按钮
   */
  change() {
    this.setData({
      isShowRow: !this.data.isShowRow
    });
  },

  /**
   * 点击Tab
   */
  clickTab(e) {
    let data = this.data.currentQuery;
    let isSort = this.data.isSort;
    let currentIndex = e.target.dataset.index;
    if (currentIndex != 3) {
      if (isSort) {
        isSort = false;
      };
      if (data.orderType) {// 清除orderType
        delete data.orderType;
      };
    };
    this.setData({
      list: null,
      isAll: true,
      currentTabIndex: currentIndex,
      isSort,
      pageNum: 1,
      noMore: false,
    });
    if (data.page) {// 清除page
      delete data.page;
    };
    if (currentIndex == 0) {
      // if (data.orderField) {// 清除orderField
      //   delete data.orderField;
      // };
      data.orderField = 'shop_price';
    };
    if (currentIndex == 1) {
      data.orderField = 'sales_sum';
    };
    if (currentIndex == 2) {
      data.orderField = 'comment_count';
    };

    if (currentIndex == 3) {
      // console.log('点击价格');
      // if (data.orderType) {// 清除orderType
      //   delete data.orderType;
      // };
      data.orderType = 'desc';
      return;
    };


    data.orderType = 'desc';
    this.data.currentQuery = data;
    delete data.brand_id;
    delete data.nation_id;
    console.log(data);
    this.getData(true, '/api/weshop/users/distribut/pagemyshop', data);
  },

  /**
   * 点击筛选
   */
  clickFilter() {
    this.setData({
      isHiddenDropdown: !this.data.isHiddenDropdown,
    });
  },

  /**
   * 点击遮罩层，关闭筛选下拉菜单
   */
  clickMask() {
    if (!this.data.isHiddenDropdown) {
      this.setData({
        isHiddenDropdown: true,
      });
    }
  },

  /**
   * 请求数据
   */
  getData: function (isInit, url, data) {
    let { brand_id, nation_id } = this.data;
    if (brand_id - 0) {
      delete data.nation_id;
      // delete data.key;
      data.brand_id = brand_id;
      this.data.brand_id=null;
    };
    if (nation_id - 0) {
      delete data.brand_id;
      // delete data.key;
      data.nation_id = nation_id;
      this.data.nation_id=null;
    };
    app.request.promiseGet(url, {
      data: data,
      isShowLoading: true,
    })
      .then(function (res) {
        // console.log('1121', res.data.code);
        if (res.data.code == 0) {

          self.setData({
            isLoading: false,
            // is_router:false,
          });

          if (isInit) {// 第一次加载
            console.log('first',res);
            self.setData({
              list: res.data.data.pageData,
            });
            console.log(self.data.list);
          } else {
            self.setData({
              list: self.data.list.concat(res.data.data.pageData)
            });
          };

          if ((res.data.data.pageData.length == 0) || (res.data.data.pageSize * res.data.data.page >= res.data.data.total)) {
            self.setData({
              noMore: true
            });
          };

        } else {
          self.setData({
            list: []
          });
        };

      })
      .catch(function (err) {
        console.log('出错拉！！！！', err);
        self.setData({
          list: []
        });
      });
  },


  /**
   * 上拉加载
   */
  scrollToLower(url, requestData) {

    // 数据总量
    let total = this.data.list.total;
    // 单页最大数据量
    let pageSize = this.data.list.pageSize;
    // 如果数据总量不为0且小于或等于单页最大数据量，说明数据已全部加载，显示‘没有更多了’
    if ((total != 0) && (total <= pageSize)) {
      this.setData({
        noMore: true
      });
    };

    if (!this.data.isLoading && !this.data.noMore) {
      this.setData({
        isLoading: true,
        pageNum: this.data.pageNum + 1
      });
      requestData.page = this.data.pageNum;
      console.log('滚动data:', requestData);
      this.getData(false, url, requestData);
    };
  },

  /**
   * 点击跳转
   */
  goto(e) {
    let url = '';
    if (e.target.dataset.url) {
      url = e.target.dataset.url;
    } else {
      url = e.currentTarget.dataset.url;
    }
    app.goto(url);
  },


  //--- 获取卡类列表 ---
  getPlusCardType: function (func) {
    var storid = os.stoid;
    var th = this;
    getApp().request.promiseGet("/api/weshop/plus/vip/mem/bership/list?" + "storeId=" + storid,
      {}).then(res => {

        if (res.data.code != 0 || !res.data.data) {
          var ob = {
            "card_list": [],
            "name_map": ""
          };
          func(ob);
          return false;
        }

        var plusCard = res.data.data;
        var arr = [1219, 2089, 3031];
        var new_arr = new Array();
        var card_name_map = new Map();

        var user = getApp().globalData.userInfo;
        if (plusCard) {
          for (var i = 0; i < plusCard.length; i++) {
            if ((!user || user.card_field == null || user.card_field == "") && (plusCard[i].IsStopBuy == true)) {
              continue;
            }
            var name = "card" + plusCard[i].CorrPrice.toLowerCase();
            card_name_map.set(name, plusCard[i].CardName);
            new_arr.push(plusCard[i]);

          }
        }
        var ob = {
          "card_list": new_arr,
          "name_map": card_name_map
        };
        func(ob);
      })
  },


  /**
   * 点击全部
   */
  clickAll() {
    let data = this.data.currentQuery;
    if (data.page) delete data.page;
    if (data.orderField) delete data.orderField;
    if (data.orderType) delete data.orderType;
    if (data.key) delete data.key;
    delete data.brand_id;
    delete data.nation_id;
    this.setData({
      pageNum: 1,
      noMore: false,
      isAll: true,
    });

    this.getData(true, '/api/weshop/users/distribut/pagemyshop', data);
  },

  /**
   * 点击新品
   */
  clickNew() {
    let data = this.data.currentQuery;

    delete data.page;
    delete data.orderField;
    delete data.orderType;
    delete data.key;
    delete data.brand_id;
    delete data.nation_id;
    this.setData({
      pageNum: 1,
      noMore: false,
      isAll: false,
    });

    this.getData(true, '/api/weshop/users/distribut/pagemyshop?type=2&orderType=desc', data);
    // app.request.promiseGet('/api/weshop/users/distribut/pagemyshop?type=2', {
    // 	data: data,
    // }).then(res => {
    // 	self.setData({
    // 		list: res.data.data,
    // 	});
    // });
  },


  /**
   * 点击新品
   */
  // imgError(e) {
  // 	this.setData({
  // 		noImg: true,
  // 	});
  // },


  bind_bnerr2: function (e) {
    var _errImg = e.target.dataset.errorimg;
    var _errurl = e.target.dataset.url;
    var ii = _errurl.indexOf(oo.imghost);
    if (ii != -1) {
      var _errObj = {};
      _errObj[_errImg] = this.data.iurl + "/miniapp/images/default_g_img.gif";
      this.setData(_errObj) //注意这里的赋值方式,只是将数据列表中的此项图片路径值替换掉 ; 
    }
  },

})