//index.js
import { getDeviceScreen, CalcMethod } from '../../utils/comm.js'
const Calc = new CalcMethod(),
  app = getApp(),
  { hostname, business_id} = app.globalData
Page({
  data: {
    showApply:'true',
    imgUrls: [
    ],
    pictures: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    recommend: []
  },
  onLoad: function (options) {
      
    // wx.setNavigationBarColor({
    //   frontColor: '#ffffff',
    //   backgroundColor: '#ff0000',
    //   animation: {
    //     duration: 400,
    //     timingFunc: 'easeIn'
    //   }
    // })

    var scene = decodeURIComponent(options.scene).split('&').toString().replace(/(\D)+/g, ',').split(',')
    console.log(scene, options)
    wx.showLoading({
      title: '正在加载',
    })
    let { business_id = ''} = options;
    this.checkHack()  
    if (scene[1]) {
      app.globalData.business_id = scene[1]
      app.globalData.layer = scene[3]
      app.globalData.table = scene[2]
      
      wx.setStorageSync('business_id', scene[1])
      wx.setStorageSync('floorIndex', scene[3])
      wx.setStorageSync('seatIndex', scene[2])
      wx.navigateTo({
        url: '../ManyStore/subStore/subStore?business_id=' + scene[1]
      })
    }
    let that = this,
      { windowHeight, pixelRatio } = getDeviceScreen(),
      scrollHeight = 0
    scrollHeight = windowHeight - (45 + 125)   // 获取滚动区域高度
    this.setData({ scrollHeight })
    var u_openid = options.u_openid;
    app.getUserInfo(function (cb, userInfo) {
      that.setData({
        userInfo: userInfo,
      })
    }, u_openid)
    // 保存AppData
    app.getUserInfo(function (userInfo) {
      that.setData({ userInfo: userInfo })  //更新数据
    }, u_openid)
   
      app.callbackOpenid = res => {
        console.log("openid", res)
        wx.setStorageSync("openId", res)
      }
    that.getSwiperImgUlrs(that);
    that.getShowPicture(that);
    that.getSubStore(that); 
    that.getStoreInfo();  
    that.getRecommendGoods();
    
    // 获取地址及经纬度
    wx.request({
      url: hostname + 'Api/get_lnglat',
      method: 'post',
      header:{
        'Content-Type':'application/x-www-form-urlencoded'
      },
      data:{
        business_id: app.globalData.business_id
      },
      success: res=>{
        if(res.data.status == 1){
          wx.setStorageSync('lat', res.data.lat)
          wx.setStorageSync('lng', res.data.lng)
        }
      }
    })
    wx.hideLoading()
   setTimeout(()=>{
     //领优惠券
     wx.request({
       url: app.globalData.hostname + 'Pre/show_red',
       header: { 'Content-type': 'application/x-www-form-urlencoded' },
       method: 'POST',
       data: {
         business_id: app.globalData.business_id,
         openid: wx.getStorageSync('openId')
       },
       success: (res) => {

        
        //  console.log(res, "红包状态")
         // 红包状态

         if (!res.data.data) {

           that.setData({
             showApply: false
           })
         } else {
           that.setData({
             showApply: true
           })
         }
         that.setData({
           couponData: res.data.data
         })


       }
     })
   },1000)
   


  
  },

// 动态修改背景颜色
  changeColor: function () {
    
  },

  //取消或确认提交申请
  whetherApply: function (e) {
    var that = this;
    var kind = e.currentTarget.dataset.kind;
    if (kind == 'cancle') {
      that.setData({
        showApply: false,
      })
    } else {

    }
  },
  
  onShow: function (options) {
    
  },

  
  // checkHack
  checkHack() {
    let that = this
    // wx.request({
    //   url: hostname + 'Goods/get_info',
    //   success: function (res) {
    //     that.setData({ checkHack: res.data })
    //     wx.setNavigationBarTitle({
    //       title: res.data.pageName
    //     })
    //   }
    // })
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.getGoodsInfo()  // 获取商品信息
  },
  /**
     * 用户点击右上角分享
     */
  onShareAppMessage: function (res) {
    var userid = wx.getStorageSync('openId')
    // var userid = 1

    if (res.from === 'button') {
      // 来自页面内转发按钮
      // console.log(res.target)
    }
    return {
      title: app.globalData.share_title,
      path: '/pages/index/index?u_openid=' + userid,
      success: function (res) {
        var pages = getCurrentPages()    //获取加载的页面
        var currentPage = pages[pages.length - 1]    //获取当前页面的对象
        //点击分享传进userid 截取userid 从onload拿到
        var url = currentPage.route + '?u_openid=' + userid;  //当前页面url
        // console.log(url, '/pages/index/index?u_openid=' + userid);
      },
      fail: function (res) {
        // 转发失败
      },
    }
  },
  //获取轮播图图片
  getSwiperImgUlrs: function (that) {
    wx.request({
      url: app.globalData.hostname + 'Chart/index',
      data: { business_id },
      header: { 'Content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      dataType: '',
      success: function (res) {
        // console.log(res,"轮播图片")
        if (res.statusCode == 200) {
          var imgUrls = [];
          var imgUrlsData = res.data.data;

          if (imgUrlsData.length != undefined) {
            for (var i = 0; i < imgUrlsData.length; i++) {
              imgUrls.push(imgUrlsData[i]);
            }
          }       
          that.setData({
            imgUrls: imgUrls
          })
        } else {
          that.setData({
            imgUrls: []
          })
        }
      },
      fail: function (res) { },
      complete: function (res) {
        // that.getGoodsList(that, 1);
      },
    })
  },

  //获取子门店列表
  getSubStore(that) {
    wx.request({
      url: app.globalData.hostname + 'ManyStore/IndexSubsidiaryStore',
      data: { business_id },

      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      dataType: '',
      success: function (res) {

          if (res.statusCode == 200) {
            var recommend = [];
            var recommendData = res.data.data;

            if (recommendData.length != undefined) {
              for (var i = 0; i < recommendData.length; i++) {
                recommend.push(recommendData[i]);
              }
            }
            that.setData({
              recommend: recommend
            })
          } else {
            that.setData({
              recommend: []
            })
          }
      }
    })
  },

  // 进入门店
  goStore(e){
      // var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../ManyStore/subStore/subStore'
    })
  },
  //跳到招商信息
  goleague(){
    wx.navigateTo({
      url: '../about/about?business_id=' + app.globalData.business_id
    })
  },
  //前往优惠券中心
  navcoupon() {
    wx.navigateTo({
      url: '../coupon/coupon'
    })
  },
  //前往资讯信息
  goinfo(){
    wx.navigateTo({
      url: '../Information/Information?business_id=' + app.globalData.business_id
    })
  },
  //前往充值会员
  navrecharge() {
    wx.navigateTo({
      url: '../recharge/recharge'
    })
  },

  //前往积分商城
  goPointsMall() {
    wx.navigateTo({
      url: '../pointsMall/pointsMall',
    })
  },
  //前往我的
  gomy() {
    wx.switchTab({
      url: '../center/center',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },


  // 前往餐厅信息
  goMessage(e) {
    var id = e.currentTarget.dataset.id;
    wx.switchTab({
      url: '../ManyStore/subStore/subStore?business_id=' + id
    })
  },

  // 获取商店信息
  getStoreInfo() {
    let that = this

    var business_id = app.globalData.business_id;
    wx.request({
      url: hostname + 'Goods/get_business_info',
      data: { business_id },
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
      method: 'POST',
      dataType: 'JSON',
      success: function (res) {
        let storeInfo = JSON.parse(res.data).data
        that.setData({ storeInfo })
      },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  //获取首页推荐商品
  getRecommendGoods(){
    var that = this;
    wx.request({
      url: app.globalData.hostname + 'Goods/GetDish',
      data: { business_id },
      header: { 'Content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      success:function(res){
        // console.log(res,"推荐商品")
        if(res.statusCode == 200){
          var dish = [];
          var dishData = res.data;

          if (dishData.length != undefined){
            for(var i = 0;i<dishData.length;i++){
              dish.push(dishData[i])
            }
          }
          that.setData({
            dish:dish
           
          })
          // console.log(dish,"dish")
        }else{
          that.setData({
            dish:[]
          })
        }
      }
    })
  },

  //获取首页显示图片
  getShowPicture(that){
    wx.request({
      url: app.globalData.hostname + 'ManyStore/IndexShowPicture',
      data: { business_id},
      header: { 'Content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      dataType: '',
      success: function (res) {
        if (res.statusCode == 200) {
          var pictures = [];
          var picturesData = res.data.data;
          
          if (picturesData.length != undefined) {
            for (var i = 0; i < picturesData.length; i++) {
              pictures.push(picturesData[i].picture);
            }
          }
          that.setData({
            pictures: pictures
          })
        } else {
          that.setData({
            pictures: []
          })
        }
        
      }
    
  })},
  // 图片预览变大
  tobig(e) {
    var src = e.currentTarget.dataset.src;

    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: this.data.pictures // 需要预览的图片http链接列表
    })
  },

  // 前往地图导航
  goAddress(e){
    // console.log(e.currentTarget.dataset.lnglat)
    wx.navigateTo({
      url: '../navPage/navPage?business_id=' + e.currentTarget.dataset.business_id,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  // 前往拨打电话
  callPhone(e){
 
    wx.makePhoneCall({
      phoneNumber: e.currentTarget.dataset.phone,
    })
  },


  // 领取优惠券
  getCoupon(e) {
    var that = this
    var pre_id = e.currentTarget.dataset.id
    var business_id = app.globalData.business_id;
    // console.log(pre_id)
    wx.request({
      url: hostname + 'Pre/get_pre',
      header: { 'Content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      data: {
        openid: wx.getStorageSync('openId'),
        pre_id,
        business_id
      },
      success: function (res) {
        // console.log(res, "领取优惠券")
        if (res.data.status == -1) {
          wx.showToast({
            title:"红包已被抢光啦",
            // image: '/images/sea2/jpg',
            duration: 1500
          })
        } else if (res.data.status == 1) {
          wx.showToast({
            title:"领取红包成功",
            duration: 1500
          })
        }
      },
      fail: function (res) { },
      complete: function (res) {},
    })
  },


  // 测试功能
  goCeshi(){
    
  },
})
