var app = getApp();
import tool from "../../utils/util";
Page({
  data: {
    language: {},
    // 商品列表数据
    goodsData: [],
    // banner数据
    bannerData: [{
      'thumb': ''
    }],
    adPlace: [], //广告位
    params: {},
    // menu
    memuData: [],
    // 是否显示面板指示点
    indicatorDots: true,
    // 方向
    vertical: false,
    // 是否自动切换
    autoplay: true,
    // 自动切换时间间隔
    interval: 4000,
    // 滑动动画时长
    duration: 300,

    designerItem: [],
    isDesigner: false,
    pageinfo: {},

    designer: '',
    readyshow: false,
    defaultdata: '',
    last_page: '',
    isLoadMore: false,
    page: 1,
    footshow: false,
    fullShow: false,
    popShow: false,
    advertisement: {},
    bottomShowBol: false,
    bottomShowBolIndex: 0,
    isWatch: true,
    everyTime: false,
    showNewcomerAward: false, //是否显示新人奖
    new_member_prize: {}, //新人奖奖品信息

    //新装修
    page_id: 0,
    components: [],
    advertising: {},
    full_screen: {},
    top_info: {},
    bottom_info: {},
    mailInfo: {},
    clientWidth: '375',
    btnFlag: false,
    foot_type: '',

    current_page: 1,
    total_page: 0,
    decorate_isLoadMore: true,
    lastIndex: '',

    showPage: true,

    showShare: false,
    shareOptions: [{
      name: '分享给好友',
      icon: 'wechat',
      openType: 'share'
    }],
    goodshare_info: {},

    //慈善基金海报相关参数
    charityFundInfo: {
      show: false,
      poster: ''
    },
  },
  componentGoodShares(e) {
    if (e.detail) {
      this.setData({
        goodshare_info: e.detail,
        showShare: true
      });
    }
  },
  onClose() {
    this.setData({
      goodshare_info: {},
      showShare: false
    });
  },
  onSelect() {
    this.setData({
      showShare: false
    });
  },
  // 分享
  onShareTimeline() {
    var value = wx.getStorageSync('yz_uid');
    var mid = '';
    if (value) {
      mid = value;
    }
    let navtitle = wx.getStorageSync('pageinfo');
    return {
      title: navtitle.desc,
      query: `mid=${mid}`
    };
  },
  onShareAppMessage: function (e) {
    var value = wx.getStorageSync('yz_uid');
    var mid = '';
    if (value) {
      mid = value;
    }
    if (e && e.from == 'button' && e.target.dataset.tag == "shareTag") {
      // 拼团活动二开#73727 弹窗邀请朋友
      if (e.target.dataset.item == '1') {
        let _path = '/packageB/member/group/GroupDetail/GroupDetail?id=' + e.target.dataset.info.id + '&mid=' + mid;
        let _title = e.target.dataset.title;
        if (e.target.dataset.store) {
          _path = '/packageB/member/group/GroupDetail/GroupDetail?id=' + e.target.dataset.info.id + 'store=' + e.target.dataset.store + '&mid=' + mid;
        }
        if (app.globalData.store_alone_temp == 1 && that.globalData.STORE_ID) {
          _path = `${_path}&store_alone_id=${app.globalData.STORE_ID}`;
        }
        return {
          path: _path,
          title: _title
        };
      }
    }
    let navtitle = wx.getStorageSync('pageinfo');
    let _params = {
      title: navtitle.desc,
      path: '/packageG/index/index?mid=' + mid
    };
    if (JSON.stringify(this.data.goodshare_info) != "{}" && e.from == "button") {
      _params.title = this.data.goodshare_info.name,
      _params.path = '/packageA/detail_v2/detail_v2?id=' + this.data.goodshare_info.id + '&mid=' + mid,
      _params.imageUrl = this.data.goodshare_info.img;
    }
    this.data.goodshare_info = {};
    return _params;
  },
  onLoad: function (options) {
    //判断是否需要显示慈善基金海报
    if (options.is_charity_fund && options.is_charity_fund == 1) {
      this.getCharityFundPoster(options.order_id);
    }

    wx.showShareMenu({
      withShareTicket: false,
      menus: ['shareAppMessage', 'shareTimeline']
    });

    let mapstatus = wx.getStorageSync('address-status');
    // console.log(mapstatus)
    if (mapstatus == 1) {
      let maplist = wx.getStorageSync('address-point');
      console.log(maplist, "有选择的地址");
    } else {
      console.log('没有选择的地址就定位当前位置');
    }
    // console.log(options)

    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      console.log(scene, '21668');
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(',');
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split('=');
          if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          }
        }
      }
    }
    try {
      const updateManager = wx.getUpdateManager();
      updateManager.onUpdateReady(function () {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success(res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate();
            }
          }
        });
      });
    } catch (err) {
      console.error(err);
    }
    if (options.mid) {
      app._setMid(options.mid);
    }

    let new_decorate = wx.getStorageSync("new_decorate");
    let home_onUnload = wx.getStorageSync('home_onUnload');
    let basic_info = wx.getStorageSync("yz_basic_info");
    if (home_onUnload == 1 && new_decorate) {
      // 页面加载
      this._getOldData(new_decorate);
    } else {
      // 页面加载
      this._getData();
    }
    this.setData({
      mailInfo: basic_info.home ? basic_info.home.mailInfo : {},
      clientWidth: wx.getSystemInfoSync().windowWidth,
    });
  },
  onReady: function () {
    // 页面渲染完成
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });

  },
  onShow: function () {
    // 页面显示
    // if (this.data.everyTime) {
    // 	this.getAdvertise();  旧弹窗
    // }

  },
  onHide: function () {
    // 页面隐藏
    this.setData({
      //关闭新人奖弹窗
      showNewcomerAward: false
    });
  },
  onUnload: function () {
    // 页面关闭
    wx.setStorageSync('home_onUnload', 1);
  },
  onPullDownRefresh: function () {
    // 下拉刷新
    console.log('onPullDownRefresh', new Date());
    this._getData();
  },
  // 获取滚动条当前位置
  onPageScroll: tool.throttle(function (msg) {
    let e = msg[0];

    // 节流
    if (e.scrollTop > 80) {
      if (!this.data.btnFlag) {
        this.setData({
          btnFlag: true
        });
      }
    } else {
      if (this.data.btnFlag) {
        this.setData({
          btnFlag: false
        });
      }
    }

    if (this.data.bottomShowBol) {
      this.setData({
        bottomShowBol: false
      });
    }
  }),
  //获取慈善基金的海报
  getCharityFundPoster(id) {
    let urlStr = app.getNetAddresss("plugin.charity-fund.api.create_new_poster.createPoster");
    app._getNetWork({
      url: urlStr,
      data: {
        order_id: id
      },
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          this.setData({
            'charityFundInfo.show': true,
            'charityFundInfo.poster': res.data
          });
        }
      }
    });
  },
  closeCharityFundPoster() {
    this.setData({
      'charityFundInfo.show': false
    });
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // 加载更多
    if (this.data.defaultdata) {
      if (this.data.isLoadMore) {
        this.getMoreData();
      } else {
        console.log('没有更多数据');
      }
    }
    this.setData({
      bottomShowBol: true,
    });

    if (this.data.decorate_isLoadMore) {
      this.getMoreDecorate();
    }
  },
  closeBtn() {
    //新人奖弹窗关闭按钮
    this.setData({
      showNewcomerAward: false,
    });
    // this.getAdvertise();

    // 新弹窗广告
    let popAdvertisement = wx.getStorageSync('popAdvertisement');
    if (this.data.advertising && this.data.advertising.id && !popAdvertisement) {
      wx.setStorageSync('popAdvertisement', true);
      this.setData({
        popShow: true
      });
    }

    let storage_newAward = wx.getStorageSync("storage_newAward");
    // let new_decorate = wx.getStorageSync("new_decorate");
    console.log("关闭新人奖弹窗======");
    if (storage_newAward) {
      storage_newAward = null;
      // wx.setStorageSync('yz_basic_info', storage_newAward);
      wx.setStorageSync('storage_newAward', storage_newAward);
    }
    // if (new_decorate && new_decorate.plugin && new_decorate.plugin.new_member_prize) {
    //   new_decorate.plugin.new_member_prize = null;
    //   wx.setStorageSync('new_decorate', new_decorate);
    // }
  },
  initBalanceLang(data) {
    if (data && data.balance) {
      try {
        //余额名称
        wx.setStorageSync('balance', data.balance);
      } catch (e) {
        console.log(e);
      }
    }
  },
  checkStoreAlone() {
    if (app.globalData.store_alone_temp == 1) {
      // 门店独立模块
      if (!app.globalData.STORE_ID) {
        // 没有门店id就跳转提示页
        wx.reLaunch({
          url: '/packageG/independent_store/access_tip/access_tip',
        });
      } else {
        // 有就跳首页
        wx.reLaunch({
          url: '/packageG/independent_store/index/index?store_id=' + app.globalData.STORE_ID,
        });
      }
      return true;
    }
    return false;
  },
  _getOldData(home_data) {
    let that = this;
    if (this.checkStoreAlone()) {
      return;
    }

    wx.showLoading({
      title: '加载中'
    });
    this.setData({
      showPage: false
    });

    that.setData({
      footshow: true
    });

    // 装修数据
    let designerItem = home_data.item;

    let _data = home_data.default;
    if (_data) {
      that.setData({
        defaultdata: home_data.default, // 默认模板消息
        last_page: home_data.default.goods.last_page,
        isLoadMore: false,
        page: 1
      });
      that.setData({
        isLoadMore: that.data.last_page > 1
      });
    }

    //爱心值和浏览权限
    let params = designerItem.pageinfo ? designerItem.pageinfo.params : {};
    that.setData({
      params: params,
      designer: home_data.designer ? home_data.designer : '', // 爱心值
      isWatch: params.allowauth == 0 ? false : true
    });
    if (!that.data.isWatch && designerItem.page_info.member_level_url && designerItem.page_info.member_level_url.link &&
      designerItem.page_info.member_level_url.link.indexOf('packageG/index/index') < 0) {
      wx.redirectTo({
        url: designerItem.page_info.member_level_url.link,
      });
    }
    console.log("会员是否可浏览装修页2", that.data.isWatch);

    //标题设置
    if (designerItem.data != '' && (designerItem.page_info && designerItem.page_info.page_title)) {
      wx.setNavigationBarTitle({
        title: designerItem.page_info.page_title ? designerItem.page_info.page_title : that.data.mailInfo.name || ''
      });

      wx.setStorageSync('pageinfo', {
        title: designerItem.page_info.page_title ? designerItem.page_info.page_title : that.data.mailInfo.name,
        desc: designerItem.page_info.page_description
      });
    } else {
      wx.setNavigationBarTitle({
        title: that.data.mailInfo.name || ''
      });
    }
    if (designerItem.page_info && designerItem.page_info.preview_color) {
      wx.setNavigationBarColor({
        backgroundColor: designerItem.page_info.preview_color,
        frontColor: designerItem.page_info.font_color == 1 ? '#ffffff' : '#000000',
        animation: {
          duration: 400,
          timingFunc: 'easeIn'
        }
      });
    }

    // 店铺装修
    if (designerItem.datas) {
      for (let i = 0; i < designerItem.datas.length; i++) {
        // console.log(designerItem.datas[i]);
        if (designerItem.datas[i].component_key == 'U_goods') {
          designerItem.datas[i].index = i;
        }
        if (designerItem.datas[i].component_key == 'U_location') {
          designerItem.datas[i].home = true;
        }
        if (designerItem.datas[i].component_key == 'U_signin') {
          designerItem.datas[i].host = app.data.host;
        }
        designerItem.datas[i].designer = that.data.designer;
      }
      that.setData({
        isDesigner: true,
        decorate_isLoadMore: true,
        designerItem: designerItem.datas,
        page_id: designerItem.id,
        components: designerItem.datas,
        foot_type: designerItem.foot_type
      });

      if (designerItem.page) {
        that.setData({
          total_page: designerItem.page.total_page,
          current_page: designerItem.page.current_page,
          bottomShowBolIndex: designerItem.page.count - 1,
        });
      }

      if (designerItem.page_info) {
        that.setData({
          advertising: designerItem.page_info.advertising_id || {},
          full_screen: designerItem.page_info.full_screen_id || {},
        });

        if (that.data.advertising.id && that.data.advertising.datas) {
          that.data.advertising.datas = JSON.parse(that.data.advertising.datas);
          that.setData({
            advertising: that.data.advertising,
          });
        }
      }

      if (designerItem.top && designerItem.top.id) {
        this.setData({
          top_info: JSON.parse(designerItem.top.page_info)
        });
      }

      // 装修的底部有三种情况
      if (designerItem.foot_type == -1) {
        // 不显示
        this.setData({
          bottom_info: {}
        });
      } else if (designerItem.foot_type == 1) {
        // 显示默认
        if (!designerItem.foot || !designerItem.foot.page_info) {
          // 显示系统默认
          this.setData({
            bottom_info: {}
          });
        } else {
          // 显示列表设置的默认
          this.setData({
            bottom_info: JSON.parse(designerItem.foot.page_info)
          });
        }
      } else if (designerItem.foot_type == 2) {
        // 显示自定义的底部导航
        if (designerItem.foot instanceof Array) {
          this.setData({
            bottom_info: {}
          });
        } else {
          this.setData({
            bottom_info: JSON.parse(designerItem.foot.page_info)
          });
        }
      }

      let fullAdvertisement = wx.getStorageSync('fullAdvertisement');
      if (this.data.full_screen && this.data.full_screen.id && !fullAdvertisement && this.data.full_screen.show_rule === 1) {
        wx.setStorageSync('fullAdvertisement', true);
        this.setData({
          fullShow: true
        });
        setTimeout(() => {
          this.countDown(this.data.full_screen.show_time);
        }, 2000);
      }

      let fullAdvertisement_expiration = wx.getStorageSync('fullAdvertisement_expiration');
      let newTime = parseInt(Date.parse(new Date()) / 1000);

      if (this.data.full_screen && this.data.full_screen.id && this.data.full_screen.show_rule === 2 && fullAdvertisement_expiration < newTime) {
        let timestamp = parseInt((new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1) / 1000); //当天23:59:59
        wx.setStorageSync("fullAdvertisement_expiration", timestamp);
        this.setData({
          fullShow: true
        });
        setTimeout(() => {
          this.countDown(this.data.full_screen.show_time);
        }, 2000);
      }

    } else {
      //默认数据设置开始
      that.setData({
        readyshow: true
      });

      // menu
      var size = 10;
      var _memuData = _data.category;
      var _memuOldData = _memuData;
      var page = Math.ceil(_memuData.length / size);

      // mailInfo
      wx.setStorageSync('pageinfo', {
        title: that.data.mailInfo.name,
        desc: that.data.mailInfo.name
      });

      wx.setNavigationBarTitle({
        title: that.data.mailInfo.name || ''
      });

      // 设置memu height
      var menuHeightClass;

      if (_memuData.length <= 5) {
        menuHeightClass = 'in1';
      } else {
        menuHeightClass = 'in2';
      }

      var dataArray = [];

      for (var i = 0; i < page; i++) {
        var dataArray2 = [];
        for (var j = 0; j < size; j++) {
          var a = _memuData[j];
          if (a != undefined) {
            dataArray2.push(_memuData[j]);
          }
        }
        _memuOldData = _memuOldData.slice(size);

        _memuData = _memuOldData;
        dataArray.push(dataArray2);
      }

      that.setData({
        bannerData: _data.ads,
        goodsData: _data.goods,
        memuData: dataArray,
        footshow: true,
        bottom_info: {},
        // 设置memu height
        menuHeightClass: menuHeightClass,
      });
    }

    that.setData({
      showPage: true
    });
    wx.hideLoading();

    //是否显示新人奖弹窗
    try {
      let storage_newAward = wx.getStorageSync("storage_newAward");
      // 首页这里整合删了
      // console.log("//////////新人奖弹窗111///////////////",home_data.plugin.new_member_prize,storage_newAward)
      // if (home_data && home_data.plugin && home_data.plugin.new_member_prize.prize) {
      //   let _prizeData = home_data.plugin.new_member_prize;
      //   let new_member_prize = {};
      //   new_member_prize.type = _prizeData.activity.background_type;
      //   new_member_prize.title = _prizeData.activity.title;
      //   new_member_prize.awardlist = _prizeData.prize;
      //   if(home_data.plugin.new_member_prize.prize.length == 0){
      //     that.setData({
      //       showNewcomerAward: false,
      //     });
      //   }else{
      //     that.setData({
      //       new_member_prize: new_member_prize,
      //       showNewcomerAward: true,
      //     });
      //   }
      // }else
      if (storage_newAward && storage_newAward.prize) {
        let _prizeData = storage_newAward;
        let new_member_prize = {};
        new_member_prize.type = _prizeData.activity.background_type;
        new_member_prize.title = _prizeData.activity.title;
        new_member_prize.awardlist = _prizeData.prize;
        if (storage_newAward.prize.length == 0) {
          that.setData({
            showNewcomerAward: false,
          });
        } else {
          that.setData({
            new_member_prize: new_member_prize,
            showNewcomerAward: true,
          });
        }
      } else {
        // 旧弹窗广告
        // that.getAdvertise();

        // 新弹窗广告
        let popAdvertisement = wx.getStorageSync('popAdvertisement');
        if (this.data.advertising && this.data.advertising.id && !popAdvertisement && this.data.advertising.show_rule === 1) {
          wx.setStorageSync('popAdvertisement', true);
          this.setData({
            popShow: true
          });
        }

        let popAdvertisement_expiration = wx.getStorageSync('popAdvertisement_expiration');
        let pop_newTime = parseInt(Date.parse(new Date()) / 1000);
        if (this.data.advertising && this.data.advertising.id && this.data.advertising.show_rule === 2 && popAdvertisement_expiration < pop_newTime) {
          let timestamp = parseInt((new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1) / 1000); //当天23:59:59
          wx.setStorageSync("popAdvertisement_expiration", timestamp);
          //每日小程序登录弹出
          this.setData({
            popShow: true
          });
        }
      }
    } catch (e) {
      console.log("新人奖报错：：：", e);
    }

  },
  _getData: function () {
    let that = this;
    if (this.checkStoreAlone()) {
      return;
    }
    let urlstr = app.getNetAddresss('home-page.wxapp');
    wx.showLoading({
      title: '加载中'
    });
    this.setData({
      showPage: false
    });

    app._getNetWork({
      // url: app.getNetAddresss("home-page.index")//这是微信商城首页的接口,
      url: urlstr,
      success: (res) => {
        if (res.data && res.data.basic_info) {
          that.initBalanceLang(res.data.basic_info.balance);
          this.setData({
            mailInfo: res.data.basic_info.home ? res.data.basic_info.home.mailInfo : {},
          });
        }
        wx.stopPullDownRefresh({
          complete: function (res) {
            console.log('关闭下拉刷新', res, new Date());
          }
        });

        that.setData({
          footshow: true
        });

        if (res.data.data.item && app.globalData.store_alone_temp != 1) {
          // app.globalData.store_alone_temp != 1 门店独立模块不缓存首页数据
          try {
            wx.setStorageSync('new_decorate', res.data.data);
          } catch (e) {  
            console.log("数据过大真机会出现无法存储【#85269】",e);
          }
        }

        // 装修数据
        let designerItem = res.data.data.item;

        var _data = res.data.data.default;
        if (_data) {
          that.setData({
            defaultdata: res.data.data.default, // 默认模板消息
            last_page: res.data.data.default.goods.last_page,
            isLoadMore: false,
            page: 1
          });
          that.setData({
            isLoadMore: that.data.last_page > 1
          });
        }

        //爱心值和浏览权限
        let params = designerItem.pageinfo ? designerItem.pageinfo.params : {};
        that.setData({
          params: params,
          designer: res.data.data.designer ? res.data.data.designer : '', // 爱心值
          isWatch: params.allowauth == 0 ? false : true
        });
        if (!that.data.isWatch && designerItem.page_info.member_level_url && designerItem.page_info.member_level_url.link &&
          designerItem.page_info.member_level_url.link.indexOf('packageG/index/index') < 0) {
          wx.redirectTo({
            url: designerItem.page_info.member_level_url.link,
          });
        }
        console.log("会员是否可浏览装修页2", that.data.isWatch);

        //标题设置
        if (designerItem.data != '' && (designerItem.page_info && designerItem.page_info.page_title)) {
          wx.setNavigationBarTitle({
            title: designerItem.page_info.page_title ? designerItem.page_info.page_title : that.data.mailInfo.name || ''
          });

          wx.setStorageSync('pageinfo', {
            title: designerItem.page_info.page_title ? designerItem.page_info.page_title : that.data.mailInfo.name,
            desc: designerItem.page_info.page_description
          });
        } else {
          wx.setNavigationBarTitle({
            title: that.data.mailInfo.name || ''
          });
        }
        if (designerItem.page_info && designerItem.page_info.preview_color) {
          wx.setNavigationBarColor({
            backgroundColor: designerItem.page_info.preview_color,
            frontColor: designerItem.page_info.font_color == 1 ? '#ffffff' : '#000000',
            animation: {
              duration: 400,
              timingFunc: 'easeIn'
            }
          });
        }

        // 店铺装修
        if (designerItem.datas) {
          for (let i = 0; i < designerItem.datas.length; i++) {
            if (designerItem.datas[i].component_key == 'U_goods') {
              designerItem.datas[i].index = i;
            }
            if (designerItem.datas[i].component_key == 'U_location') {
              designerItem.datas[i].home = true;
            }
            if (designerItem.datas[i].component_key == 'U_signin') {
              designerItem.datas[i].host = app.data.host;
            }
            designerItem.datas[i].designer = that.data.designer;
          }
          that.setData({
            isDesigner: true,
            decorate_isLoadMore: true,
            designerItem: designerItem.datas,
            page_id: designerItem.id,
            components: designerItem.datas,
            foot_type: designerItem.foot_type
          });
          if (designerItem.page) {
            that.setData({
              total_page: designerItem.page.total_page,
              current_page: designerItem.page.current_page,
              bottomShowBolIndex: designerItem.page.count - 1,
            });
          }

          if (designerItem.page_info) {
            that.setData({
              advertising: designerItem.page_info.advertising_id || {},
              full_screen: designerItem.page_info.full_screen_id || {},
            });

            if (that.data.advertising.id && that.data.advertising.datas) {
              that.data.advertising.datas = JSON.parse(that.data.advertising.datas);
              that.setData({
                advertising: that.data.advertising,
              });
            }
          }

          if (designerItem.top && designerItem.top.id) {
            this.setData({
              top_info: JSON.parse(designerItem.top.page_info)
            });
          }

          // 装修的底部有三种情况
          if (designerItem.foot_type == -1) {
            // 不显示
            this.setData({
              bottom_info: {}
            });
          } else if (designerItem.foot_type == 1) {
            // 显示默认
            if (!designerItem.foot || !designerItem.foot.page_info) {
              // 显示系统默认
              this.setData({
                bottom_info: {}
              });
            } else {
              // 显示列表设置的默认
              this.setData({
                bottom_info: JSON.parse(designerItem.foot.page_info)
              });
            }
          } else if (designerItem.foot_type == 2) {
            // 显示自定义的底部导航
            if (designerItem.foot instanceof Array) {
              this.setData({
                bottom_info: {}
              });
            } else {
              this.setData({
                bottom_info: JSON.parse(designerItem.foot.page_info)
              });
            }
          }

          let fullAdvertisement = wx.getStorageSync('fullAdvertisement');
          if (this.data.full_screen && this.data.full_screen.id && !fullAdvertisement && this.data.full_screen.show_rule === 1) {
            wx.setStorageSync('fullAdvertisement', true);
            this.setData({
              fullShow: true
            });
            setTimeout(() => {
              this.countDown(this.data.full_screen.show_time);
            }, 2000);
          }

          let fullAdvertisement_expiration = wx.getStorageSync('fullAdvertisement_expiration');
          let newTime = parseInt(Date.parse(new Date()) / 1000);

          if (this.data.full_screen && this.data.full_screen.id && this.data.full_screen.show_rule === 2 && fullAdvertisement_expiration < newTime) {
            let timestamp = parseInt((new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1) / 1000); //当天23:59:59
            wx.setStorageSync("fullAdvertisement_expiration", timestamp);
            this.setData({
              fullShow: true
            });
            setTimeout(() => {
              this.countDown(this.data.full_screen.show_time);
            }, 2000);
          }

        } else {
          //默认数据设置开始
          that.setData({
            readyshow: true
          });

          // menu
          var size = 10;
          var _memuData = _data.category;
          var _memuOldData = _memuData;
          var page = Math.ceil(_memuData.length / size);

          // mailInfo
          wx.setStorageSync('pageinfo', {
            title: that.data.mailInfo.name,
            desc: that.data.mailInfo.name
          });

          wx.setNavigationBarTitle({
            title: that.data.mailInfo.name || ''
          });

          // 设置memu height
          var menuHeightClass;

          if (_memuData.length <= 5) {
            menuHeightClass = 'in1';
          } else {
            menuHeightClass = 'in2';
          }

          var dataArray = [];

          for (var i = 0; i < page; i++) {
            var dataArray2 = [];
            for (var j = 0; j < size; j++) {
              var a = _memuData[j];
              if (a != undefined) {
                dataArray2.push(_memuData[j]);
              }
            }
            _memuOldData = _memuOldData.slice(size);

            _memuData = _memuOldData;
            dataArray.push(dataArray2);
          }

          that.setData({
            footshow: true,
            bottom_info: {},
            bannerData: _data.ads,
            goodsData: _data.goods,
            memuData: dataArray,
            // 设置memu height
            menuHeightClass: menuHeightClass,
          });

        }

        that.setData({
          showPage: true
        });
        wx.hideLoading();

        //是否显示新人奖弹窗
        try {
          let storage_newAward = wx.getStorageSync("storage_newAward");
          // 首页这里整合删了
          // console.log("//////////新人奖弹窗222///////////////",res.data.data.plugin.new_member_prize,storage_newAward)
          // if (res.data && res.data.data && res.data.data.plugin && res.data.data.plugin.new_member_prize.prize) {

          //   let _prizeData = res.data.data.plugin.new_member_prize;
          //   let new_member_prize = {};
          //   new_member_prize.type = _prizeData.activity.background_type;
          //   new_member_prize.title = _prizeData.activity.title;
          //   new_member_prize.awardlist = _prizeData.prize;
          //   if(res.data.data.plugin.new_member_prize.prize.length == 0){
          //     that.setData({
          //       showNewcomerAward: false,
          //     });
          //   }else{
          //     that.setData({
          //       new_member_prize: new_member_prize,
          //       showNewcomerAward: true,
          //     });
          //   }
          // } else
          if (storage_newAward && storage_newAward.prize) {
            let _prizeData = storage_newAward;
            let new_member_prize = {};
            new_member_prize.type = _prizeData.activity.background_type;
            new_member_prize.title = _prizeData.activity.title;
            new_member_prize.awardlist = _prizeData.prize;
            if (storage_newAward.prize.length == 0) {
              that.setData({
                showNewcomerAward: false,
              });
            } else {
              that.setData({
                new_member_prize: new_member_prize,
                showNewcomerAward: true,
              });
            }

          } else {
            // 旧弹窗广告
            // that.getAdvertise();

            // 新弹窗广告
            let popAdvertisement = wx.getStorageSync('popAdvertisement');
            if (this.data.advertising && this.data.advertising.id && !popAdvertisement && this.data.advertising.show_rule === 1) {
              wx.setStorageSync('popAdvertisement', true);
              this.setData({
                popShow: true
              });
            }

            let popAdvertisement_expiration = wx.getStorageSync('popAdvertisement_expiration');
            let pop_newTime = parseInt(Date.parse(new Date()) / 1000);
            if (this.data.advertising && this.data.advertising.id && this.data.advertising.show_rule === 2 && popAdvertisement_expiration < pop_newTime) {
              let timestamp = parseInt((new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000 - 1) / 1000); //当天23:59:59
              wx.setStorageSync("popAdvertisement_expiration", timestamp);
              //每日小程序登录弹出
              this.setData({
                popShow: true
              });
            }
          }
        } catch (e) {
          console.log("新人奖报错：：：", e);
        }
      },
      fail: function (res) {
        wx.stopPullDownRefresh({
          complete: function (res) {
            console.log('关闭下拉刷新', res, new Date());
          }
        });
      }
    });
  },
  gotoBrand(evt) {
    let item = evt.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/packageB/member/category/brandgoods/brandgoods?id=' + item.id,
    });
  },
  gotoBrandV2() {
    wx.navigateTo({
      url: '/packageB/member/category/brand_v2/brand_v2',
    });
  },
  gotoTimeGood(evt) {
    let item = evt.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + item.id,
    });
  },
  gotoLimitedTimeGoods() {
    wx.navigateTo({
      url: '/packageG/limitedTimeGoods/limitedTimeGoods',
    });
  },
  getMoreDecorate() {
    let that = this;
    that.setData({
      decorate_isLoadMore: false
    });

    if (that.data.current_page < that.data.total_page) {
      that.setData({
        current_page: that.data.current_page + 1
      });
      let urlStr = app.getNetAddresss('plugin.decorate.frotend.decorate-api.get-page');
      app._postNetWork({
        url: urlStr,
        data: {
          decorate_page: this.data.current_page,
          decorate_id: this.data.page_id
        },
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              decorate_isLoadMore: true,
              components: that.data.components.concat(res.data.datas)
            });
          } else {
            that.setData({
              decorate_isLoadMore: false,
              current_page: that.data.current_page - 1
            });
            console.log(res.msg);
          }
        }
      });
    }

  },
  getAdvertise() {
    let urlStr = app.getNetAddresss('member.member.getAdvertisement');
    app._getNetWork({
      url: urlStr,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if (res.data.advertisement) {
            this.setData({
              advertisement: res.data.advertisement
            });
            if (this.data.advertisement.switch) {
              // 全屏广告首次登录
              if (this.data.advertisement.rule === 1) {
                // everyTime == false证明不是每次进首页广告
                if (!this.data.everyTime) {
                  this.setData({
                    fullShow: true
                  });
                  this.countDown(this.data.advertisement.time);
                }
              } else {
                // 全面每次广告
                this.setData({
                  fullShow: true,
                  everyTime: true
                });
                this.countDown(this.data.advertisement.time);
              }
            }

            if (this.data.advertisement.Midswitch) {
              // 弹窗首次登录
              if (this.data.advertisement.Midrule === 1) {
                // everyTime == false证明不是每次进首页广告
                if (!this.data.everyTime) {
                  this.setData({
                    // fullShow: false,
                    popShow: true
                  });
                }
              } else {
                console.log('弹窗每次登录');
                this.setData({
                  popShow: true,
                  everyTime: true
                });
              }
            }

          }
        } else {
          console.log(res.msg, '该用户不是首次登录');
          this.setData({
            advertisement: res.data
          });

          if (this.data.advertisement.switch) {
            if (this.data.advertisement.rule === 1) {
              this.setData({ // 全屏广告为1，但是接口返回result为0时，改用户不是首次登录
                fullShow: false
              });
              this.countDown(this.data.advertisement.time);
            } else {
              this.setData({
                fullShow: true,
              });
              this.countDown(this.data.advertisement.time);
            }
          }
          if (this.data.advertisement.Midswitch) {
            if (this.data.advertisement.Midrule === 1) {
              this.setData({
                popShow: false
              });
            } else {
              this.setData({
                popShow: true,
              });
            }
          }
        }
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  turnFullTo() {
    let url = this.data.full_screen.minapp_link;
    try {
      wx.navigateTo({
        url: url
      });
    } catch (e) {
      wx.showToast({
        title: '链接设置错误',
        icon: 'none',
        duration: 2000
      });
    }
  },
  turnTo() {
    if (this.data.advertising.is_minapp == 2) {
      if (this.data.advertising.minapp_sid) {
        if (this.data.advertising.minapp_link2) {
          try {
            wx.navigateToMiniProgram({
              appId: this.data.advertising.minapp_sid,
              path: this.data.advertising.minapp_link2,
              extraData: {},
              envVersion: 'release',
              success(res) {
                // 打开成功
              },
              fail(res) {
                wx.showToast({
                  title: '小程序跳转失败',
                  icon: 'none',
                  duration: 2000
                });
              }
            });
          } catch (e) {
            wx.showToast({
              title: '小程序跳转失败',
              icon: 'none',
              duration: 2000
            });
          }
        } else {
          wx.showToast({
            title: '请设置跳转小程序后的跳转链接',
            icon: 'none',
            duration: 2000
          });
        }
      } else {
        wx.showToast({
          title: '请设置小程序所需跳转appId',
          icon: 'none',
          duration: 2000
        });
      }
    } else {
      let url = this.data.advertising.minapp_link;
      try {
        wx.navigateTo({
          url: url
        });
      } catch (e) {
        wx.showToast({
          title: '链接设置错误',
          icon: 'none',
          duration: 2000
        });
      }
    }
  },
  closePop() {
    this.setData({
      popShow: false
    });
  },
  closeFull() {
    this.setData({
      fullShow: false
    });
  },
  countDown(num) {
    let numberNum = num;
    this.setData({
      'full_screen.show_time': numberNum,
      'advertisement.time': numberNum
    });
    numberNum--;

    let cleartime = setTimeout(() => {
      if (numberNum <= 0) {
        this.setData({
          fullShow: false
        });
        clearInterval(cleartime);
      } else {
        this.countDown(numberNum);
      }
    }, 1000);
  },
  tel: function (e) {
    var telnum = e.currentTarget.dataset.telnum;

    wx.makePhoneCall({
      phoneNumber: telnum
    });
  },
  // 事件处理函数
  goToDetail: function (event) {
    var url = '/packageA/detail_v2/detail_v2?id=' + event.currentTarget.id;
    wx.navigateTo({
      url: url
    });
    console.log(url);
  },

  goGoodsList: function (e) {
    var _id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/packageB/member/category/catelist/catelist?id=' + _id
    });
  },
  clickADTo() {
    if (this.data.bannerData[0].small_link) {
      console.log("设置小程序跳转", this.data.bannerData[0].small_link);
      try {
        wx.navigateTo({
          url: this.data.bannerData[0].small_link
        });
      } catch (err) {
        console.log(err);
      }
    }
  },
  clickADPlaceTo(e) {
    let _link = e.currentTarget.dataset.link;
    console.log("设置小程序跳转", _link);
    if (_link) {
      try {
        wx.navigateTo({
          url: _link
        });
      } catch (err) {
        console.log(err);
      }
    }
  },
  // 获取更多数据
  getMoreData() {
    const that = this;
    that.setData({
      isLoadMore: false
    });
    if (this.data.page >= this.data.last_page) {
      return;
    } else {
      that.setData({
        page: this.data.page + 1
      });
      let urlStr = app.getNetAddresss('home-page.get-first-goods-page');
      app._getNetWork({
        url: urlStr,
        data: {
          page: that.data.page
        },
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            if (that.data.page >= that.data.last_page) {
              that.setData({
                isLoadMore: false
              });
            } else {
              that.setData({
                isLoadMore: true
              });
            }
            var myData = res.data.data;
            that.setData({
              'defaultdata.goods.data': that.data.defaultdata.goods.data.concat(myData)
            });
          } else {
            that.setData({
              page: that.data.page - 1,
              isLoadMore: false
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    }
  },
  gophone(e) {
    let num = e.currentTarget.dataset.num;
    wx.makePhoneCall({
      phoneNumber: num
    });
  }
});