// 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: {
    showTabbar:true,
    showLoading:false,
    rightView:'',
    paramsObj:{
      sort:0,
      orderBy:0
    },
    type:'bottom',
    toViewId:'test1',
    topHeight:300,
    sort:0,
    imgUrl:'',
    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:[],//购物车数据
    animateInfo:{
      startX:99999,
      startY:0,
      endX:0,
      endY:0,
    },
    move:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  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||this.data.productList.length == 0) return
    this.setData({
      type:'top'
    })
    let data = {currentTarget:{
      dataset:{
        index:this.data.subIndex-1
      }
    }}
    this.onleftMenuTab(data)
    // this.setData({
    //   topHeight:0
    // })
  },
  scrollBottom(){
    // this.data.productList 新增判断  避免为空自动滚动
    if(this.data.subIndex==(this.data.subCategoryList.length-1)||this.data.subCategoryList.length==0||this.data.productList.length == 0) return
    this.setData({
      type:'bottom'
    })
    let data = {currentTarget:{
      dataset:{
        index:this.data.subIndex+1
      }
    }}
    
    this.setData({
      topHeight:15
    },() => {
      // 3. 延迟恢复样式（避免视觉闪烁）
      setTimeout(() => {
        this.onleftMenuTab(data)
      }, 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){
    // 查看是否授权
    util.checkAuthInfo(()=>{
      let {num,item,type,index} = e.currentTarget.dataset
      let data = {
        "basketId": item.basketId||0,
        "count": num,
        "distributionCardNo": item.distributionCardNo||'',
        "prodId": item.prodId,
        "shopId": item.shopId,
        "skuId": item.skuId||item.skuList[0].skuId,
        platform:1
      }
      this.changeCar(data)
      if(type == 'add'){
        this.addAnimate(e)
      }
    })
  },
  addAnimate(e){
    let startX = e.touches[0].clientX-10
    let startY = e.touches[0].clientY-10
    const query = wx.createSelectorQuery().in(this);
    query.select('.bottom-box .left .icon').boundingClientRect(cartRect => {
      console.log(222222,cartRect);
      if (!cartRect) return;
      let animateInfo = {
        startX,
        startY,
        endX:cartRect.left,
        endY:cartRect.bottom,
      }
      this.setData({
        move:true,
        animateInfo
      })
      console.log(animateInfo);
    }).exec();

   
  
  },
  endAnimate(){
    console.log('ddddd');
    let animateInfo = {
      startX:9999,
      startY:0,
      endX:0,
      endY:0,
    }
    this.setData({
      move:false,
      animateInfo
    })
  },

  // 获取点击位置和购物车位置
  getNodePositions(index) {
    const query = wx.createSelectorQuery().in(this);

    // 1. 获取"加入购物车"按钮的位置（动画起始点）
    query.select(`.product-item:nth-child(${index + 1}) .info .price-box .test`).boundingClientRect(btnRect => {
      if (!btnRect) return; // 容错：防止节点未找到
      const startX = btnRect.left + btnRect.width / 2 - 20; // 20 = 40rpx/2（图标宽高）
      const startY = btnRect.top + btnRect.height / 2 - 20;

      // 2. 获取购物车位置（动画结束点）
      query.select('.bottom-box .left .icon').boundingClientRect(cartRect => {
        if (!cartRect) return;
        const endX = cartRect.left + cartRect.width / 2 - 20;
        const endY = cartRect.top + cartRect.height / 2 - 20;

        // 3. 计算抛物线中间点（控制弧度）
        const midX = (startX + endX) / 2;
        const midY = startY - 80; // 向上凸起80px，可调整弧度

        // 4. 创建动画图标
        this.createAnimationIcon(startX, startY, midX, midY, endX, endY);
      }).exec();
    }).exec();
  },

  // 创建抛物线动画（数据驱动，无DOM操作）
  createAnimationIcon(startX, startY, midX, midY, endX, endY) {
    // 生成唯一ID，避免key冲突
    const iconId = Date.now() + Math.floor(Math.random() * 1000);
    const newIcon = {
      id: iconId,
      startX,
      startY,
      midX,
      midY,
      endX,
      endY
    };

    // 添加动画图标到数组（自动渲染）
    this.setData({
      animationIcons: [...this.data.animationIcons, newIcon]
    });

    // 动画结束后移除图标+更新购物车
    setTimeout(() => {
      this.setData({
        animationIcons: this.data.animationIcons.filter(icon => icon.id !== iconId),
      });
    }, 700); // 与动画时长保持一致（0.7s）
  },
  
  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'),
        platform:1
      },
      callBack: (res) => {
        // this.get_categoryInfo(res)
        wx.setStorageSync('shopInfo', 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
        });
        let categoryId =wx.getStorageSync('categoryId')
        if(categoryId){

          that.data.categoryList.map((item,index)=>{
            if(item.categoryId == categoryId){
                that.setData({
                  selCategory:categoryId,
                  selIndex:index,
                  subCategoryList:res[index].children
                })
              }
          })
          wx.removeStorageSync('categoryId')
        }
        // eventBus.on('categoryId', (data) => {
        //   eventBus.clear()
        //   that.data.categoryList.map((item,index)=>{
        //     if(item.categoryId == data){
        //         that.setData({
        //           selCategory:data,
        //           selIndex:index,
        //           subCategoryList:res[index].children
        //         })
        //       }
        //   })
        // });
        ths.getData(ths.data.subCategoryList[0])
   
      }
    };
    http.request(params);
  },
  getData(data){
    console.log(data);
    if(!data){
     return this.setData({
        thridCategoryList:[],
        showLoading:false
      })
    }
      this.setData({
        thridCategoryList:[],
        showLoading:true
      })
      // 二级分类有商品
      if(data.productBeBound == 1){
        this.getAllProList(data.categoryId)
        // 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 () {
    console.log('show');
    if(this.data.shopId){
      this.getCarData(this.data.shopId)
    }
    // 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.resetData()
    // 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;
    // if(this.data.categoryList[index].children.length == 0){
    //   return
    // }
    this.setData({
      show:false,
      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,
        channelId:wx.getStorageSync('channelId'),
        platform:1
        // lat: wx.getStorageSync('LATITUDE'),
        // lon: wx.getStorageSync('LONGITUDE'),
        // distance: wx.getStorageSync('DISTANCE') || 0
      },
      callBack: (res) => {
        setTimeout(() => {
          this.setData({
            showLoading:false
          })
        }, 500);
      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,
        channelId:wx.getStorageSync('channelId'),
        shopId:this.data.testShopId||this.data.shopId
      },
      callBack: (res) => {
        setTimeout(() => {
          this.setData({
            showLoading:false
          })
        }, 500);
      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/1",
      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);
    http.getCartCount(); //重新计算购物车总数量
  },
  // 添加修改购物车数量
  changeCar(data) {
    var params = {
      url: "/p/shopCart/changeItem?t="+new Date().getTime(),
      method: "post",
      data,
      callBack: (res) => {
        if(res.code == 500){
          wx.showToast({
            title: res.msg,
            icon:'none'
          })
        }else{
          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&shopId='+this.data.carData[0].shopId,
    })
  }

})