// pages/orderBy/orderBy.js
import {
  get,
  post
} from '../../utils/http'
import {
  PROJECT_TYPE
} from '../../utils/global'
import {
  getStoreInfo
} from '../../utils/util'
const app = getApp()

Page({
  /**
   * 页面的初始数据
   */
  data: {},

  initData: {
    current: 0,
    currentType: 1,
    currentList: [{
        id: 0,
        title: '精选项目',
        type: PROJECT_TYPE.project,
        source: 'project',
        child: []
      },
      {
        id: 1,
        title: '项目耗材',
        type: PROJECT_TYPE.product,
        source: 'product',
        child: []
      },
      {
        id: 2,
        title: '项目卡券',
        type: PROJECT_TYPE.cardgoods,
        source: 'cardgoods',
        child: []
      },
      {
        id: 3,
        title: '美妆产品',
        type: PROJECT_TYPE.goods,
        source: 'goods',
        child: []
      },
      {
        id: 4,
        title: '次卡',
        type: PROJECT_TYPE.secondaryCard,
        source: 'secondaryCard',
        child: []
      }
    ],
    currentKeys: {},
    currentItemIndex: 0,
    currentItemCatId: 0,
    productData: {},
    productDataLoading: false,
    storeId: 0,
    storeData: {},
    inFirstIn: false,
    navBarData: app.globalData.navBarData,
    navBarBgClass: '',
    selectProductList: 0,
    productListV2: [],
    showProducePup: false,
    selectProductData: {},
    selectProductIndex: '',
    selectProductCar: [],
    onCloseCar: false,
    showMoney: 0.0,
    toView: '',
    orderDiscount: {},
    onMakeup: false,
    // 美妆产品购物车列表
    selectMakeupList: [],
    page: 1,
    limit: 20,
    showMoneyGood: 0,
    // 点击美妆产品购物袋图标标识
    isIcon: false,
    // 产品id
    sourceId: '',
    // 每个商品数据
    proItem: '',
    // 美妆产品总数量
    sum: 0,
    // 商品价格
    v2_price: '',
    goods_ids: [], //购物车中的产品id
    exchangeInfo: [], //需要加购多少商品的价格信息
    isNewUser: 0, //结果，1是新用户，0不是新用户
  },

  /**
   * 首页数据
   */
  getHomeData() {
    get('api/home', {}, (res) => {
      this.setData({
        homeData: res.data
      }, )
    })
  },

  /**
   * 获取当前用户折扣
   * 折扣类型，0.无折扣，20.任意三个项目8折，50.新人五折活动，100.仪器免费使用权益
   */
  orderDiscount() {
    get('v2/api/order/discount', {}, (res) => {
      this.setData({
        orderDiscount: res.data
      }, )
    })
  },

  // 选择项目左边的操作
  selectProductList(e) {
    let selectProductList = e.currentTarget.dataset.index
    this.setData({
      selectProductList: selectProductList,
      toView: 'A' + selectProductList
    })
  },

  selectProduct(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      selectProductIndex: index
    })
  },

  rpxTopx(rpx) {
    let deviceWidth = wx.getSystemInfoSync().windowWidth; //获取设备屏幕宽度
    let px = (deviceWidth / 750) * Number(rpx)
    return Math.floor(px);
  },

  onDoHeight() {
    let productListV2 = this.data.productListV2
    let inHeight = 0
    let doHeight = []
    doHeight.push(0)
    for (let i = 0; i < productListV2.length; i++) {
      if (productListV2[i].products[0] && productListV2[i].products[0].type == 'one') {
        let needAdd = 0
        for (let j = 0; j < productListV2[i].products.length; j++) {
          needAdd = needAdd + 280 * productListV2[i].products[j].items.length + 140
        }

        inHeight = inHeight + this.rpxTopx(20 + 40 + 20 + needAdd)
        // console.log('xxxxxxxxxxx走了这里哈哈哈' + needAdd)
      } else {
        inHeight = inHeight + this.rpxTopx(20 + 40 + 20 + 280 * productListV2[i].products.length)
      }
      doHeight.push(inHeight)
    }
    this.setData({
      doHeight: doHeight
    })
    // console.log(doHeight)
  },

  scroll(e) {
    let that = this
    let doHeight = this.data.doHeight
    // console.log(e.detail.scrollTop)

    if (e.detail.scrollTop < doHeight[1] - 20) {
      that.setData({
        selectProductList: 0,
      })
      return
    }

    for (let i = 0; i < doHeight.length; i++) {

      if (e.detail.scrollTop > (doHeight[i] - 20) && e.detail.scrollTop < doHeight[i + 1]) {
        // console.log(e.detail.scrollTop)

        that.setData({
          selectProductList: i,
        })
      }
    }

    // if (e.detail.scrollTop > )

  },

  // 关闭产品包
  onClosePay() {
    this.setData({
      showProducePup: false
    })
    this.setData({
      isIcon: this.data.showProducePup
    })
  },

  buttomCar: function () {
    this.setData({
      onCloseCar: true
    })
  },

  // 删除购物车
  inDeleteCarOne(e) {
    let index = e.currentTarget.dataset.index
    let selectProductCars = this.data.selectProductCar
    selectProductCars.splice(index, 1)
    this.setData({
      selectProductCar: selectProductCars
    })
    this.showCarMoney()
  },

  toSubmit: function () {
    if (this.data.selectProductCar.length == 0) {
      return
    }
    // 判断是否是新用户
    let money = 0
    if (this.data.isNewUser == 1) {
      money = this.data.showMoney
    } else {
      money = this.data.showMoney
    }
    wx.navigateTo({
      url: '../reserveCar/reserveCar?data=' + JSON.stringify(this.data.selectProductCar) + '&&money=' + this.data.showMoney + '&&type=project',
    })
  },

  onKeySubmit: function (e) {
    let keySubmit = e.currentTarget.dataset.item
    wx.navigateTo({
      url: '../reserveCar/reserveCar?data=' + JSON.stringify(keySubmit) + '&&money=' + keySubmit.price + '&&type=one',
    })
  },

  showCarMoney() {
    let that = this
    let money = 0
    let selectProductCars = this.data.current == 3 ? this.data.selectMakeupList : this.data.selectProductCar
    console.log(selectProductCars);
    for (let i = 0; i < selectProductCars.length; i++) {
      // 判断是否是新人有新人价格
      let price = this.data.isNewUser == 1 && selectProductCars[i].new_price != 0 ? selectProductCars[i].new_price : selectProductCars[i].price
      money = money + price
      console.log(money, 'moneymoney');
      if (selectProductCars[i].selectMaterial) {
        money = money + selectProductCars[i].selectMaterial.price * 1
      }
    }
    this.setData({
      showMoney: money.toFixed(2)
    })
  },

  onCloseCar: function () {
    this.setData({
      onCloseCar: false
    })
  },


  // 选择项目
  toSelectProduct(e) {
    let toSelectProduct = e.currentTarget.dataset.item
    for (let i = 0; i < this.data.selectProductCar.length; i++) {
      if (toSelectProduct.id == this.data.selectProductCar[i].id) {
        wx.showToast({
          title: '单项目只能选一次!',
          icon: "none"
        })

        return
      }
    }

    this.setData({
      toSelectProduct: toSelectProduct,
      selectProductIndex: '空',
      showProducePup: true
    })
    this.productV2(toSelectProduct.id)
  },

  submit_bottom: function () {
    let selectProductCars = this.data.selectProductCar
    let toSelectProducts = this.data.toSelectProduct
    if (this.data.selectProductIndex == '空') {
      toSelectProducts.selectMaterial = ''
    } else {
      toSelectProducts.selectMaterial = this.data.selectProductData.upgrade[this.data.selectProductIndex]
    }
    selectProductCars.push(toSelectProducts)
    this.setData({
      showProducePup: false,
      selectProductCar: selectProductCars
    })
    this.showCarMoney()
  },


  /**
   * 跳转店铺列表
   */
  goToStore() {
    if (this.data.inFirstIn) {
      return;
    }
    wx.navigateTo({
      url: '/pages/store/store?defaultStore=' +
        JSON.stringify(this.data.homeData.store)
    })
  },

  /**
   * 店铺信息
   * /api/store/info
   */
  getStoreInfo(store_id) {
    get(
      'api/store/info', {
        store_id
      },
      (res) => {
        this.setData({
            ['homeData.store']: res.data
          },
          () => {
            wx.setStorageSync('store_id', String(store_id))
            app.globalData.storeData = res.data
          }
        )
        console.log(res)
      }
    )
  },

  /**
   * 获取项目产品数据
   * /api/store/info
   */
  productList() {
    get(
      'v2/api/product/list', {
        store_id: this.data.storeId
      },
      (res) => {
        // 新人价格去掉.00
        res.data.forEach(item => {
          item.products.forEach(item => {
            item.new_price = Number(item.new_price)
          })
        });
        this.setData({
          productListV2: res.data
        })
        this.onDoHeight()
        if (app.globalData.toViewIndex != 0) {
          this.setData({
            toView: 'A' + (app.globalData.toViewIndex - 1),
            selectProductList: app.globalData.toViewIndex - 1
          })
        } else {
          this.setData({
            toView: 'A' + 0,
            selectProductList: 0
          })
        }
        console.log(res)
      }
    )
  },

  /**
   * 获取升级产品列表
   * /api/store/info
   */
  productV2(id) {
    get(
      'v2/api/product/product', {
        id: id,
        store_id: this.data.storeId
      },
      (res) => {
        this.setData({
          selectProductData: res.data
        })
        console.log(res)
      }
    )
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options, 'options');
    this.setData({
      navBarHeight: app.globalData.navBarData.navBarHeight,
    })
    // this.getHomeData()
    let data = JSON.parse(JSON.stringify(this.initData))
    data.storeData = getApp().globalData.storeData
    data.storeId = data.storeData.id || wx.getStorageSync('store_id')
    // 存在传入的分类类型
    if (options.hasOwnProperty('cat_type')) {
      data.currentKeys = this.buildKeys(data.currentList, 'type')
      let _current = data.currentKeys['key_' + options.cat_type]
      if (_current != undefined) {
        data.current = _current
        data.currentType = options.cat_type
      }
    }
    // 存在传入的店铺ID
    if (options.hasOwnProperty('store_id')) {
      data.storeId = options.store_id
      // 更新店铺信息
      getStoreInfo(data.storeId)
        .then((res) => {
          data.storeData = res
          this.setData({
            storeData: res
          })
        })
        .catch(() => {})
    }
    this.setData(data, () => {
      this.getProductCategory(options)
    })
    this.productList()
    this.needAddGood()
    // 进入页面判断是否是直接跳转到美妆产品的是的话调用修改类型
    if (app.globalData.showGoods) {
      this.gotoGoods()
    }
  },
  // 监听页面隐藏
  onHide() {
    // 将全局的项目分类下标重置
    app.globalData.toViewIndex = 0
  },
  noneEnoughPeople() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.orderDiscount()
    let version1 = wx.getStorageSync('version1')
    if (!version1 || version1 != 1) {
      this.setData({
        // inFirstIn: true
      })
      wx.setStorageSync('version1', 1)
    }
    // 当切换了店铺时，重新请求一次数据
    let storeData = getApp().globalData.storeData
    let storeId = storeData.id || wx.getStorageSync('store_id')
    if (storeId != this.data.storeId && this.data.storeId) {
      let data = JSON.parse(JSON.stringify(this.initData))
      this.setData(data, () => {
        this.setData({
          storeId: storeId,
          storeData: storeData
        }, () => {
          this.getProductCategory()
          this.getStoreInfo(storeId)
          this.productList()
        })
      })
    } else {
      this.getStoreInfo(storeId)
    }
    let that = this
    let curres = wx.getStorageSync('curre')
    // console.log('haves1')
    if (curres && curres == 1) {
      // console.log('haves')
      let item = that.data.currentList[0]
      this.setData({
          current: item.id,
          currentItemIndex: 0,
          currentType: item.type
        },
        () => {
          // this.getProduct(item.type, item.child[0].id)
          let _dataset = {
            currentTarget: {
              dataset: {
                item: item.child[0],
                index: 0
              }
            }
          }
          this.onTabsItem(_dataset)
        }
      )
      wx.setStorageSync('curre', 0)
    }
    setTimeout(() => {
      if (this.data.current == 3) {
        this.needAddGood()
      } else {
        this.needAddCar()
      }
    }, 500)
    if (app.globalData.toViewIndex != 0) {
      this.setData({
        toView: 'A' + (app.globalData.toViewIndex - 1),
        selectProductList: app.globalData.toViewIndex - 1
      })
    } else {
      this.setData({
        toView: 'A' + 0,
        selectProductList: 0
      })
    }
    // 检查是否是新用户
    this.checkNewUser()
  },
  //精选项目
  needAddCar() {
    let toSelectProduct = wx.getStorageSync('toSelectProduct')
    if (toSelectProduct && JSON.parse(toSelectProduct) == []) {
      wx.setStorageSync('toSelectProduct', JSON.stringify([]))
      return
    }
    let cardAddData = []
    if (toSelectProduct) {
      cardAddData = JSON.parse(toSelectProduct)
    }
    wx.setStorageSync('toSelectProduct', JSON.stringify([]))
    let selectProductCarData = this.data.selectProductCar
    for (let i = 0; i < selectProductCarData.length; i++) {
      if (selectProductCarData[i].id == cardAddData[i].id || cardAddData.id) {
        return
      }
    }
    console.log(selectProductCarData, 'cardAddData', cardAddData);

    selectProductCarData = selectProductCarData.concat(cardAddData)
    this.setData({ //对上一个页面data中的参数进行赋值（上一个页面的数据是在当前页面进行赋值的），就变相实现了向上一个页面传值
      selectProductCar: selectProductCarData
    })
    this.showCarMoney()
  },
  //美妆产品
  needAddGood() {
    let params = {
      store_id: this.data.storeId,
      page: this.data.page,
      limit: this.data.limit
    }
    get('v2/api/car/list', params, (res) => {
      if (res.code == 200) {
        let selectProductCarData = []
        selectProductCarData = selectProductCarData.concat(res.data.list)
        // 购物车产品总数量
        let sum = 0
        selectProductCarData.map(item => {
          sum += item.num
        })
        selectProductCarData.sum = sum
        // 设置美妆产品购物车总数量
        this.setData({
          sum: sum
        })
        this.setData({
          selectMakeupList: selectProductCarData,
          showMoneyGood: res.data.total_money == null ? "0.00" : res.data.total_money
        })
        if (this.data.selectMakeupList < res.data.count) {
          this.setData({
            page: this.data.page + 1
          })
          this.needAddGood()
        }
        if (res.data.list.length == 0) {
          this.setData({
            onMakeup: false
          })
        }
      }
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getProduct(this.data.currentType, this.data.currentItemCatId, 1)
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},

  /**
   * 转化对象
   */
  buildKeys: function (params, key) {
    let keys = {}
    for (let i = 0; i < params.length; i++) {
      let item = params[i]
      keys['key_' + item[key]] = i
    }
    return keys
  },

  /**
   * 切换tabs
   */
  onTabsChange(e) {
    if (this.data.inFirstIn) {
      return;
    }
    let item = e.currentTarget.dataset.item
    this.setData({
        current: item.id,
        currentItemIndex: 0,
        currentType: item.type
      },
      () => {
        // this.getProduct(item.type, item.child[0].id)
        let _dataset = {
          currentTarget: {
            dataset: {
              item: item.child[0],
              index: 0
            }
          }
        }
        this.onTabsItem(_dataset)
        if (this.data.current == 3) {
          this.needAddGood()
          return
        }
        this.showCarMoney()
      }
    )
  },

  /**
   * 切换子tabs
   */
  onTabsItem(e) {
    console.log(e, 'e')
    if (this.data.inFirstIn) {
      return;
    }
    // this.setData({
    //   inFirstIn:true
    // })
    let that = this
    let item = e.currentTarget.dataset.item
    let currentItemIndex = e.currentTarget.dataset.index
    if (!item) {
      return
    }
    this.setData({
        currentItemIndex: currentItemIndex,
        currentItemCatId: item.id
      },
      () => {
        console.log(this.data.current, 'this.data.current')
        // if(this.data.current === 4){
        //   // 查询次卡列表
        //   this.getSecondaryCardList(that.data.currentType, item.id)
        // } else {
        //   that.getProduct(that.data.currentType, item.id)
        // }
        that.getProduct(that.data.currentType, item.id)
      }
    )
  },

  knowSubmit: function () {
    this.setData({
      inFirstIn: false
    })
  },

  /**
   * 获取产品分类
   */
  getProductCategory(options = {}) {
    let {
      currentList,
      current,
      currentType,
      currentItemIndex,
      currentItemCatId
    } = this.data
    get('api/product/category', {}, (res) => {
      console.log(res, 'res')
      let {
        project,
        product,
        cardgoods,
        other
      } = res.data
      currentList[0].child = project
      currentList[1].child = product
      currentList[2].child = cardgoods
      currentList[3].child = other
      currentList[4].child = cardgoods
      // 存在传入的分类ID
      if (options.hasOwnProperty('cat_id')) {
        let catKyes = this.buildKeys(currentList[current].child, 'id')
        let _currentItemIndex = catKyes['key_' + options.cat_id]
        if (_currentItemIndex != undefined) {
          currentItemIndex = _currentItemIndex
          currentItemCatId = options.cat_id
        }
      } else {
        // 判断是否是跳转到下单页面直接显示美妆产品
        if (app.globalData.showGoods) {
          current = (other.length > 0 && '3') ||
            (project.length > 0 && '0') ||
            (product.length > 0 && '1') ||
            (cardgoods.length > 0 && '2')
        } else {
          current = (project.length > 0 && '0') ||
            (product.length > 0 && '1') ||
            (cardgoods.length > 0 && '2') ||
            (other.length > 0 && '3')
        }
        switch (current) {
          // 默认值
          case 0:
            currentItemCatId = project[0].id
            break
          case 1:
            currentItemCatId = product[0].id
            break
          case 2:
            currentItemCatId = cardgoods[0].id
            break
          case 3:
            currentItemCatId = other[0].id
            break
        }
      }
      this.setData({
          currentList,
          current,
          currentItemIndex,
          currentItemCatId
        },
        () => {
          if (project.length > 0) {
            this.getProduct(currentType, currentItemCatId)
          }
        }
      )
    })
  },

  /**
   * 项目/产品列表
   * type: 数据类型，1项目，2项目耗材，3美妆产品，默认1
   */
  getProduct(ptype, pcat_id, turn = 0) {
    let that = this
    let key = `pkey_${ptype}_${pcat_id}`
    let {
      productData,
      productDataLoading,
      storeId
    } = that.data
    let pcatData = productData[key] || {
      total: 0,
      list: [],
      page: 1,
      has_more: 1,
      type: ptype,
      cat_id: pcat_id
    }
    if (productDataLoading || !pcatData.has_more) return
    // 是否为翻页
    if (!turn && pcatData.total > 0) return
    this.setData({
      productDataLoading: true
    })
    let page = pcatData.page

    get(
      this.data.current !== 4 ? 'api/product' : 'v2/api/card/list', this.data.current !== 4 ? {
        store_id: storeId,
        type: ptype,
        category_id: pcat_id,
        page: page
      } : {
        store_id: storeId,
        category_id: pcat_id,
        page: page,
        limit: 5
      },
      (res) => {
        that.setData({
          productDataLoading: false
        })
        let plist = pcatData.list.concat(res.data.list)
        page++
        pcatData = Object.assign(pcatData, {
          total: res.data.total,
          page: page,
          list: plist,
          has_more: plist.length < res.data.total && res.data.list.length > 0
        })
        productData[key] = pcatData
        this.setData({
          productData: productData
        })
      },
      (err) => {
        that.setData({
          productDataLoading: false
        })
      }
    )
  },
  // 获取需要加购多少商品的价格
  getExchangePrice() {
    post('v2/api/car/plus_project', {
      store_id: this.data.storeId || wx.getStorageSync('store_id'),
      goods_id: '',
      type: 1
    }, (res) => {
      if (res.code == 200) {
        this.setData({
          exchangeInfo: res.data
        })
      }
    })
  },
  onOpenMakeup() {
    // 获取需要加购多少商品的价格
    this.getExchangePrice()
    this.setData({
      onMakeup: true
    })
  },
  onCloseMakeup() {
    this.setData({
      onMakeup: false
    })
  },
  // 删除购物车
  inDeleteCarGood(e) {
    let index = e.currentTarget.dataset.index
    get('v2/api/car/del', {
      car_id: this.data.selectMakeupList[index].id
    }, res => {
      if (res.code == 200) {
        this.needAddGood()
        // 获取需要加购多少商品的价格
        this.getExchangePrice()
      }
    })
  },
  //购物车结算
  toSubmitGood: function () {
    if (this.data.selectMakeupList.length == 0) {
      return
    }
    // let _projectData = this.data.selectMakeupList
    // 筛选出购物车中所有商品的id
    let {
      goods_ids
    } = this.data
    goods_ids = []
    this.data.selectMakeupList.map(item => {
      goods_ids.push(item.goods_id)
    })
    wx.navigateTo({
      url: `/pages/goodsOrderConfirm/goodsOrderConfirm?source=goods&storeId=${this.data.storeId}&goods_ids=${goods_ids}&type=1`,
    })
  },
  onChangeNum(e) {
    let params = {
      car_id: this.data.selectMakeupList[e].id,
      num: this.data.selectMakeupList[e].num
    }
    get('/v2/api/car/add_number', params, res => {
      if (res.code == 200) {
        this.needAddGood()
        // 获取加购多少商品价格
        this.getExchangePrice()
      }
    })
  },
  onReduce(e) {
    let index = e.currentTarget.dataset.index
    let num = this.data.selectMakeupList[index].num
    num = num - 1
    if (num < 0) {
      num = 0
    }
    let dataNum = `selectMakeupList[${index}].num`
    this.setData({
      [dataNum]: num
    })
    this.onChangeNum(index)
  },
  onLationAdd(e) {
    let index = e.currentTarget.dataset.index
    let num = this.data.selectMakeupList[index].num
    num = num + 1
    let dataNum = `selectMakeupList[${index}].num`
    this.setData({
      [dataNum]: num
    })
    this.onChangeNum(index)
  },
  // 点击美妆产品购物袋图标显示弹出购物车框
  showProduce(e) {
    console.log(e);
    this.setData({
      showProducePup: true,
      sourceId: e.target.dataset.proitem.id,
      proItem: e.target.dataset.proitem
    })
    this.setData({
      isIcon: this.data.showProducePup
    })
  },
  // 点击美妆产品购物袋加入购物车
  submit_add(type) {
    let params = {
      goods_id: this.data.sourceId,
      store_id: this.data.storeId
    }
    post('v2/api/car/add', params, (res) => {
      if (res.code == 200) {
        if (type == 'shopping') {
          wx.navigateTo({
            url: `/pages/goodsOrderConfirm/goodsOrderConfirm?storeId=${this.data.storeId}`,
          })
        } else {
          wx.showToast({
            title: '成功加入购物车!',
            icon: 'none'
          })
          this.needAddGood()
          setTimeout(() => {
            // wx.switchTab({
            //   url: '/pages/orderBy/orderBy?cat_type=3',
            // })
            this.setData({
              showProducePup: false,
              isIcon: false
            })
          }, 1000)
        }
      }
    })
  },
  // 点击商品或者按钮直接跳转到下单页面的美妆产品页面(进入页面将类型改为美妆产品)
  gotoGoods() {
    this.setData({
      current: 3,
      currentType: 3,
    })
  },
  // 监听tab切换(判断进入页面是是否是上次跳转进来的美妆产品如果是直接刷新（current==3判断类型）)
  onTabItemTap() {
    //具体操作
    if (this.data.current == 3) {
      wx.reLaunch({
        url: '/pages/orderBy/orderBy',
      })
    }
  },
  // 检查是否是新用户
  checkNewUser() {
    get('v2/api/order/check_new_user', {}, (res => {
      // 结果，1是新用户，0不是新用户
      this.setData({
        isNewUser: res.data.status
      })
    }))
  }
})