import CustomPage from '../../../base/CustomPage'
import storeGoods from '../../../api/storeGoods'

import OrderApi from '../../../api/order'

import {
  getCurrDistance
} from '../../../utils/location'

import storeList from '../../../api/storeList'
const cache = require('../../../utils/cache.js');
const user = require('../../../utils/user.js');
import base from '../../../utils/base'

CustomPage({
  onShareAppMessage() {
    return {
      storeInfo: null,
      store: null,
      distance: null,
      title: 'vtabs',
      path: 'page/weui/example/vtabs/vtabs',
      showViewDel: false
    }
  },
  data: {
    vtabs: [],
    activeTab: 0,
    totalPrice: 2,
    isShowCartPannel: false,
    cartSkuMapData: [{}],
    comBoFoodsList: [{}, {}],
    showView: true,
    showViewDel: false,
    showViewNotInStore: false,
    notInStoreImage: 'https://cdn1.overseasdragon.com.cn/xcx-smdd/order_not_in_store.png',
    openScroll: true,
    openGoodsScroll: false,
    goodsScrollTop: 0,
    currSpecGoods: {},
    allNum: 0,
    allFee: 0.0,
    isShowCartPannel: false,
    isShowSpecPannel: false,
    isShowComboPannel: false,
    collapseOrDetail: {},
    hasMobile: false,
    isShowComboSpecPannel: false,
    currSpecGoodsSpec: {},
    comBoShow: false,
    opacityStyle: "opacity8",
    orderMode: ''
  },

  // 进入门店列表
  goToStoreList() {
    wx.navigateTo({
      url: '/pages/groupmeallist/storeList/storeList',
    })


  },
  handleEmptyCart() {
    this.onChangeShowStateDelTrue()
    OrderApi.emptyCart({

      storeId: cache.getStoreId(),
      mobile: user.getMobileCache()
      // tableId: user.getTableId(),
      // orderMode: this.data.orderMode
    }).then(res => {
      if (res.code == 200) {
        this.loadCartData()
        this.setData({
          isShowCartPannel: false
        })
      }
    }).catch(_ => {})
  },


  //关闭删除弹出层
  onChangeShowStateDelTrue: function () {
    this.setData({
      showViewDel: false
    })
  },
  // 清空购物车
  onChangeShowStateDelFalse() {
    var that = this;
    that.setData({
      showViewDel: true
    })

  },
  // 商品详情
  gotoGoodDetails(e) {
    let idx = e.currentTarget.dataset.index;
    let fatherindex = e.currentTarget.dataset.fatherindex;

    let goods = this.data.vtabs[fatherindex].goodsList[idx]
    let goodsJson = JSON.stringify(goods)

    wx.navigateTo({
      url: '/pages/groupmeallist/goodDetails/goodDetails?goodsJson=' + goodsJson
    })


  },

  //创建订单
  confirmOrder() {

    wx.navigateTo({
      url: '../submitOrder/submitOrder',
    })


  },

  // 弹窗购物车面板
  popCartPannel: function () {
    if (this.data.isShowCartPannel) {
      this.closeCartPannel()
      return
    }
    if (this.data.allNum == 0) {
      return
    }
    this.showCartPannel();
  },
  // 详情和收起
  changeCollapseOrDetail: function (e) {
    let idx = e.currentTarget.dataset.idx;
    var that = this;
    that.data.cartSkuMapData[idx].show = !that.data.cartSkuMapData[idx].show
    that.setData({
      cartSkuMapData: that.data.cartSkuMapData
    });
    console.log("购物车详情");
    console.log(that.data.cartSkuMapData);
  },
  //关闭购物车面板
  closeCartPannel: function () {
    this.setData({
      isShowCartPannel: false
    })
  },
  //显示对话框
  showCartPannel: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 100,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      isShowCartPannel: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 100)
  },
  onLoad(options) {},

  async onShow() {
    let _self = this;

    //获取缓存赋值
    let location = cache.getCurrStore()
    console.log("缓存值")
    console.log(location)
    if (location != null) {
      _self.setData({
        storeInfo: location
      })

    } else {
      _self.authMobileLocation()

    }

    await this.loadData()
    await this.loadStoreData()
    await this.loadCartData()
    await this.cartPanelNum();
  },

  loadStoreData() {
    let store = cache.getCurrStore()
    console.log("store")
    console.log(store)
    this.setData({
      store: store || {}
    })
    getCurrDistance(store.longitude, store.latitude, (m, m1, m2) => {
      this.setData({
        distance: "距离您" + m1
      })
    })
  },


  async loadData() {
     await storeGoods.getExhibit(cache.getStoreId()).then(res => {
      if (res.code == 200) {
        this.dataMapView(res.data)
      }
    }).catch(_ => {
      
    })

  },


  handleAddToCart(e) {
    let goodsId = e.currentTarget.dataset.goodsid;
    let skuId = e.currentTarget.dataset.skuid || null;
    let combo = e.currentTarget.dataset.combo;

    this.addSubCart(goodsId, skuId, 1, combo)
  },

  async addSubCart(goodsId, skuId, num, comboSkuList) {

    console.log("进入套餐购物api")
    await storeGoods.comBoaddToCart({
      storeId: cache.getStoreId(),
      mobile: cache.getMobile(),
      skuId: skuId,
      num: num,
      comboSkuList: comboSkuList,
    }).then(res => {
      if (res.code == 200) {
        this.refreshCartData()
      }
    }).catch(_ => {})
    await this.loadCartData()




  },

  handleSubToCart(e) {
    let goodsId = e.currentTarget.dataset.goodsid;
    let skuId = e.currentTarget.dataset.skuid || null;
    let combo = e.currentTarget.dataset.combo;

    this.addSubCart(goodsId, skuId, -1, combo)

  },

  dataMapView(data) {

    // let bannerList = null;
    // if (data.bannerList && data.bannerList.length > 0) {
    //     bannerList = data.bannerList;
    // }
    let tabs = [];
    if (data.classifyGoodsList && data.classifyGoodsList.length > 0) {
      console.log("进入方法")
      data.classifyGoodsList.forEach(v => {
        let classify = v.classify || {}
        let node = {
          title: classify.classifyName,
          img: classify.fullClassifyFigure,
          classifyId: classify.classifyId,
          classifyCode: classify.classifyCode,
          classifyName: classify.classifyName,
          fullClassifyFigure: classify.fullClassifyFigure,
          goodsList: v.goodsList
        }

        v.goodsList.forEach((vv, i) => {
          if (base.isArray(vv.productSkuList)) {
            let minPriceSku = this.getMinPriceGoods(vv.productSkuList)
            vv.priceY = minPriceSku.priceY
            vv.oriPriceY = minPriceSku.oriPriceY
            vv.minPriceSku = minPriceSku
          }
          if (base.isEmpty(vv.openSpec) && base.isArray(vv.productSkuList) && vv.productSkuList.length > 0) {
            if (vv.minPriceSku) {
              vv.skuId = vv.minPriceSku.skuId
            } else {
              vv.skuId = vv.productSkuList[0].skuId
            }
          }
        })
        tabs.push(node)
      })

      this.setData({
        vtabs: tabs,
      })
      // console.log("this.data.vtabs")
      // console.log(this.data.vtabs)
    }


  },
  getMinPriceGoods(productSkuList) {
    let minPriceSku = null;
    productSkuList.forEach(sku => {
      if (minPriceSku == null) {
        minPriceSku = sku
      } else {
        if (minPriceSku.price > sku.price) {
          minPriceSku = sku
        }
      }
    })
    return minPriceSku
  },
  /**
   * 加载购物车数据
   */
  async loadCartData() {
    await storeGoods.getCartData(cache.getStoreId(), user.getMobileCache(), null, null).then(res => {
      if (res.code == 200) {
         this.cartDataMapToView(res.data)
      }
    }).catch(_ => {
      console.log(_)
    })
  },
  cartPanelNum() {
    this.data.vtabs.forEach((item, i) => {
      item.goodsList.forEach((children, x) => {
        this.data.cartSkuMapData.forEach((sku, s) => {
          if (sku.skuId == children.minPriceSku.skuId) {
            children.chooseNum = sku.num
          }
        })
      })
    })

    this.setData({
      vtabs: this.data.vtabs
    })

    console.log(this.data.vtabs)

  },
  // 购物车数据映射
  cartDataMapToView(data) {
    // var isShowCartPannel = true;
    if (base.isEmpty(data.skuList) || data.skuList.length == 0) {
      // isShowCartPannel = false
      data.totalPriceY = "0.00"
      data.totalNum = 0
    }

    console.log("进入购物车塞值")

    this.setData({
      allFee: data.totalPriceY,
      allNum: data.totalNum,
      cartSkuMapData: data.skuList,
      // isShowCartPannel: isShowCartPannel,
      isShowSpecPannel: false,
    })

    // if (base.isEmpty(data.skuList) || data.skuList.length == 0) {
    //     this.setData({
    //         allFee: 0.0,
    //         allNum: 0,
    //         cartSkuMapData: {},
    //         isShowCartPannel: false,
    //     })
    //     return
    // }
    // this.data.cartSkuMapData = {}
    // // 总金额
    // let allFee = 0;
    // // 总商品数
    // let allNum = 0;
    // data.skuList.forEach(sku => {
    //     this.data.cartSkuMapData[sku.skuId] = sku
    //     sku.allFee = base.fenToYuan(sku.num * sku.price)
    //     allFee = allFee.add(sku.allFee)
    //     allNum = allNum.add(sku.num)
    //     sku.allOriFee = base.fenToYuan(sku.num * sku.oriPrice)
    // })
    // this.setData({
    //     allFee: allFee,
    //     allNum,
    //     cartSkuMapData: this.data.cartSkuMapData
    // })
  },
  /**
   * 获取定位
   */
  getPosition() {
    let _self = this;
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        console.log(res);
        const latitude = res.latitude
        const longitude = res.longitude
        //存储最近的经纬度
        cache.setNearLocation(longitude, latitude);

        _self.nearbyStoreList(longitude, latitude);
      },
      fail(res) {
        console.log(res)
      }
    })
  },

  /**
   * 获取最近的门店
   */
  async nearbyStoreList(longitude, latitude) {
    let _self = this;
    try {
      let storeRes = await storeList.nearbyStoreList(longitude, latitude);
      if (storeRes.code == 200 && storeRes.msg == "success") {
        let data = storeRes.data;
        _self.setData({
          storeInfo: data
        })

        cache.setCurrStore(data)
      }
    } catch (error) {
      console.log(error);
    }
  },
  authMobileLocation: function () {
    var _self = this;
    wx.getSystemInfoAsync({
      success(res) {
        console.log(res)
        if (res.locationEnabled) {
          _self.authLocation();
        } else {
          wx.showToast({
            title: '请打开手机位置信息',
            icon: 'none',
            duration: 1000
          })

        }

      }
    })
  },
  authLocation: function () {
    var _self = this;
    wx.getSetting({ //先查看授权情况
      success: function (res) {
        console.log(res);
        var statu = res.authSetting;
        //判断是否授权，没有授权就提示下面的信息
        //undefined  是第一次没有拒绝 也没有同意
        //true 是已经同意了
        //false  是拒绝了
        if (statu['scope.userLocation'] === undefined || statu['scope.userLocation'] === true) {
          _self.getPosition()
          return;
        }

        //授权被拒绝了 需要重新允许小程序授权
        if (statu['scope.userLocation'] === false) {
          wx.showModal({
            title: '需要获取您的地理位置，请确认授权，否则小程序功能将无法使用',
            cancelColor: '需要获取您的地理位置，请确认授权，否则小程序功能将无法使用',
            success: function (tip) {
              if (tip.confirm) { //查看是否点击确定
                wx.openSetting({ //打开设置
                  success: function (data) {
                    if (data.authSetting["scope.userLocation"] == true) { //到这一步表示打开了位置授权   
                      _self.getPosition()
                    }

                  },

                })
              } else {
                wx.showToast({
                  title: '取消授权',
                  icon: 'none',
                  duration: 1000
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: '请给小程序授权位置服务',
            icon: 'none',
            duration: 1000
          })
        }
      }
    })
  },

  onTabClick(e) {
    const index = e.detail.index
    console.log('tabClick', index)
  },

  onChange(e) {
    const index = e.detail.index
    console.log('change', index)
  },
  handleClick() {
    wx.navigateTo({
      url: '../tabs/webview',
    })
  }

})