// pages/category/category.js

var http = require("../../utils/http.js");
var util = require('../../utils/util.js');
var config = require("../../utils/config.js");
import eventBus from '../../utils/eventBus';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    rightView:'',
    paramsObj:{
      sort:0,
      orderBy:0
    },
    type:'bottom',
    toViewId:'test1',
    topHeight:300,
    sort:0,
    imgUrl:'https://zswl-shop.oss-cn-chengdu.aliyuncs.com/',
    testShopId:0,//109
    totalInfo:{"totalMoney":0,"finalMoney":0,"subtractMoney":0.0,"count":0},
    shopId:0,
    show:false,
    showCar:false,
    selIndex: 0,
    selCategory:0,
    subIndex:0,
    thridIndex:-1,
    subCategoryId:0,
    categoryList: [],
    categoryImg: '',
    subCategoryList: [],
    thridCategoryList:[],
    pageTopHeight: wx.getWindowInfo().statusBarHeight,
    hotList: [],
    topCurrentIndex: 0,
    productList:[],
    carData:[],//购物车数据
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    this.getRecommended()
    // this.get_neighborShop()
    // this.get_categoryInfo()
  },
  scroll(){
  },
  scrollTop(){
    console.log('top',);
    if(this.data.subIndex==0||this.data.subCategoryList.length==0) return
    this.setData({
      type:'top'
    })
    let data = {currentTarget:{
      dataset:{
        index:this.data.subIndex-1
      }
    }}
    this.onleftMenuTab(data)
    // this.setData({
    //   topHeight:0
    // })
  },
  scrollBottom(){
    console.log('bottom');
    if(this.data.subIndex==(this.data.subCategoryList.length-1)||this.data.subCategoryList.length==0) return
    this.setData({
      type:'bottom'
    })
    let data = {currentTarget:{
      dataset:{
        index:this.data.subIndex+1
      }
    }}
    this.onleftMenuTab(data)
    // this.setData({
    //   topHeight:0
    // })
  },
  handleSale(){
    this.setData({
      sort:1,
      paramsObj:{sort:1,orderBy:0}
    })
    this.getData(this.data.subCategoryList[this.data.subIndex])
  },
  handlePrice(){
    // 没点击价格
    if(this.data.sort !=2&&this.data.sort!=3){
      this.setData({
        sort:2,
        paramsObj:{sort:2,orderBy:0}
      })
    }else{
     let sort = this.data.sort ==2?3:2
     this.setData({
      sort,
      paramsObj:{sort:2,orderBy:this.data.sort ==2?0:1}
    })
    }
    this.getData(this.data.subCategoryList[this.data.subIndex])
  },
  resetData(){
    this.setData({
      subIndex:0,
      thridIndex:-1,
      subCategoryId:0,
    })
  },
  // 点击购物车内加减按钮
  handleNum(e){
    let {num,item} = e.currentTarget.dataset
    console.log(num,item);
    let data = {
      "basketId": item.basketId||0,
      "count": num,
      "distributionCardNo": item.distributionCardNo||'',
      "prodId": item.prodId,
      "shopId": item.shopId,
      "skuId": item.skuId||item.skuList[0].skuId
    }
    this.changeCar(data)
  },
  handleAll(){
    this.setData({
      show:true
    })
  },
  onClose(){
    this.setData({
      show:false
    })
  },
  openCar(){
    console.log(111111);
    this.setData({
      showCar:true
    })
  },
  onCarClose(){
    this.setData({
      showCar:false
    })
  },
  /**
   * 获取距离最近店铺id
   * @param {*} e 
   */
   get_neighborShop: function () {
    var params = {
      url: "/shop/neighborShop",
      method: "GET",
      data: {
        lat: wx.getStorageSync('LATITUDE'),
        lon: wx.getStorageSync('LONGITUDE'),
      },
      callBack: (res) => {
        // this.get_categoryInfo(res)
    console.log(99999999,res);

        this.setData({
          shopId:res.shopId
        })
          this.get_categoryInfo(res.shopId)
          this.getCarData(this.data.shopId)
      }
    };
    http.request(params);
  },
  get_categoryInfo: function (shopid) {
    var ths = this;
    let that = this
    //加载分类列表
    var params = {
      // url: "/category/categoryInfo",
      url: "/category/listCategoryForUser/"+(this.data.testShopId||shopid),
      method: "GET",
      callBack: function (res) {

        ths.setData({
          categoryList: res,
          subCategoryList: res[ths.data.selIndex].children
        });
        eventBus.on('categoryId', (data) => {
          that.data.categoryList.map((item,index)=>{
              if(item.categoryId == data){
                
                that.setData({
                  selCategory:data,
                  selIndex:index,
                  subCategoryList:res[index].children
                })
                eventBus.clear('categoryId')
              }
          })
        });
        console.log(ths.data.subCategoryList);
        ths.getData(ths.data.subCategoryList[0])
   
      }
    };
    http.request(params);
  },
  getData(data){
      this.setData({
        thridCategoryList:[]
      })
      // 二级分类有商品
      if(data.productBeBound == 1){
        this.getProdList(data.categoryId)
      }else{//二级分类有三级分类
        this.getAllProList(data.categoryId)
        this.setData({
          thridCategoryList:data.children,
          subCategoryId:data.categoryId
        })
      }
  },
 /**
   * 选择定位后更新列表
   */
  go_update() {
    this.get_neighborShop()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.resetData()
    // if (getApp().globalData.categoryId) {
    //   let categoryId = getApp().globalData.categoryId
    //   let index = getApp().globalData.index
    //   let pic = getApp().globalData.pic

    //   this.setData({
    //     categoryImg: pic,
    //     selIndex: index
    //   });
    // }else{
    // this.get_neighborShop()
    // }
    this.get_neighborShop()

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

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

  },

  /**
   * 分类点击事件，获取子分类
   */
  onMenuTab: function (e) {
    var id = e.currentTarget.dataset.id;
    var index = e.currentTarget.dataset.index;
    this.setData({
      categoryImg: this.data.categoryList[index].pic,
      subCategoryList:this.data.categoryList[index].children,
      selIndex: index,
      selCategory:id,
      productList:[],
      subIndex:0,
      paramsObj:{sort:0,orderBy:0},
      sort:0

    });
    // this.getProdList(this.data.subCategoryList[0].categoryId)
    this.getData(this.data.subCategoryList[0])
    getApp().globalData.categoryId = ''
    getApp().globalData.index = ''
    getApp().globalData.pic = ''
  },
  /**
   * 推荐词,type:1关键词,2热门搜索词，3推荐搜索词
   */
  getRecommended: function () {
    var params = {
      url: "/keyword/list",
      method: "GET",
      data: {
        type: 2
      },
      callBack: (res) => {
        let reslut = res.filter(item => item.status !== 2) //过滤下线词
        let timeReslut = reslut.filter(e => util.dateToTimestamp(e.effectiveTime) < new Date().getTime()) //过滤未生效词
        this.setData({
          hotList: timeReslut
        })
      }
    };
    http.request(params);
  },

  /**
   * 推荐词搜索
   */
  topSwiperChange: function (e) {
    this.setData({
      topCurrentIndex: e.detail.current // 获取当前滚动到的swiper-item的索引并更新到data中
    })
  },
  topHotSearch: function () {
    const topname = this.data.hotList[this.data.topCurrentIndex].name
    wx.navigateTo({
      url: `/pages/search-prod-show/search-prod-show?prodName=${topname}&shopId=${this.data.shopId}`,
    })
  },

  // 跳转搜索页
  toSearchPage: function () {
    wx.navigateTo({
      url: `/pages/search-page/search-page?shopId=${this.data.shopId}`,
    })
  },
  /**
   * 跳转到定位页面
   */
  toLocationPage: function () {
    wx.navigateTo({
      url: '/pages/locationAdd/locationAdd',
    })
  },
  // 点击二级分类
  onleftMenuTab(e){
    const {
      index,
      id
    } = e.currentTarget.dataset
    if(id){
      this.setData({
        type:'click'
      })
      console.log('click');
    }
    this.setData({
      subIndex:index,
      paramsObj:{sort:0,orderBy:0},
      sort:0
    })
    // this.getProdList(this.data.subCategoryList[index].categoryId)
    this.getData(this.data.subCategoryList[index])

  },

  // 根据分类id获取商品数据
  getProdList(categoryId) {
    var params = {
      url: "/search/searchProdPage",
      method: "GET",
      data: {
        categoryId,
        current: 1,
        size: 999999,
        orderBy:this.data.paramsObj.orderBy,
        sort:this.data.paramsObj.sort,
        isAllProdType: true,
        // lat: wx.getStorageSync('LATITUDE'),
        // lon: wx.getStorageSync('LONGITUDE'),
        // distance: wx.getStorageSync('DISTANCE') || 0
      },
      callBack: (res) => {
      console.log(res);
      let productList = res.records
      let img = ''
      productList.map(e => {
        img = e.pic.split(',')
        e.pic = img[0]
      })
        this.setData({
          productList,
          topHeight:15
        })
        if(productList.length == 0){
          if(this.data.type == 'top'){
            this.scrollTop()
          }else{
            this.scrollBottom()
          }
        }
        this.addParmasProduct()
      }
    };
    http.request(params);
  },
  // 根据分类id获取所有三级商品数据
  getAllProList(categoryId) {
    var params = {
      url: "/prod/listProdByCategoryIdAndShopId",
      method: "post",
      data: {
        orderBy:this.data.paramsObj.orderBy,
        sort:this.data.paramsObj.sort,
        categoryId,
        current: 1,
        size: 999999,
        shopId:this.data.testShopId||this.data.shopId
      },
      callBack: (res) => {
      let productList = res.records
      let img = ''
      productList.map(e => {
        img = e.pic.split(',')
        e.pic = img[0]
      })
        this.setData({
          productList,
          topHeight:15
        })
        if(productList.length == 0){
          if(this.data.type == 'top'){
            this.scrollTop()
          }else if(this.data.type == 'bottom'){
            this.scrollBottom()
          }
        }
        this.addParmasProduct()

      }
    };
    http.request(params);
  },
  // 点击三级分类
  handleThrid(e){
    let {
      index,
      categoryid
    } = e.currentTarget.dataset
    console.log(33333333333,e.currentTarget.dataset);
    this.setData({
      thridIndex:index
    })
    if(index == -1){
      categoryid = this.data.subCategoryId
    }
    this.getAllProList(categoryid)
  },
  // 除了产品列表数据 给产品列表添加显示和数量  同步购物车数据
  addParmasProduct(){
    if(this.data.productList.length >0){
      let productList = JSON.parse(JSON.stringify( this.data.productList))
      productList.map(i=>{
        i.show = false
        this.data.carData.map(item=>{
          if(item.prodId == i.prodId){
            i.prodCount = item.prodCount
            i.show = true
          }
        })
      })
      this.setData({
        productList
      })
    }
  },
  // 获取购物车数据
  getCarData() {
    var params = {
      url: "/p/shopCart/info",
      method: "post",
      data: [{
        "basketId": 0,
        "discountId": 0,
        "shopId":this.data.testShopId||this.data.shopId
      }],
      callBack: (res) => {
        if(res.length){
          let carData = res[0].shopCartItemDiscounts[0].shopCartItems
          let img = ''
          carData.map(e => {
            img = e.pic.split(',')
            e.pic = img[0]
          })
          this.setData({
            carData
          },()=>{
           
            this.getCarTotal()
          })
          


      }else{
        this.setData({
          carData:[]
        },()=>{
          this.getCarTotal()
        })
      }
      // 给产品列表添加显示和数量  同步购物车数据
      this.addParmasProduct()
      }
    };
    http.request(params);
  },

  // 获取购物车数量和总价
  getCarTotal() {
    let basketIds = this.data.carData.map(item=>{
      return  item.basketId
       
    })
    var params = {
      url: "/p/shopCart/totalPay?t="+new Date().getTime(),
      method: "post",
      data: basketIds,
      callBack: (res) => {
       this.setData({
         totalInfo:res
       })
      }
    };
    http.request(params);
  },
  // 添加修改购物车数量
  changeCar(data) {
    var params = {
      url: "/p/shopCart/changeItem?t="+new Date().getTime(),
      method: "post",
      data,
      callBack: (res) => {
        this.getCarData()
      }
    };
    http.request(params);
  },
   /**
   * 跳转到商品详情页
   */
  toProdPage: function (e) {
    var prodid = e.currentTarget.dataset.prodid;
    console.log(22222222,e);
    if (prodid) {
      wx.navigateTo({
        url: '/pages/prod/prod?prodid=' + prodid,
      })
    }
  },

  handleBuy(){
    if(this.data.carData.length == 0){
      return 
    }
    let basketIds = this.data.carData.map(item=>{
      return item.basketId
    })
    wx.setStorageSync("basketIds", JSON.stringify(basketIds));
    wx.navigateTo({
      url: '/pages/submit-order/submit-order?orderEntry=0',
    })
  }

})