﻿var WxParse = null;
//获取应用实例
var app = getApp()
var sopenFrame=null;
var sopenFrame0=null;
var sopenFrame1=null;
var that=null;
Page({
    data: {
        indicatorDots: true,
        indicatorDots0: true,
        vertical: false,
        vertical0: false,
        autoplay: true,
        interval: 6000,  
        interval0: 8000, 
        duration: 1000,
        loadingHidden: false,  // loading
        images:[],
        images1:[],
        Products:[],
        Products0:[],
        ifxn:0
    },

    //事件处理函数
    swiperchange: function(e) {
        //console.log(e.detail.current)
    },

    //事件处理函数
    swiperchange0: function(e) {
        //console.log(e.detail.current)
    },onShow: function () {
      if (typeof this.getTabBar === 'function' && this.getTabBar()) {
        this.getTabBar().setData({
          selected: 2
        })
      }
    },
    
    onLoad: function(options) {
        
        that=this;
        WxParse = require('../../wxParse/wxParse.js');
        
        // ============================================
        // 【测试数据配置区域 - 开始】
        // 用途：用于本地测试swiper组件渲染效果
        // 使用方法：将 useTestData 设为 true 启用测试数据，设为 false 恢复正式数据
        // 注意：测试完成后请将 useTestData 设为 false 或删除测试代码块
        // ============================================
        var useTestData = false;  // 切换开关：true=使用测试数据，false=使用后端数据
        
        if (useTestData) {
            // 虚拟测试数据 - 用于验证swiper组件渲染效果
            var testData = {
                ifxn: 1,  // 控制wx:if条件显示
                indicatorDots0: true,  // 显示指示点
                vertical0: false,  // 水平轮播
                autoplay: true,  // 自动播放
                interval0: 3000,  // 轮播间隔3秒
                duration: 500,  // 动画时长0.5秒
                loadingHidden: true,  // 隐藏loading
                // images1数组：包含3个swiper-item，每个item包含4个cell
                images1: [
                    {
                        datas: [
                            { id: '1', label: '手机数码', img: 'https://picsum.photos/200/200?random=1' },
                            { id: '2', label: '电脑办公', img: 'https://picsum.photos/200/200?random=2' },
                            { id: '3', label: '家用电器', img: 'https://picsum.photos/200/200?random=3' },
                            { id: '4', label: '服饰鞋包', img: 'https://picsum.photos/200/200?random=4' }
                        ]
                    },
                    // {
                    //     datas: [
                    //         { id: '5', label: '美妆护肤', img: 'https://picsum.photos/200/200?random=5' },
                    //         { id: '6', label: '食品生鲜', img: 'https://picsum.photos/200/200?random=6' },
                    //         { id: '7', label: '家居家装', img: 'https://picsum.photos/200/200?random=7' },
                    //         { id: '8', label: '运动户外', img: 'https://picsum.photos/200/200?random=8' }
                    //     ]
                    // },
                    // {
                    //     datas: [
                    //         { id: '9', label: '图书音像', img: 'https://picsum.photos/200/200?random=9' },
                    //         { id: '10', label: '母婴用品', img: 'https://picsum.photos/200/200?random=10' },
                    //         { id: '11', label: '汽车用品', img: 'https://picsum.photos/200/200?random=11' },
                    //         { id: '12', label: '玩具乐器', img: 'https://picsum.photos/200/200?random=12' }
                    //     ]
                    // }
                ],
                // 其他必要数据
                images: [
                    { url: '1', img: 'https://picsum.photos/750/300?random=101' },
                    { url: '2', img: 'https://picsum.photos/750/300?random=102' },
                    { url: '3', img: 'https://picsum.photos/750/300?random=103' }
                ],
                Products: [],
                Products0: []
            };
            
            that.setData(testData);
            console.log('【测试模式】已加载虚拟测试数据');
            // 测试数据模式下不调用后端接口，防止数据被覆盖
            return;
        }
        // ============================================
        // 【测试数据配置区域 - 结束】
        // ============================================
        
        /*var shopdata = wx.getStorageSync('shopdata') 
        if(shopdata){
              var resshopdata=JSON.parse(shopdata);
              that.setData({
                images: resshopdata.pic,
                images1: resshopdata.pic1,
                Products:resshopdata.products,
                Products0:resshopdata.Products0,
                loadingHidden:true
            })
           
         }*/
     
               that.rdata(0);  
       
       
        sopenFrame=setInterval(function (){
          if(app.globalData.IFRefreshshop==1){
              app.globalData.IFRefreshshop=0;
              that.setData({
                Start: 0
             }); 
              that.rdata(0);
          }
       }, 1000);
    },onPullDownRefresh: function () {
        //在当前页面显示导航条加载动画  
         wx.showNavigationBarLoading(); 
        //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
        wx.showLoading({
            title: '刷新中...',
           
        })
        
        that.setData({
          Start: 0
       }); 
        wx.removeStorageSync('selcityid')
        wx.removeStorageSync('selcountyid')
        wx.removeStorageSync('dlMemberId')
        
               that.rdata(1);   
        
    },// 页面上拉触底事件（上拉加载更多）
     

// 清缓存
clearCache:function(){
  that.setData({
     loadingHidden:false
  }); 
},rdata:function(t) {
       
           try{
             var userId = wx.getStorageSync("userId")
             var LoginId = wx.getStorageSync("LoginId")
             var selcityid = wx.getStorageSync("selcityid")
             var selcountyid = wx.getStorageSync("selcountyid")
             var dlMemberId = wx.getStorageSync("dlMemberId")
            
               wx.request({
                 url: app.globalData.apiurl + "/xapiajax.ashx", 
                 
                 data: {
                   action:"getshopdata", 
                    userId:(!userId?"":userId),
                    LoginId:(!LoginId?"":LoginId),
                    Start:that.data.Start,
                    cid:that.data.cid,
                    selcityid:(!selcityid?"":selcityid),
                    selcountyid:(!selcountyid?"":selcountyid),
                    dlMemberId:(!dlMemberId?"":dlMemberId),
                 },  
                 method:"GET", 
                 dataType:"json",   
                 header: { 
                   "content-type": "application/json" // 默认值
                 },
                 success (res) {   
                  
                   if(res.data.status==1){
                        wx.setStorageSync('shopdata', JSON.stringify(res.data))
                        
                        // 转换 pic1 数据格式：将扁平数组包装为包含 datas 的嵌套结构
                        var pic1Data = res.data.pic1 || []
                        var formattedImages1 = []
                        if (pic1Data.length > 0) {
                            // 每8个一组进行分组（双行显示，每行4个分类）
                            var groupSize = 8
                            for (var i = 0; i < pic1Data.length; i += groupSize) {
                                formattedImages1.push({
                                    datas: pic1Data.slice(i, i + groupSize)
                                })
                            }
                        }
                        
                        that.setData({
                           images: res.data.pic || [],
                           images1: formattedImages1,
                           Products:res.data.products || [],
                           Products0:res.data.products0 || [],
                           loadingHidden:true
                       })
                       if(res.data.ifxn==1){
                        that.setData({
                          ifxn:1
                        })
                       }
                      //  if(res.data.userInfo && res.data.userInfo.ifxn==0){
                      //   that.setData({
                      //     ifxn:1
                      //   })
                      //  }
                        //  that.setData({
                        //   ifxn:1
                        // })
                       if(t==1){
                            //隐藏loading 提示框
                            wx.hideLoading();
                            //隐藏导航条加载动画
                            wx.hideNavigationBarLoading();
                            //停止下拉刷新
                            wx.stopPullDownRefresh();
                       }
                      
                   }else{
                        if(res.data.msg=="您未登录"||res.data.msg=="参数错误"){
                            wx.removeStorageSync('userId')
                            wx.removeStorageSync('LoginId')
                            that.rdata(0) 
                        }
                   }
                 }
               }) 
             }catch(err){
               wx.showToast({
                 title: err,
                 icon: "none",
                 duration: 2000
               })
             }
    },gotodetail:function(e) {
      
          var id = e.currentTarget.dataset.id
          wx.navigateTo({  
              url: "../details/index?id="+id
          })
    
    },
    onshop: function (e) { 
      var id = e.currentTarget.dataset.id
    
            wx.navigateTo({  
                url: "../othershop/index?t=" + id
            })
       
      
    },onnav: function (e) {
          var id = e.currentTarget.dataset.id
         
          wx.navigateTo({  
            url: "../list/index?t=0&id=" + id
        })
   
          
    },getkeyword:function(e) {
      that.setData({
          keyword:e.detail.value
      })
    },onsearch:function() {
      var keyword=that.data.keyword.replace(/\s+/g, "");
      if(keyword!=""){
         wx.navigateTo({  
             url: "../list/index?keyword=" + keyword 
          }) 
      }else{
        wx.showToast({
          title: "关键字不能为空",
          icon: "none", 
          duration: 3000 
         })
      }
    },onpd:function(e) {
        var ids = e.currentTarget.dataset.id
        wx.navigateTo({  
          url: "../details/index?"+ids
      })
    },onyjpt:function(e) {
        var id = e.currentTarget.dataset.id
        var userId = wx.getStorageSync("userId")
        var LoginId = wx.getStorageSync("LoginId")
        if(userId&&LoginId){
          if(that.data.IFAuto==1){
          if(that.data.button_title=="一键拼团"){
          that.setData({
            button_title: "请稍候..."
          })
        wx.request({
          url: app.globalData.apiurl + "/xapiajax.ashx", 
          data: { 
            action:"ononekey",
             userId:(!userId?"":userId),
             LoginId:(!LoginId?"":LoginId),
             id:id,
             t:1
          },
          method:"GET",
          dataType:"json", 
          header: { 
            "content-type": "application/json" // 默认值
          },
          success (res) { 
            that.setData({
              button_title: "一键拼团"
            })
              if(res.data.status==1){
                  wx.showToast({
                    title: "已下单成功",
                    icon: "success",
                    duration: 2000
                  })
                  that.setData({
                       IFAuto:2
                   })
                   that.setData({ 
                    Start: 0
                }); 
                that.getlist(0);
               
              }else{
                 wx.showToast({
                    title: res.data.msg,
                    icon: "none",
                    duration: 2000
                  })
              }
              
          }
        })
      }
      }else{
        if(that.data.IFAuto==0){
        wx.navigateTo({  
            url: "../vip/index"
        })   
       }
      }
    }else{
        wx.navigateTo({  
            url: "../login/index"
        })   
     }
    },catchbutton:function(e) {
      
    },onautopt:function(e) {
    
    }
})
