var app = getApp();
var $ = require('../../js/util.js');
var QQMapWX = require('../../js/qqmap-wx-jssdk.min.js');
var qqmapsdk;
var stepnowtime = 0;//当前循环标识
var is_step = -1;
Page({
  data: {
    array: [{
      mode: 'scaleToFill',
      text: 'scaleToFill：不保持纵横比缩放图片，使图片完全适应'
    }],
    imgUrls: [],
    indicatorDots: true,//轮播图上的小点
    autoplay: true,//是否自动播放
    interval: 3000,//轮播图切换间隔
    duration: 1000,//轮播图间隔动画
    navlist: {},
    nearby_info: [],
    show_q: false,
    is_shop_id: 0,//门店id
    //主列表
    HClist: [],
    list: [],
    //追加列表
    HCaddlist: '',
    //当前点击添加的模板类型
    type_con: '',
    //数据库存储的新数组
    HCnewlist: [],
    //数据库存储的新数组长度【用来遍历渲染】
    HCnewlistlen: 0,
    //轮播组件数量
    HCowlnum: 0,
    indexlist: [],
    location_n: '选择地址',
    shop_name: '',
    time: '',
    small_title: '',
    promat_list: [],
    param: {
      mpage: 0,
      page: 1,
    },
    user_info:[],
    is_getUserProfile:false,
    Height: "",    //这是swiper要动态设置的高度属性
  },
  onLoad: function () {
    var self = this;
    var animation = wx.createAnimation({
      duration: 500,
      transformOrigin: "50% 50%",
      timingFunction: 'ease',
    })
    this.animation = animation;
    self.setData({
      is_shop_id: app.globalData.is_shop_id
    })
    if (wx.getUserProfile){
      self.setData({
        is_getUserProfile:true
      })
    }
    // if (app.globalData.HCshopid){
    //   self.getIndex();
    // }
  },
  onShow: function () {
    //版本更新
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function (res) {
      // 请求完新版本信息的回调
      //console.log(res.hasUpdate)
    });
    updateManager.onUpdateReady(function () {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，点击确定更新小程序',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      })
    });
    updateManager.onUpdateFailed(function () {
      app.HCtoast('新版本下载失败!', 2000, 'none'); return;
    });
    var self = this;
    if (app.globalData.HCshopid) {
      //console.log(app.globalData.HCshopid);
      var location_n = app.globalData.location_n;
      //console.log(location_n);
      if (location_n && location_n != '选择地址') {
        self.setData({
          location_n: location_n
        });
      }
      var shop_catch = app.HCgetStorage("catch_shop_info" + app.globalData.HCshopid);
      if (shop_catch) {
        self.setData({
          shop_name: shop_catch.shop_name
        })
      } else {
        self.setData({
          shop_name: ''
        })
        app.HCsetStorage("catch_shop_info" + app.globalData.HCshopid, '');
        self.getshopname();
      }
    } else {
      qqmapsdk = new QQMapWX({
        key: app.getQQmapkey()
      });
      var location_n = app.globalData.location_n;
      if (location_n && location_n != '选择地址') {
        self.setData({
          location_n: location_n
        });
      } else {
        if (self.data.list) {
          var param = self.data.param;
          param.page = 1;
          param.mpage = 0;
          is_step = -1;
          self.setData({
            page: 1,
            param: param,
            HClist: [],
            list: [],
            hasMore: false,
            dataNull: false
          });
        }

        app.HCgetlocation(function (ret) {
          if (ret) {
            qqmapsdk.reverseGeocoder({
              location: {
                latitude: ret.latitude,
                longitude: ret.longitude
              },
              coord_type: 1,
              success: function (res) {
                if (res.message == 'query ok') {
                  app.globalData.location_n = res.result.formatted_addresses.recommend;
                  self.setData({
                    location_n: res.result.formatted_addresses.recommend
                  });
                  app.getUserInfo(function (ret) {
                    if (ret) {
                      self.setData({
                        user_info: ret
                      })
                    }
                    app.HCsetHCshopid(function (res) {
                      self.getshopname();
                      self.getIndex();

                    })
                  });

                }
              },
            });
          } else {
            app.getUserInfo(function (ret) {
              if(ret){
                self.setData({
                  user_info:ret
                })
              }
              self.getIndex();
            });
          }
        });
      }
    }
    self.setData({
      mpage: 0,
      page: 1
    });
    is_step = -1;
    if (self.data.is_shop_id != app.globalData.HCshopid || ($.is_empty(self.data.list) && self.data.is_shop_id > 0)) {
      app.globalData.is_shop_id = app.globalData.HCshopid;
      self.setData({
        list: [],
        is_shop_id: app.globalData.is_shop_id
      })
      self.getIndex();
    }
  },
  tolocation: function () {
    app.HCnavigateTo('../location/location');
  },
  getshopname: function () {
    var self = this;
    var param = new Object;
    param.shop_id = app.globalData.HCshopid;
    var action = 'c=Index&a=get_shop_name';
    param = $.ObjectToStr(param);
    app.ajaxRequest(action, 'GET', param, function (ret) {
      //console.log(ret);
      if (ret.status == 1) {
        app.globalData.is_shop_id = app.globalData.HCshopid;
        self.setData({
          shop_name: ret.data.shop_name,
          is_shop_id: app.globalData.is_shop_id
        })
        app.HCsetStorage('catch_shop_info' + app.globalData.HCshopid, ret.data);
      }
    })
  },
  //下拉刷新
  onPullDownRefresh: function () {
    var param = this.data.param;
    param.page = 1;
    param.mpage = 0;
    is_step = -1;
    this.setData({
      page: 1,
      param: param,
      HClist: [],
      list: [],
      hasMore: false,
      dataNull: false
    });
    this.getIndex();
  },
  getIndex: function (pagefrom, is_append) {
    var self = this;
    var param = new Object;
    param.pagefrom = pagefrom ? pagefrom : 0;

    if (param.pagefrom <= is_step) return false;
    is_step = param.pagefrom;
    param.page = self.data.param.page;
    param.uu = self.data.user_info.rank_id ? self.data.user_info.rank_id : 0;
    param.is_append = is_append ? pagefrom : 0;
    if (!pagefrom && !is_append) {
      self.data.HCnewlist = [];
    }
    var action = 'c=Index&a=get_vindex';

    if (pagefrom <= 0) {
      app.showLoading('加载中...');
      stepnowtime = Math.random();
    }
    param.stepnowtime = stepnowtime;
    param = $.ObjectToStr(param);
    app.ajaxRequest(action, 'GET', param, function (ret) {
      //console.log(ret);
      if (ret.data.title_name != '') {
        app.HCsetNavigationBarTitle(ret.data.title_name);
        self.setData({
          small_title: ret.data.title_name
        })
      }
      if (stepnowtime != ret.stepnowtime) return;
      if (is_append >= 0 || ret.data.pagefrom >= 0) {
        $.init_vue_append_list(self, ret.data.HCinitlist);
      }
      if (ret.data.pagefrom) {
        setTimeout(function () {
          self.getIndex(ret.data.pagefrom, 1);
        }, 1000)
      }
      app.globalData.temp_idcode = ret.data.temp_id;
      for (var i in ret.data.HCinitlist) {
        if (ret.data.HCinitlist[i].data_type == 4) {
          if (ret.data.HCinitlist[i].content.is_timelimit == 2 && ret.data.HCinitlist[i].content.end_time) {
            var time = ret.data.HCinitlist[i].content.end_time;
            self.setData({
              xs_time: time
            })
            setInterval(function () {
              var Countdowndata = $.Countdown(self.data.xs_time);
              self.setData({
                Countdowndata: Countdowndata,
              })
            }, 1000);
          }
        }
        if (ret.data.HCinitlist[i].data_type == 18) {
          if (ret.data.HCinitlist[i].content.promot_list) {
            self.setData({
              promat_list: ret.data.HCinitlist[i].content.promot_list
            })
            self.countDown();
          }
        }
        var time = ret.data.time;
        self.setData({
          time: time
        })
      }
      self.get_category();
    });
  },
  countDown: function () {
    var list = this.data.promat_list;
    for (var i in list) {
      list[i].Countdowndata = $.Countdown(list[i].end_time);
    }
    this.setData({
      promat_list: list
    })
    setTimeout(this.countDown, 1000);
  },
  goToCoupon: function (event) {
    app.HCnavigateTo('../coupon/list/list');
  },
  goToNearby: function (event) {
    app.HCnavigateTo('../nearby/nearby');
  },
  goBuy: function () {
    app.HCswitchTab('../takeout/index/index');
  },
  gotoSearch: function () {
    var keyword = '';
    app.HCnavigateTo('../search/index?keyword=' + keyword);
  },
  jumtop: function (event) {
    var catid = event.currentTarget.dataset.id;
    var app_mark = event.currentTarget.dataset.inx;
    if (app_mark == '') return false;
    var jumtopdata = new Object;
    jumtopdata.type = app_mark;
    jumtopdata.id = catid ? catid : 0;
    app.jumtop_open_poster(jumtopdata);
  },
  GotoCont: function (event) {
    var pt_id = event.currentTarget.dataset.pt_id;
    var pt_price = event.currentTarget.dataset.pt_price;
    var is_overdue = event.currentTarget.dataset.is_overdue;
    var is_ptdue = event.currentTarget.dataset.is_ptdue;

    if (pt_id > 0 && pt_price > 0 && is_ptdue == 0) {
      app.HCnavigateTo('../../spellgroup/pages/fightgroup/cont/cont?id=' + event.currentTarget.dataset.id + '&name=' + event.currentTarget.dataset.goodsname);
    } else {
      app.HCnavigateTo('../takeout/cont/cont?id=' + event.currentTarget.dataset.id);
    }
  },
  //获取用户信息授权
  bindGetUserInfo: function (e) {
    var self = this;
    if (wx.getUserProfile){
      wx.getUserProfile({
        desc:'用于完善会员资料',
        success:function(res){
          app.HCsetStorage('profile_Users', res.userInfo);
          app.HCsetStorage('profile_iv', res.iv);
          app.HCsetStorage('profile_encryptedData', res.encryptedData);
          app.getUserInfo(function (ret) {  
            self.setData({
              show_q: false,
              info: ret,
            })
            if ($.is_empty(ret.mobile) && e.detail.userInfo) {
              app.HCnavigateTo('../../login_accredit/login_accredit');
            }
          })
        }
      })
    }else{
      app.getUserInfo(function (ret) {
        self.setData({
          show_q: false,
          info: ret,
        })
        if ($.is_empty(ret.mobile) && e.detail.userInfo) {
          app.HCnavigateTo('../../login_accredit/login_accredit');
        }
      })
    }
  },
  get_category: function () {
    var self = this;
    var action = 'c=Index&a=get_category';
    app.ajaxRequest(action, 'GET', '', function (ret) {
      if (ret.status == 1) {
        app.HCsetStorage('catch_cate_list', ret.data.cate_list);
        app.HCsetStorage('catch_screen_list', ret.data.screen_list);
        app.HCsetStorage('catch_order_list', ret.data.order_list);
      }
    });
  },
  onShareAppMessage: function () {
    return {
      title: this.data.small_title,
      desc: '选择您心仪的宝贝!',
      path: '/' + $.getCurrentPageUrl() + '?invite_key=' + app.globalData.init_invite_key
    }
  },
  imgHeight: function (e) {
    var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
    var imgh = e.detail.height;//图片高度
    var imgw = e.detail.width;//图片宽度
    var swiperH = winWid * imgh / imgw + "px";
    this.setData({
      Height: swiperH//设置高度
    })
  },
})