import { url } from '../request';
Page({
  data: {
      current: 0,
      businessName:'',
      items: [
          {
              title: '全部',
          },
          {
              title: '待支付',
          },
          {
              title: '待使用',
          },
          {
            title: '已完成',
          },
          {
            title: '已取消',
          },
          {
            title: '已退款',
          },
      ],
      dingdan:[],
      paymentStatuses: [
        { paymentStatuses: '0', statue: '待支付' },
        { paymentStatuses: '1', statue: '待使用' },
        { paymentStatuses: '2', statue: '已取消' },
        { paymentStatuses: '3', statue: '已退款' },
        { paymentStatuses: '4', statue: '已完成' }
      ]

  },
  onShow() {
    my.getStorage({
        key: 'userInfo',
        success: (res) => {
            const userInfo = res.data;
            this.setData({ id: userInfo.id });

            if (userInfo) {
                my.request({
                    url: url + '/api/orders/my/page',
                    method: 'POST',
                    data: {
                        claimStatus: 0,
                        current: 1,
                        pageSize: 1000,
                        userId: userInfo.id,
                        userRole: 0,
                    },
                    headers: { 'content-type': 'application/json' },
                    dataType: 'json',
                    success: async (res) => {
                      console.log(res,'rwssss');
                        if (res.data.code === 0) {
                            // 生成包含 appointmentId 的订单列表
                            let orders = res.data.data.records.map(order => ({
                                id:order.id,
                                businessAvatar:order.businessVO.businessAvatar,
                                serviceMode: order.serviceMode,
                                businessName: order.businessVO.businessName || '未知店铺',
                                commoditiesImage: order.orderItemsVOList[0].commoditiesVO.commoditiesImage || '',
                                commoditiesName: order.orderItemsVOList[0].commoditiesVO.commoditiesName || '未知商品',
                                orderNumber: order.orderNumber,
                                totalPrice: order.totalPrice,
                                paymentStatus: order.paymentStatus,
                                status: '', 
                                appointmentId: order.appointmentId,
                                phone:order.phone,
                                username:order.userName,
                                businessId:order.businessVO.id,
                                quantity:order.orderItemsVOList.quantity,
                                createTime:order.createTime
                            }));

                            this.setData({ dingdan: orders }); // 初始化订单列表

                            // 提取所有 appointmentId 并获取详情
                            const appointmentIds = res.data.data.records.map(order => order.appointmentId);
                            appointmentIds.forEach(id => {
                                this.fetchOrderDetail(id); // 逐个请求状态
                            });

                        } else if (res.data.code === 40100) {
                            my.alert({ content: '登录信息已过期，请重新登录' });
                            my.navigateTo({ url: '/pages/denglu/denglu' });
                        }
                    },
                    fail: (error) => {
                        console.error('请求失败: ', JSON.stringify(error));
                        my.alert({ content: '请求失败，请稍后重试' });
                    },
                });
            } else {
                my.alert({
                    content: '您未登录，请先登录。',
                    success: () => my.navigateTo({ url: '/pages/denglu/denglu' }),
                });
            }
        },
    });
},

fetchOrderDetail(appointmentId) {
  my.request({
    url: url + '/api/appointments/getAppointments',
    method: 'GET',
    data: { appointmentsId: appointmentId }, // 使用正确的参数名
    headers: { 'content-type': 'application/json' },
    dataType: 'json',
    success: (res) => {
      if (res.data.code === 0) {
        const status = res.data.data.status; // 根据实际接口返回调整
        // 更新对应订单的 status
        const updatedDingdan = this.data.dingdan.map(order => {
          return order.appointmentId === appointmentId 
            ? { ...order, status: status } 
            : order;
        });
        this.setData({ dingdan: updatedDingdan });
        console.log(this.data.dingdan);
      }
    },
    fail: (error) => {
      console.error(`订单 ${appointmentId} 请求失败:`, JSON.stringify(error));
    }
  });
},
  onSwipeChange(e) {
      this.setData({
          current: e.detail.current,
      });
  },
  onChange(current) {
      this.setData({
          current,
      });
  },
handleChange(current) {
    this.setData({
        current,
    });
},
onPlus() {
    this.alert('plus');
},
alert(content) {
    my.alert({
        title: content,
    });
},
getPaymentStatusText(status) {
  const statusObj = this.paymentStatuses.find(item => item.paymentStatuses === status.toString());
  return statusObj ? statusObj.statue : '未知状态'; // 如果找不到对应状态，返回 '未知状态'
},
quxiao(item){
  const id = item.target.dataset.num
  console.log(id);
  const orderId = id.id
  console.log(orderId,'zheshiorderid');
  my.getStorage({
    key: 'userInfo',
    success: (res) => {
      const userInfo = res.data;
      this.setData({
        id: userInfo.id, // 获取 id
      });

      if (userInfo && userInfo.cookie) {
        my.request({
          url: url + '/api/orders/cancel',
          method: 'POST',
          data: {
            id:orderId,
            userId: this.data.id 
          },
          headers: {
            'content-type': 'application/json',
            'Cookie': userInfo.cookie,
          },
          dataType: 'json',
          success: (res) => {
            if(res.data.code===0){
              my.showToast({
                content: '订单已取消',
              });
              this.onShow()
            }
            else if(res.data.code===40100){
              my.alert({
                content: '登录信息已过期，请重新登录'
              });
              my.navigateTo({
                url:'/pages/denglu/denglu'
              })
            }
            console.log(res); 
            console.log(this.data.dingdan);
          },
          fail: (error) => {
            console.error('请求失败: ', JSON.stringify(error));
            my.alert({ content: '请求失败，请稍后重试' });
          },
        });
      } 
      else {
        my.alert({
          content: '您未登录，请先登录。',
          success: () => {
            my.navigateTo({
              url: '/pages/denglu/denglu',
            });
          },
        });
      }
    },
  });
  console.log(orderId,this.data.id);
},
tuikuan(){
 my.alert({
  content:'退款申请已提交，等待商家同意'
 })
},
pay(item){
  console.log(item,'jashgdkhjashdkjashdkaskh');
  const id = item.target.dataset.num
  const ordernumber = id.orderNumber
  const commoditiesName = id.commoditiesName
  const commoditiesPrice = id.totalPrice
  const quantity =id.quantity
  const commoditiesImage =id.commoditiesImage
  console.log(orderid,ordernumber,commoditiesName,commoditiesPrice);
  const orderid = id.id
  my.navigateTo({
    url:`/pages/pay/pay?ordernumber=${ordernumber}
    &&commoditiesName=${commoditiesName}
    &&commoditiesPrice=${commoditiesPrice}
    &&quantity=${quantity}&&commoditiesImage=${commoditiesImage}
    &&orderid=${orderid}`
  })
  console.log(id,'id啊');
  console.log(orderid,'orderid');
},
xiangqing(item){
  const id = item.target.dataset.num
  console.log(id,'xiangqing');
  const ordernumber  = id.orderNumber
  const createTime = id.createTime
  const phone = id.phone
  const userName = id.username
  const businessName =id.businessName
  const commoditiesName = id.commoditiesName;
  const commoditiesImage = id.commoditiesImage;
  const commoditiesPrice = id.totalPrice;
  const businessId = id.businessId
  const statues =id.paymentStatus
  const serviceMode = id.serviceMode
  console.log(statues,businessId,commoditiesPrice,commoditiesImage,commoditiesName,ordernumber,createTime,phone,userName,businessName);
  my.navigateTo({
    url:`/pages/dingdanxiangqing/dingdanxiangqing?ordernumber=${ordernumber}
    &&createTime=${createTime}&&phone=${phone}&&userName=${userName}
    &&businessName=${businessName}&&commoditiesName=${commoditiesName}&&commoditiesImage=${commoditiesImage}
    &&commoditiesPrice=${commoditiesPrice}&&businessId=${businessId}
    &&statues=${statues}&&serviceMode=${serviceMode}`
  })
},
orderok(item){
  const id = item.target.dataset.num
  const orderId = id.id
  console.log(orderId,'okroderid');
  my.getStorage({
    key: 'userInfo',
    success: (res) => {
      const userInfo = res.data;
      this.setData({
        id: userInfo.id, // 获取 id
      });

      if (userInfo && userInfo.cookie) {
        my.request({
          url: url + '/api/orders/success',
          method: 'POST',
          data: {
            id:orderId,
            userId: this.data.id 
          },
          headers: {
            'content-type': 'application/json',
            'Cookie': userInfo.cookie,
          },
          dataType: 'json',
          success: (res) => {
            if(res.data.code===0){
              my.showToast({
                content: '订单已完成',
              });
              this.onShow()
            }
            else if(res.data.code===40100){
              my.alert({
                content: '登录信息已过期，请重新登录'
              });
              my.navigateTo({
                url:'/pages/denglu/denglu'
              })
            }
            console.log(res); 
            console.log(this.data.dingdan);
          },
          fail: (error) => {
            console.error('请求失败: ', JSON.stringify(error));
            my.alert({ content: '请求失败，请稍后重试' });
          },
        });
      } 
      else {
        my.alert({
          content: '您未登录，请先登录。',
          success: () => {
            my.navigateTo({
              url: '/pages/denglu/denglu',
            });
          },
        });
      }
    },
  });
  console.log(orderId,this.data.id);
}
});

