<template>
  <view class="container">
	   <uni-pagination v-if="total > 0" :current="currentPage" :total="total" :pageSize="pageSize" @change="onPageChange"></uni-pagination>

    <scroll-view scroll-y class="preview">
      <!-- 商品详情 -->
      <view class="tab-menu">
        <view class="tab-item"
              v-for="(tab, index) in tabs"
              :key="index"
              :class="{ active: currentIndex === index }"
              @click="switchTab(index)">
          {{ tab.name }}
        </view>
      </view>
      <view class="content">
        <block v-if="currentIndex === 0">
          <view class="container1" v-for="(order, index) in orderList" :key="index">
          <view class="box">
            <view class="numberState">
              <view class="number">#{{ order.id }}</view>
              <view class="state">商家已自动接单</view>
            </view>
            <view class="time">下单时间:{{formatOrderTime(order.createTime)}}</view>
            <view class="message">
              <view class="name">{{order.userName}}</view>
              <view class="phone">手机尾号{{ order.phone.slice(-4) }}</view>
            </view>
            <view class="button" @click="telephone(order)">电话联系</view>
            <view class="sure" @click="dinner(index)">打印小票</view>
 <!-- <button type='primary' @tap='receiptTest' :loading='isReceiptSend' :disabled='isReceiptSend'>票据测试</button> -->
			 <view class="sure" @click="refund(order)">确认退款</view>
			  <view class="sure" @click="finish(order)">确认出餐</view>
          </view>
          <view class="box2">
            <view class="beizhu">
				<view class="tag-view">
					<uni-tag :mark="true" text="备注" type="warning" size="mini" />
				</view>
				顾客需要餐具；
			</view>
            <view class="goods">1种商品，共1件</view>
            <view class="money">预计收入￥{{ order.totalPrice }}</view>
			<uni-collapse-item title="订单详情" :show-animation="true">
					 <view v-for="(item, index) in order.orderDetailsVOList" :key="index" class="box3">
					      <text class="left3">{{ item.attributeNames || '未知菜品' }}</text>
					      <text class="right3">¥ {{ item.price }}</text>
					    </view>

			</uni-collapse-item>
          </view>
        </view>
        </block>
        <block v-if="currentIndex === 1">
          <view class="container1" v-for="(order, index) in refundOrderList" :key="index">
            <view class="box">
              <view class="numberState">
                <view class="number">#{{ order.id }}</view>
                <view class="state">订单已退款</view>
              </view>
              <view class="message">
                <view class="name">{{order.userName}}</view>
                <view class="phone">手机尾号{{ order.phone.slice(-4) }}</view>
              </view>
              <view class="sure" @click="refunddinner(index)">打印退款小票</view>
            </view>
            <view class="box2">
              <view class="goods">1种商品，共1件</view>
              <view class="money">退款金额￥{{ order.totalPrice }}</view>
          	<uni-collapse-item title="订单详情" :show-animation="true">
          			 <view v-for="(item, index) in order.orderDetailsVOList" :key="index" class="box3">
          			      <text class="left3">{{ item.attributeNames || '未知菜品' }}</text>
          			      <text class="right3">¥ {{ item.price }}</text>
          			    </view>
          
          	</uni-collapse-item>
            </view>
          </view>
        </block>
        <block v-if="currentIndex === 2">
         
		<!-- <view class="container1" v-for="(order, index) in orderList" :key="index">
		          <view class="box">
		            <view class="numberState">
		              <view class="number">#{{ order.id }}</view>
		              <view class="state">用户退款申请</view>
		            </view>
		            <view class="time">下单时间:{{formatOrderTime(order.createTime)}}</view>
		            <view class="message">
		              <view class="name">{{order.userName}}</view>
		              <view class="phone">手机尾号{{ order.phone.slice(-4) }}</view>
		            </view>
		            <view class="button" @click="telephone(order)">电话联系</view>
		 			 <view class="sure" @click="refund(order)">确认退款</view>
		          </view>
		          <view class="box2">
		            <view class="goods">1种商品，共1件</view>
		            <view class="money">需退金额￥{{ order.totalPrice }}</view>
		 			<uni-collapse-item title="订单详情" :show-animation="true">
		 					 <view v-for="(item, index) in order.orderDetailsVOList" :key="index" class="box3">
		 					      <text class="left3">{{ item.attributeNames || '未知菜品' }}</text>
		 					      <text class="right3">¥ {{ item.price }}</text>
		 					    </view>
		 			</uni-collapse-item>
		          </view>
		        </view> -->
		 
		 
        </block>
      </view>
    </scroll-view>
  </view>
</template>
<script>
import { apiImageUrl } from '../../API/api';

export default {
  data() {
    return {
      currentIndex: 0,
      tabs: [
        { name: '待出餐' },
        { name: '已退款' },
        { name: '已完成' },
      ],
	     orderList: [],
	        refundOrderList: [],
	        currentPage: 1, 
	        pageSize: 10, 
	        total: 0, 

    };
  },
  onLoad() {
    this.getLoginUser();
  },
  onShow() {
    this.getLoginUser();
  },
  methods: {
    getRefundReason(){
		uni.request({
			url:apiImageUrl+'/api/refund/list/business',
			method:'POST',
			header: {
			  'cookie': uni.getStorageSync("cookie")
			},
			success(res) {
				console.log(res);
			},
			fail(err) {
				console.log(err);
			}
		})
	},
    switchTab(index) {
         this.currentIndex = index;
         if (index === 0) {
           this.getOrder();
         } else if (index === 1) {
           this.getRefundOrder();
         }else if (index===2){
			 this.getRefundReason()
		 }
       },
       onPageChange(e) {
         this.currentPage = e.current;
         if (this.currentIndex === 0) {
           this.getOrder();
         } else if (this.currentIndex === 1) {
           this.getRefundOrder();
         }else if (this.currentIndex === 2) {
           this.getRefundReason()
         }
       },
	dinner(index) {
		  const currentOrder = this.orderList[index];
		   console.log('当前选择的订单信息:', currentOrder);
		  const orderInfo = encodeURIComponent(JSON.stringify(currentOrder));
		  uni.navigateTo({
		     url: `/pages/sendCommand/sendCommand?orderInfo=${orderInfo}`
		   });
	},
	refunddinner(index) {
		  const currentOrder = this.refundOrderList[index];
		   console.log('当前选择的订单信息:', currentOrder);
		  const orderInfo = encodeURIComponent(JSON.stringify(currentOrder));
		  uni.navigateTo({
		     url: `/pages/sendCommand/sendCommand?orderInfo=${orderInfo}`
		   });
	},
	telephone(order){
		console.log("99999999999999999");
		console.log(order.phone);
		uni.makePhoneCall({
			phoneNumber: order.phone 
		});

	},
	 refund(order) {
	      console.log(order.pickupCode);
	      const pickupCodeNumber = order.pickupCode;
	      const _this = this; 
	      uni.request({
	        url: apiImageUrl + '/api/Alipay/test/refund',
	        method: 'GET',
	        data: {
	          orderNo: pickupCodeNumber
	        },
	        header: {
	          'cookie': uni.getStorageSync("cookie")
	        },
	        success: (res) => {  
	          console.log(res);
	          if (['10000', '40006', '20000'].includes(res.data.alipay_trade_refund_response.code)) {
	            uni.showModal({
	              title: '提示',
	              content: '退款成功',
	              showCancel: false,
	              success: () => {
	                if (_this.currentIndex === 0) {
	                  _this.getOrder();
	                } else if (_this.currentIndex === 1) {
	                  _this.getRefundOrder();
	                }
	                uni.reLaunch({ url: '/pages/order/order' });
	              }
	            });
	          } else {
	            uni.showModal({
	              title: '提示',
	              content: '退款失败',
	              showCancel: false,
	            });
	          }
	        },
	        fail() {
	          console.log("失败");
	        }
	      })
	    },
	  finish(order) {
		  console.log(order.id);
	      const _this = this; 
	      uni.request({
	        url: apiImageUrl + '/api/orders/update',
	        method: 'POST',
	        data: {
	          id: order.id
	        },
	        header: {
	          'cookie': uni.getStorageSync("cookie")
	        },
	        success: (res) => { 
	          console.log(res);
	          if (res.data.code === 0) {
	            uni.showModal({
	              title: '提示',
	              content: '确认出餐成功',
	              showCancel: false,
	              success: () => {
	                if (_this.currentIndex === 0) {
	                  _this.getOrder();
	                }
	                _this.getFinishOrderList();
	              }
	            });
	          } else {
	            uni.showModal({
	              title: '提示',
	              content: '确认出餐失败',
	              showCancel: false,
	            });
	          }
	        },
	        fail: (err) => {
	          console.log(err);
	          uni.showModal({
	            title: '错误',
	            content: '网络请求失败',
	            showCancel: false
	          });
	        }
	      })
	    },
	formatOrderTime(timeString) {
	  if (!timeString) return '';
	  const date = new Date(timeString);
	  const year = date.getFullYear();
	  const month = ('0' + (date.getMonth() + 1)).slice(-2); 
	  const day = ('0' + date.getDate()).slice(-2);
	  const hour = ('0' + date.getHours()).slice(-2);
	  const minute = ('0' + date.getMinutes()).slice(-2);
	  const second = ('0' + date.getSeconds()).slice(-2);

	  return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
	},
	  getOrder() {
	      uni.request({
	        url: apiImageUrl + '/api/orders/my/page',
	        method: 'POST',
	        data: {
	          current: this.currentPage,
	          endTime: "",
	          id: "",
	          pageSize: this.pageSize,
	          pickupMethod: "",
	          sortField: "",
	          sortOrder: "",
	          startTime: "",
	          state: 1
	        },
	        header: {
	          'cookie': uni.getStorageSync("cookie")
	        },
	        success: (res) => {
	          console.log(res);
	          this.orderList = res.data.data.records.reverse();
	          this.total = res.data.data.total; 
	          console.log(this.orderList);
			
	        },
	        fail: () => {
	          console.log('出错啦');
	        }
	      });
	    },
	  getRefundOrder() {
	      uni.request({
	        url: apiImageUrl + '/api/orders/my/page',
	        method: 'POST',
	        data: {
	          current: this.currentPage,
	          endTime: "",
	          id: "",
	          pageSize: this.pageSize,
	          pickupMethod: "",
	          sortField: "",
	          sortOrder: "",
	          startTime: "",
	          state: 2
	        },
	        header: {
	          'cookie': uni.getStorageSync("cookie")
	        },
	        success: (res) => {
	          console.log(res);
	          this.refundOrderList = res.data.data.records;
	          this.total = res.data.data.total;
	          console.log(this.refundOrderList);
	        },
	        fail: () => {
	          console.log('出错啦');
	        }
	      });
	    },
		 getFinishOrderList() {
		      uni.request({
		        url: apiImageUrl + '/api/orders/my/page',
		        method: 'POST',
		        data: {
		          current: this.currentPage,
		          endTime: "",
		          id: "",
		          pageSize: this.pageSize,
		          pickupMethod: "",
		          sortField: "",
		          sortOrder: "",
		          startTime: "",
		          state: 4
		        },
		        header: {
		          'cookie': uni.getStorageSync("cookie")
		        },
		        success: (res) => {
		          console.log(res);
		          this.finishOrderList = res.data.data.records.reverse();
		          this.total = res.data.data.total;
		        },
		        fail: () => {
		          console.log('出错啦');
		        }
		      });
		    }
		  },
		getLoginUser() {
		  uni.request({
		    url: apiImageUrl + '/api/business/get/current',
		    method: 'POST',
		    header: {
		      'cookie': uni.getStorageSync("cookie")
		    },
		    success: (res) => {
		      console.log('用户信息:', res);
			   if (res.data && res.data.data) {
			            this.user = res.data.data; 
			            const currentBusinessId = res.data.data.id;
			            uni.setStorageSync('currentBusinessId', currentBusinessId); 
			            console.log('当前商家ID:', currentBusinessId);
			          }
		        uni.showToast({
		          title: '去蓝牙连接小票机',
		          duration: 2000,
		          icon: 'none'
		        });
		    },
		    fail: (err) => {
		      console.log('请求失败:', err);
		      uni.showToast({
		        title: '去登录',
		        duration: 2000,
		        icon: 'none'
		      });
		      uni.navigateTo({ url: '/pages/login/login' })
		    }
		  });
		},
  mounted() {
    this.getOrder();
	 this.getRefundOrder();
	 this.getFinishOrderList(); 
  }

};
</script>
<style scoped>
.container {
  height: 100vh; 
  display: flex;
  flex-direction: column;
}

.preview {
  flex: 1; 
  overflow-y: auto;
}

.tab-menu {
  display: flex;
  justify-content: space-around;
  background-color: #f8f8f8;
  padding: 10px 0;
}

.tab-item {
  padding: 10px 20px;
  font-size: 16px;
}

.tab-item.active {
  color: #007aff;
  border-bottom: 2px solid #007aff;
}

.content {
  padding: 10px;
}

.container1 {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 10px;
  padding: 10px;
}

.box {
  padding: 10px;
  border-bottom: 1px solid #e0e0e0;
}

.numberState {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.number {
  font-weight: bold;
  font-size: 20px;
}

.state {
  color: #007aff;
  font-size: 14px;
}

.time {
  margin-top: 5px;
  color: #757575;
  font-size: 14px;
}

.message {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
  font-size: 14px;
}

.phone {
  color: #757575;
}

.button {
  background-color: #fdd835;
  color: #000;
  padding: 5px 10px;
  margin-top: 5px;
  border-radius: 5px;
  font-size: 12px;
}

.sure {
  background-color: #007aff;
  color: #fff;
  padding: 5px 10px;
  margin-top: 5px;
  border-radius: 5px;
  font-size: 14px;
  text-align: center;
}

.box2 {
  padding: 10px;
  font-size: 14px;
}

.beizhu {
	font-size: 20px;
	font-weight: 700;
	padding-bottom: 15px;
	padding-top: 10px;
	background-color: linear-gradient(to bottom,#fdd835,#fff);
}

.beizhu, .goods, .money {
  margin-top: 5px;
}

.km {
  margin-top: 5px;
  color: #757575;
  font-size: 14px;
}

.box3 {
	padding-top: 5px;
	padding-bottom: 5px;
}
.left3,.right3 {
	font-size: 30rpx;
}
.right3 {
	float: right;
	padding-right: 5px;
	font-weight: 700;
}
.left3 {
	padding-left: 5px;
}
.tag-view {
	float: left;
	margin-right: 10px;
}
</style>
