//index.js
import { getDeviceScreen, CalcMethod } from '../../utils/comm.js'
const Calc = new CalcMethod(),
  app = getApp(),
  { hostname, business_id} = app.globalData
Page({
  data: {
    showApply:'true',
    logoShow: 1,
    imgUrls: [
    ],
    pictures: [],
    indicatorDots: true,
    autoplay: true,
    interval: 5000,
    duration: 1000,
    recommend: [],
    imgbBefore:'https://jisu.shenmikj.com/canyin2/Uploads/' ,
  },
  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();
    that.indexImg();
    that.getNewLogo();
    that.getNav();
    that.getLogoShow();
    that.getcatList();
    that.getChartShow();
    that.getcatConfig();
    that.getNotice();
    that.getaddresslng();
    
    // thta
    
    // 获取地址及经纬度
    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)
  

    let userInfo = wx.getStorageSync('userInfo')  // 获取用户信息
  },

// 动态修改背景颜色
  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) {
    let that = this;
    that.judgeSign(that);
  },

  
  // 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) {
        // 转发失败
      },
    }
  },

  //首页推荐图片
  indexImg: function () {
    let that = this;
    wx.request({
      url: app.globalData.hostname + 'exhibition/index',
      data:{ business_id },
      header:{'Content-type':'application/x-www-form-urlencoded'},
      method:'POST',
      dataType:'',
      success:function(res){
        console.log(res,"shouye首尔也图片")
        let indexImgData = res.data.data;
        that.setData({
          indexImgData: indexImgData
        })
        // console.log(indexImgData,"indexImgDataindexImgDataindexImgData")
      }
    })
  },

  
  //获取公告栏信息
  getNotice: function () {
    let that = this;
    wx.request({
      url: app.globalData.hostname + 'kaiguan/getNotice',
      data: { business_id },
      header: { 'Content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      dataType: '',
      success: function (res) {
           let noticeData = res.data.data,
            notice = noticeData[0];
           var article = notice.content;
           article = article.replace(/&lt;/g, '<');
           article = article.replace(/&gt;/g, '>');
          //  article = article.replace(/&p;/g, ' ');  
           article = article.replace(/&amp;/g, "&");
           article = article.replace(/&nbsp;/g, " ");
           let notification = article.split('');
          //  let article = article.split('');
        that.setData({
          noticeData,
          notification,
          notice,
          article,
          animateTime: article.length > 22 ? (article.length * 0.5) + 's' : '0'
        })
        console.log(noticeData, notice, noticeData.id, "let that = this;let that = this;let that = this;")
      },
      fail: function (res) { },
      complete: function (res) {
      },
    })
  },


  //获取轮播图图片
  getSwiperImgUlrs: function (that) {
    wx.request({
      url: app.globalData.hostname + 'Kaiguan/getChart',
      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);
      },
    })
  },

  //显示隐藏首页轮播图
  getChartShow() {
    var that = this;
    wx.request({
      url: app.globalData.hostname + 'Kaiguan/chartConfig',
      data: { business_id },

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

        let chartShow = res.data.data;
        that.setData({
          chartShow: chartShow
        })
        console.log(chartShow, "新首页轮播")
      }
    })
  },

  

  //显示隐藏首页logo
  getLogoShow() {
    var that = this;
    wx.request({
      url: app.globalData.hostname + 'Kaiguan/navConfig',
      data: { business_id },

      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      dataType: '',
      success: function (res) {
        
        let logoShow = res.data.data;
        that.setData({
          logoShow: logoShow
        })
        console.log(logoShow, "新首页logo")
      }
    })
  },

  //获取视频
  getNewLogo() {
    var that = this;
    wx.request({
      url: app.globalData.hostname + 'Kaiguan/getVedio',
      data: { business_id },

      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      dataType: '',
      success: function (res) {
        console.log(res, "新首页视频")
        var videoData = res.data.data;
        var vimg = videoData.img
        that.setData({
          videoData: videoData,
          vimg: vimg
        })
        console.log(videoData, vimg,"videoData")
      }
    })
  },

  //分类首页显示
  getcatConfig() {
    var that = this;
    wx.request({
      url: app.globalData.hostname + 'Kaiguan/catConfig',
      data: { business_id },
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      dataType: '',
      success: function (res) {
        let cateShow = res.data.data;
        that.setData({
          cateShow: cateShow
        })
        console.log(res, "分类首页显示")
      }
    })
  },

  //分类首页显示
  getcatList() {
    wx.request({
      url: app.globalData.hostname + 'Kaiguan/getCat',
      data: { business_id },

      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      dataType: '',
      success: function (res) {
        console.log(res, "分类首页列表")
      }
    })
  },

  

  //getNavgetNavgetNav
  getNav() {
    var that = this;
    wx.request({
      url: app.globalData.hostname + 'Kaiguan/getNav',
      data: { business_id },

      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: 'POST',
      dataType: '',
      success: function (res) {
        console.log(res, "getNav getNav getNav")
        let swtich = res.data.data;
        that.setData({
          swtich
        })
      }
    })
  },


  //获取子门店列表
  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) {},
  //   })
  // },


  // 获取地址及经纬度
  getaddresslng: function (that) {

    wx.request({
      url: hostname + 'Goods/BusinessAddress',
      method: 'POST',
      data: { business_id },
      header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;' },
      success: (res) => {
        // console.log(res,"地图经纬度")
        let that = this;
        let markers = res.data;
        console.log(markers, "地图经纬度1")
        console.log(typeof markers, "123")
        let dz = res.data.lnglat.split(/,/);
        console.log(dz, "切割经纬度")
        if (res.data) {

          markers.longitude = dz[0]
          markers.latitude = dz[1]
        }
        that.setData({
          markers
        })
        console.log(markers, "地图经纬度2")
      }
    })
  },

// 前往地图导航
  goAddress(){
    let that = this;
    wx.openLocation({
      latitude: Number(that.data.markers.latitude),
      longitude: Number(that.data.markers.longitude),
      name:that.data.recommend[0].business_name,
      address:that.data.recommend[0].business_address
    })
  },

  // 前往拨打电话
  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) {},
    })
  },

  // 分类跳转
  goKind(e) {
    let that = this,
      { key,indexSign } = e.currentTarget.dataset;
    switch (key) {
      case 'mall':
        wx.navigateTo({
          url: '../pointsMall/pointsMall',
        })
        break;
      case 'egg':
        wx.navigateTo({
          url: '/pages/games/games?kind=eggs',
        })
        break;
      case 'guagua':
        wx.navigateTo({
          url: '/pages/games/games?kind=card',
        })
        break;
      case 'tuike':
        wx.navigateTo({
          url: '../pushoff/pushoff',
        })
        break;
      case 'order_center':
        wx.navigateTo({
          url: '../order/order',
        })
        break;
      case 'reserve':
        wx.switchTab({
          url: '../confirm_appointment/confirm_appointment',
        })
        break;
      case 'off_buy':
        wx.navigateTo({
          url: '../pay/pay',
        })
        break;
      case 'take_out':
        wx.switchTab({
          url: '../ManyStore/subStore/subStore',
        })
        break;
      case 'code':
        // wx.switchTab({
        //   url: '../ManyStore/subStore/subStore',
        // })
        wx.scanCode({
          success: (res) => {
            console.log(res)
          }
        })
        break;
      case 'about_us':
        wx.navigateTo({
          url: '../about/about',
        })
        break;
      case 'coupon':
        wx.navigateTo({
          url: '../coupon/coupon',
        })
        break;
        
      case 'DistributeCenter':
        wx.switchTab({
          url: '../center/center',
        })
        break;        
      case 'vip':
        wx.navigateTo({
          url: '../recharge/recharge',
        })
        break;
      case 'delicious':
        wx.navigateTo({
          url: '../Information/Information',
        })
        break; 
      case 'sign':
        wx.switchTab({
          url: '../center/center?indexSign=' + indexSign,
        })
        break;
      default:
        wx.navigateTo({
          url: '../luckydraw/luckydraw',
        })
        break;
    }
  },

  //  分类前往商店
  kindGoStore:function(){
    wx.switchTab({
      url: '../ManyStore/subStore/subStore',
    })

  },

  // 签到
  goSign:function(){
    var that = this;
    // indexSign = that.data.indexSign;
    if (that.data.isSign) {
      wx.showModal({
        title: 'Reminder',
        content: 'Check-In Today',
        confirmText:"OK",
        showCancel: false,
      })
    } else {
      wx.request({
        url: app.globalData.hostname + 'User/UserSignIn',
        method: 'POST',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
          openid: wx.getStorageSync('openId'),
          business_id: business_id
        },
        dataType: 'json',
        success: function (signRes) {
          that.setData({
            isSign: true,
          })
          wx.showToast({
            title: signRes.data.msg,
          })
        },
      })
      // 再次获取积分
      wx.request({
        url: app.globalData.hostname + 'Int/get_my_int',
        method: 'POST',
        header: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
        data: {
          openid: wx.getStorageSync('openId'), business_id
        },
        success: function (res) {
          console.log(res);
          that.setData({
            integralData: res.data.data
          })
        }
      })
    }
  },

  //判断是否已签到
  judgeSign: function (that) {
    if (!that.data.isSign) {
      wx.request({
        url: app.globalData.hostname + 'User/CheckUserSignIn',
        method: 'POST',
        header: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
          openid: wx.getStorageSync('openId'),
          business_id: business_id
        },
        success: function (judgeRes) {
          console.log(judgeRes);
          that.setData({
            isSign: judgeRes.data.status == -2 ? true : false //待定
          })
        },
        fail: function (res) { },
        complete: function (res) { },
      })
    }
  },


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