import{url} from '../request'
Page({
  data: {
    lie: [
      { id: 1, name: '推荐款式', showLine: true },
      { id: 2, name: '中长款', showLine: false },
      { id: 3, name: '本甲款', showLine: false },
      { id: 4, name: '长款', showLine: false },
      { id: 5, name: '短款', showLine: false },
    ],
    names:[
      { id:1, hengname:'款式分类',line:true},
      {id:2,hengname:'评价',line:false},
      {id:3,hengname:'商家',line:false},
    ],
    userId: '',
    address: '',
    businessName:'',
    businessAvatar:'',
    startBusiness:'',
    endBusiness:'',
    storeStatus:'',
    businessId: '',
    commoditiesGroupId: 0,
    commoditiesName: "",
    current: 0,
    pageSize: 0,
    sortField: "",
    sortOrder: "",
    status: "",
    tuijian:[],
    meijiashi:[],
    email: "",
		gender: 0,
	  manicuristAvatar: "",
		manicuristName: "",
		phone: "",
		rating: 0,
		specialties: "",
    id:'',
    filteredShopping: [],
    showShoppingCart: true,  // 控制购物车部分是否显示
    showComments: false,      // 控制评论部分是否显示
    showBusinessInfo: false, // 控制商家信息是否显示
    pingjia:[],
    level:'',
  },

  callPhone() {
    my.makePhoneCall({
      number: this.data.businessPhone,
      success: function(res) {
        console.log(res);  //{"success": true}
      },
      fail: function(err) {
        console.log(err);
      }
    });
  },
  number(){
    const randomLevel = Math.floor(Math.random() * 5) + 1; 
    this.setData({
      level: randomLevel,
    });
  
    console.log("随机生成的 level 值是：", randomLevel);
  },
  onLoad(options) {
    this.number();
    // Extract userId and address from options
    const userId = options.userId;
    const address = options.address;
    const businessName = options.businessName;
    const businessAvatar = options.businessAvatar;
    const startBusiness = options.startBusiness;
    const endBusiness = options.endBusiness;
    const storeStatus = options.storeStatus;
    const id = options.id
    const businessPhone = options.businessPhone
    
    console.log(id,storeStatus,'这是店铺id吗');
    // Set them in data for use in the page
    this.setData({
      userId: userId,
      address: address,
      businessName:businessName,
      businessAvatar:businessAvatar,
      endBusiness:endBusiness,
      startBusiness:startBusiness,
      storeStatus:storeStatus,
      id:id,
      businessPhone:businessPhone,
    });
    my.request({
      url: url + '/api/commodities/list/page/commodities',
      method: 'POST',
      data: {
      businessId: id,
      commoditiesGroupId: "",
      commoditiesName: "",
      current: 0,
      pageSize: 100,
      sortField: "",
      sortOrder: "",
      status: "",
      },
      headers: {
        'content-type': 'application/json',
      },
      dataType: 'json',
      success: (res) => {
        console.log(id,'这是onload');
        console.log('Request succeeded:', res);
        if (res.data && res.data.data) {
          this.setData({
            tuijian: res.data.data.records, // 更新 tuijian 列表
          });
          this.chushihua();
          console.log(this.data.tuijian,'这是推荐');
        } else {
          console.log('shibaile')
        }
      },
      fail: (error) => {
        console.error('Request failed', error);
      }
    });
    this.pingjia()
  },
  soucang() {
    my.getStorage({
      key: 'userInfo',
      success: (res) => {
        const userInfo = res.data;
        const businessId = this.data.id; // 获取 onLoad 中保存的 id

        if (userInfo && userInfo.cookie) {
          my.request({
            url: url + '/api/collect/add',
            method: 'POST',
            data: {
              businessId: businessId, // 使用 businessId 来请求收藏
              userId: userInfo.id
            },
            headers: {
              'content-type': 'application/json',
              'Cookie': userInfo.cookie,
            },
            dataType: 'json',
            success: (res) => {
              console.log(res);
              if(res.data.code===0){
                my.alert({
                  content: '收藏成功'
                });
              }
              else if(res.data.code===40100){
                my.alert({
                  content: '登录信息已过期，请重新登录'
                });
                my.navigateTo({
                  url:'/pages/denglu/denglu'
                })
              }else{
                my.alert({
                  content: '店铺已收藏'
                });
              }
            },
            fail: (error) => {
              console.error('请求失败: ', JSON.stringify(error));
              my.alert({ content: '请求失败，请稍后重试' });
            },
          });
        } else {
          my.alert({
            content: '您未登录，请先登录。',
            success: () => {
              my.navigateTo({
                url: '/pages/denglu/denglu',
              });
            },
          });
        }
      },
    });
  },
  pingjia(){
    my.request({
      url: url + '/api/level/listBusinessRating',
      method: 'GET',
      data: {
        businessId:this.data.id,
      },
      headers: {
        'content-type': 'application/json',
      },
      dataType: 'json',
      success: (res) => {
        console.log(res,'评价部分');
        if(res.data.code===0){
          this.setData({
            pingjia:res.data.data,
            useridpingjia:res.data.data.userId
          })
        
        }
        console.log(this.data.pingjia);
      },
      fail: (error) => {
        console.error('请求失败: ', JSON.stringify(error));
        my.alert({ content: '请求失败，请稍后重试' });
      },
    });
  },
  zixun(){
    my.navigateTo({
      url:'/pages/zixunmeijiashi/zixunmeijiashi'
    })
  },
  // 点击事件处理函数
selectItem(e) {
  const id = e.currentTarget.dataset.id;
  console.log(id);
  // 更新对应的 showLine 状态，控制是否显示线条
  const updatedLie = this.data.lie.map(item => {
    if (item.id === id) {
      item.showLine = !item.showLine;  // 切换显示状态
    } else {
      item.showLine = false; // 其他项隐藏
    }
    return item;
  });

  // 根据点击的类别 id 筛选对应的商品
  const filteredShopping = this.data.tuijian.filter(item => String(item.commoditiesGroupId) === String(id));

  // 更新数据
  this.setData({
    lie: updatedLie,
    filteredShopping,  // 更新右侧商品列表
    showShoppingCart: true,  // 显示购物车部分
    showComments: false,     // 隐藏评论部分
    showBusinessInfo: false, // 隐藏商家信息部分
  });
  console.log(this.data.filteredShopping,'hhhhhhhhhhhhhh');
},
chushihua(){
  this.setData({
    filteredShopping: this.data.tuijian.filter(item => String(item.commoditiesGroupId) === "1"), // 默认选中类别 1
  })
  console.log(this.data.filteredShopping,'chushi');
},
chaxunzhuangtai(e) {
  const id = e.currentTarget.dataset.id;
  console.log(id);

  // 更新对应的 line 状态，控制是否显示线条
  const updatednames = this.data.names.map(item => {
    if (item.id === id) {
      item.line = !item.line;  // 切换显示状态
    } else {
      item.line = false; // 其他项隐藏
    }
    return item;
  });

  this.setData({
    names: updatednames,
  });

  // 根据点击的分类切换显示内容
  if (id === 1) {
    this.setData({
      showShoppingCart: true,  // 显示购物车
      showComments: false,     // 隐藏评论
      showBusinessInfo: false, // 隐藏商家信息
    });
  } else if (id === 2) {
    this.setData({
      showShoppingCart: false,  // 隐藏购物车
      showComments: true,      // 显示评论
      showBusinessInfo: false, // 隐藏商家信息
    });
  } else if (id === 3) {
    this.setData({
      showShoppingCart: false,  // 隐藏购物车
      showComments: false,      // 隐藏评论
      showBusinessInfo: true,   // 显示商家信息
    });
  }
},
jiaru(item) {
      const id = item.target.dataset.num
      console.log('传递的数据:', id); 
      const ids = id.id
      const businessId = id.businessId 
      const selectedOptions = '到店服务'
  my.getStorage({
    key: 'userInfo',
    success: (res) => {
        const userInfo = res.data;
        console.log(userInfo);
        if (userInfo && userInfo.cookie) {
          my.request({
            url: url + '/api/cart/add',
            method: 'POST',
            data: {
              businessId: businessId,
              commoditiesId: ids,
              quantity: 1,
              selectedOptions: selectedOptions,
              userId: userInfo.id
            },
            headers: {
              'content-type': 'application/json',
              'Cookie': userInfo.cookie, // 通过头部传递 cookie
            },
            dataType: 'json',
            success: (res) => {
              if(res.data.code===0){
                console.log(res);
                my.alert({ content: '成功添加到购物车' });
              }
              else if(res.data.code===40100){
                my.alert({
                  content: '登录信息已过期，请重新登录'
                });
                my.navigateTo({
                  url:'/pages/denglu/denglu'
                })
            }else{
              console.log(res,'shibaile');
            }
            },
            fail: (error) => {
              console.error('请求失败: ', JSON.stringify(error));
              my.alert({ content: '请求失败，请稍后重试' });
            },
          });
        } else {
            my.alert({
                content: '您未登录，请先登录。',
                success: () => {
                    my.navigateTo({
                        url: '/pages/denglu/denglu',
                    });
                },
            });
        }
    },
});
},
shangpinjiemian(item){
  const id = item.target.dataset.num
  console.log('传递的数据:', id); 
    const ids = id.id
    const commoditiesPrice = id.commoditiesPrice
    const commoditiesName = id.commoditiesName
    const commoditiesImage = id.commoditiesImage
    const businessId = id.businessId
    const dianpuid = this.data.id
    const businessName =this.data.businessName
    console.log('Address being passed: ',id,commoditiesPrice,commoditiesName,commoditiesImage,businessId); 
  my.navigateTo({
    url:`/pages/shangpinjiemian/shangpinjiemian?commoditiesPrice=${commoditiesPrice}&&commoditiesName=${commoditiesName}&&commoditiesImage=${commoditiesImage}&&ids=${ids}&&businessId=${businessId}&&dianpuid=${dianpuid}&&businessName=${businessName}`
  })
  console.log(ids,businessId,commoditiesImage,commoditiesName,commoditiesPrice+'这是商品的',dianpuid+'这是店铺的')
},
kefu(){
  my.navigateTo({
    url:'/pages/zixunmeijiashi/zixunmeijiashi'
  })
}
});