<template>
  <view class="order-page" :class="{ 'wechat-browser': isWeixinBrowser }">

    <view class="header-title" :class="{ 'hide-in-wechat': isWeixinBrowser }">我的购票</view>
    <!-- 订单卡片列表 -->
    <view class="order-list">
      <template v-if="reservationList.length > 0">
        <view
          v-for="item in reservationList"
          :key="item.id"
          class="order-card"
          :class="getCardClass(item.status)"
        >
          <view class="order-card-header">
            <view class="status-wrapper">
              <view class="status" :class="getStatusClass(item.status)">
                <span class="status-text">{{ getStatusText(item.status) }}</span>
              </view>
              <view
                v-if="getBillStatusText(item.bill_status)"
                class="bill-status-tag"
              >
                {{ getBillStatusText(item.bill_status) }}
              </view>
            </view>
            <view class="date">{{ formatChinaDate(item.created_at) }}</view>
          </view>
          <view class="order-info">
            <view class="flight">编号：{{item.id}} - {{ item.ship ? item.ship.ship_number : '' }}</view>
            <view class="desc">
              {{ item.direction_name }} | {{ item.batch && item.batch.name ? item.batch.name : '-' }}
            </view>
          </view>
          <view
            class="order-actions"
            :class="{ 'single-btn': isSingleAction(item) }"
          >
            <template v-if="canCancel(item.status)">
              <button class="cancel-btn" @click="onCancelOrder(item)">取消预约</button>
            </template>
            <template v-if="canRebook(item.status)">
              <button class="cancel-btn" @click="goReservation(item)">重新预约</button>
            </template>
            <template v-if="canPay(item.status)">
              <button class="buy-btn" @click="goPayOrder(item)">去支付</button>
            </template>
            <template v-if="canIssueInvoice(item.bill_status)">
              <button class="invoice-btn" @click="goInvoice(item)">去开票</button>
            </template>
            <button class="detail-btn" @click="onShowDetail(item)">查看详情</button>
          </view>
        </view>
      </template>
      <template v-else>
        <view class="empty-box">
          <image src="/static/empty.png" class="empty-img" mode="aspectFit" />
          <view class="empty-text">暂无订单</view>
        </view>
      </template>
      <!-- 加载更多提示 -->
      <view v-if="reservationList.length > 0" class="load-more">
        <view v-if="loading" class="loading-text">加载中...</view>
        <view v-else-if="!hasMore" class="no-more-text">没有更多数据了</view>
      </view>
    </view>
  </view>
</template>

<script>
import { base } from '@/common/util.js'
import { API } from '@/config/index.js'

export default {
  name: 'OrderPage',
  data() {
    return {
      reservationStatusEnum: [],
      reservationList: [],
      isWeixinBrowser: false,
      page: 1,
      lastPage: 1,
      loading: false,
      hasMore: true
    }
  },
  onLoad() {
    // #ifdef H5
    this.isWeixinBrowser = /MicroMessenger/i.test(navigator.userAgent)
    // #endif
  },
  onShow() {
    this.fetchReservationStatusEnum().then(() => {
      // 重置分页
      this.page = 1;
      this.hasMore = true;
      this.fetchReservationList(true);
    });
  },
  // 下拉刷新
  onPullDownRefresh() {
    this.page = 1;
    this.hasMore = true;
    this.fetchReservationList(true).finally(() => {
      uni.stopPullDownRefresh();
    });
  },
  // 上拉加载更多
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore();
    }
  },
  methods: {
    formatChinaDate: base.formatChinaDate,
    async fetchReservationStatusEnum() {
      const token = uni.getStorageSync('token');
      if (!token) return;
      try {
        const res = await new Promise((resolve, reject) => {
          uni.request({
            url: `${API.RESERVATION_STATUS_ENUM}?token=${token}`,
            method: 'GET',
            success: resolve,
            fail: reject
          });
        });
        if (res.data && res.data.errcode === 0) {
          this.reservationStatusEnum = res.data.data;
        }
      } catch (e) {
        // 可选：错误处理
      }
    },
    async fetchReservationList(reset = false) {
      const token = uni.getStorageSync('token');
      if (!token) return;
      
      // 如果正在加载，直接返回
      if (this.loading) return;
      
      this.loading = true;
      
      try {
        const res = await new Promise((resolve, reject) => {
          uni.request({
            url: `${API.RESERVATION_LIST}?token=${token}`,
            method: 'GET',
            data: {
              page: this.page,
              page_size: 5,
            },
            success: resolve,
            fail: reject
          });
        });
        
        if (res.data && res.data.errcode === 0) {
          const newList = res.data.data.data || [];
          this.lastPage = res.data.data.last_page || 1;
          
          if (reset) {
            // 重置列表
            this.reservationList = newList;
          } else {
            // 追加数据
            this.reservationList = [...this.reservationList, ...newList];
          }
          
          // 判断是否还有更多数据
          this.hasMore = this.page < this.lastPage;
          
          console.log('当前页:', this.page, '总页数:', this.lastPage, '是否有更多:', this.hasMore);
        } else {
          uni.showToast({
            title: res.data.errmsg || '获取订单列表失败',
            icon: 'none'
          });
        }
      } catch (e) {
        console.error('获取订单列表失败:', e);
        uni.showToast({
          title: '网络错误',
          icon: 'none'
        });
      } finally {
        this.loading = false;
      }
    },
    // 加载更多
    loadMore() {
      if (this.hasMore && !this.loading) {
        this.page += 1;
        this.fetchReservationList(false);
      }
    },
    onCancelOrder(item) {
      uni.showModal({
        title: '提示',
        content: '确定要取消该预约吗？',
        confirmText: '确定',
        cancelText: '再想想',
        success: (res) => {
          if (res.confirm) {
            // 调用取消预约接口
            const token = uni.getStorageSync('token');
            if (!token) {
              uni.showToast({ title: '请先登录', icon: 'none' });
              return;
            }
            uni.showLoading({ title: '取消中...' });
            uni.request({
              url: `${API.CANCEL_RESERVATION}/${item.id}?token=${token}`,
              method: 'POST',
              success: (res) => {
                uni.hideLoading();
                if (res.data && res.data.errcode === 0) {
                  uni.showToast({ title: '已取消预约', icon: 'success' });
                  // 重置分页并刷新列表
                  this.page = 1;
                  this.hasMore = true;
                  this.fetchReservationList(true);
                } else {
                  uni.showToast({ title: res.data.errmsg || '取消失败', icon: 'none' });
                }
              },
              fail: () => {
                uni.hideLoading();
                uni.showToast({ title: '网络错误', icon: 'none' });
              }
            });
          }
        }
      });
    },
    onShowDetail(item) {
      uni.navigateTo({ url: `/pages/order/pay_order_detail?id=${item.id}` });
    },
    goPayOrder(item) {
      uni.navigateTo({ url: `/pages/order/pay_order_detail?id=${item.id}` });
    },
    goReservation(item) {
      uni.navigateTo({ url: '/pages/reservation/index' });
    },
    getStatusText(status) {
      if (this.reservationStatusEnum && this.reservationStatusEnum[status]) {
        return this.reservationStatusEnum[status].label;
      }
      return status;
    },
    getCardClass(status) {
      const map = {
        paid: 'purchased',
        completed: 'purchased',
        pending: 'pending',
        price_checked: 'pending',
        rejected: 'pending',
        unpaid: 'confirmed',
        approved: 'confirmed',
        canceled: 'canceled',
      };
      return map[status] || 'pending';
    },
    getStatusClass(status) {
      return {
        paid: 'purchased',
        completed: 'purchased',
        pending: 'pending',
        price_checked: 'pending',
        rejected: 'rejected',
        unpaid: 'confirmed',
        approved: 'confirmed',
        canceled: 'canceled',
      }[status] || 'pending';
    },
    isSingleAction(item) {
      const actions = [
        this.canCancel(item.status),
        this.canRebook(item.status),
        this.canPay(item.status),
        this.canIssueInvoice(item.bill_status)
      ];
      return actions.filter(Boolean).length === 0;
    },
    canCancel(status) {
      return ['pending', 'price_checked'].includes(status);
    },
    canRebook(status) {
      return status === 'rejected';
    },
    canPay(status) {
      return ['unpaid', 'approved'].includes(status);
    },
    canIssueInvoice(billStatus) {
      return billStatus === 2;
    },
    getBillStatusText(billStatus) {
      const map = {
        2: '待开票',
        3: '已开票'
      };
      return map[billStatus] || '';
    },
    goInvoice(item) {
      const token = uni.getStorageSync('token');
      if (!token) {
        uni.showToast({ title: '请先登录', icon: 'none' });
        return;
      }
      if (!item || !item.id) {
        uni.showToast({ title: '订单信息缺失', icon: 'none' });
        return;
      }
      uni.showLoading({ title: '提交中...' });
      uni.request({
        url: `${API.GET_INVOICE}`,
        method: 'GET',
        data: {
          reservation_id: item.id,
          token
        },
        success: (res) => {
          uni.hideLoading();
          if (res.data && res.data.errcode === 0) {
            const billData = res.data && res.data.data;
            const billInfo = billData && billData.bill;
            const billInfoList = billInfo && billInfo.billInfoList;
            const pictureUrl = Array.isArray(billInfoList) && billInfoList.length > 0
              ? billInfoList[0].pictureUrl
              : '';
            uni.showToast({ title: '开票申请已提交', icon: 'success', duration: 2000 ,success: () => {
              if (pictureUrl) {
                this.openExternalLink(pictureUrl);
              }
            }});
            this.page = 1;
            this.hasMore = true;
            this.fetchReservationList(true);
          } else {
            uni.showToast({ title: (res.data && res.data.errmsg) || '提交失败', icon: 'none' });
          }
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({ title: '提交失败', icon: 'none' });
        }
      });
    },
    openExternalLink(url) {
      if (!url) return;
      window.open(url, '_blank');
    }
  }
}
</script>

<style scoped>
.order-page {
  background: linear-gradient(180deg, #cbe6ff 0%, #f6faff 100%);
  min-height: 100vh;
  padding-bottom: 20px;
  font-family: 'SourceHanSansCN', 'PingFang SC', 'Microsoft YaHei', sans-serif;
}
.header-title {
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
  padding-top: 7vh;
  letter-spacing: 2rpx;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 16px 10px 16px;
  background: linear-gradient(180deg, #cbe6ff 0%, #f6faff 100%);
}
.back-btn, .more-btn {
  font-size: 24px;
  color: #333;
}
.title {
  font-size: 22px;
  font-weight: bold;
  color: #222;
}
.order-list {
  padding: 10px 0 0 0;
  margin-top: 44rpx;
}
.order-card {
  background: #fff;
  border-radius: 10px;
  margin: 0 16px 16px 16px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  padding: 18px 18px 12px 18px;
  height: 340rpx;
}
.order-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.status {
  font-size: 12px;
  border-radius: 8rpx;
  padding: 2px 8px;
  color: #fff;
  font-weight: 500;
  display: inline-block;
  transform: skewX(-20deg);
  border: none;
}
.status-text {
  display: inline-block;
  transform: skewX(20deg);
}
.status.purchased { background: #22c58b; }
.status.pending { background: #ff9800; }
.status.rejected { background: #ff4d4f; }
.status.confirmed { background: #217aff; }
.status.cancelled { background: #bdbdbd; }
.status.canceled {
  background: #b0b8c6;
  color: #fff;
}
.status-wrapper {
  display: flex;
  align-items: center;
  gap: 12rpx;
}
.bill-status-tag {
  padding: 4rpx 16rpx;
  border-radius: 999rpx;
  font-size: 24rpx;
  color: #217aff;
  background: #e4f3fe;
}
.date { color: #173766; font-size: 15px; }
.order-info {
  margin-bottom: 24px;
}
.flight {
  font-size: 16px;
  font-weight: 500;
  margin-top: 12px;
}
.desc {
  color: #888;
  font-size: 14px;
  margin-top: 10px;
}
.order-actions {
  display: flex;
  gap: 12px;
}
button {
  flex: 1;
  border-radius: 4px;
  padding: 8px 0;
  font-size: 16px;
  margin: 0;
}
.detail-btn {
  background: #e4f3fe;
  color: #217aff;
  height: 69rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  margin-left: auto;
}
.order-actions.single-btn {
  justify-content: flex-end;
}
.order-actions.single-btn .detail-btn {
  flex: 0 0 auto;
  width: 153px;
}
.buy-btn, .rebook-btn {
  background: linear-gradient(90deg, #3b7cff 0%, #5bb6ff 100%);
  color: #fff;

  height: 69rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}
.invoice-btn {
  background: #fff5e6;
  color: #ff9f0a;
  height: 69rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}
.cancel-btn {
  background: #ededed;
  color: #bdbdbd;

  height: 69rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}
.cancel-btn[disabled] {
  opacity: 1;
}
.tabbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 60px;
  background: #fff;
  display: flex;
  border-top: 1px solid #eaeaea;
  z-index: 10;
}
.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #888;
  font-size: 14px;
}
.tab-item.active {
  color: #217aff;
}
.icon {
  font-size: 22px;
  margin-bottom: 2px;
}
.detail-modal-mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background: rgba(0,0,0,0.5);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}
.detail-modal {
  background: #fff;
  border-radius: 20px;
  padding: 64rpx 56rpx 48rpx 56rpx;
  width: 90vw;
  max-width: 500px;
  min-height: 420px;
  margin: 0 auto;
  position: relative;
  display: flex;
  flex-direction: column;
}
.detail-modal-content {
  flex: 1 1 auto;
  min-height: 0;
  overflow-y: auto;
}
.modal-close {
  position: absolute;
  right: 24rpx;
  top: 24rpx;
  font-size: 44rpx;
  color: #222;
  z-index: 2;
  cursor: pointer;
}
.modal-title {
  font-size: 38rpx;
  font-weight: bold;
  margin-bottom: 40rpx;
  text-align: left;
}
.modal-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 34rpx;
  color: #222;
  margin-bottom: 36rpx;
}
.modal-label {
  color: #3b4a6b;
  min-width: 180rpx;
  font-size: 34rpx;
}
.modal-amount {
  color: #217aff;
  font-size: 32rpx;
  font-weight: bold;
}
.modal-confirm-btn {
  width: 160px !important;
  height: 44px !important;
  line-height: 44px !important;
  border-radius: 12px !important;
  background: linear-gradient(90deg, #3b7cff 0%, #5bb6ff 100%) !important;
  color: #fff !important;
  font-size: 18px !important;
  font-weight: 500 !important;
  margin: 40px auto 0 auto !important;
  border: none !important;
  outline: none !important;
  display: block !important;
  padding: 0 !important;
  box-sizing: border-box !important;
  text-align: center !important;
  align-self: center !important;
  flex-shrink: 0 !important;
  flex-grow: 0 !important;
}
.order-card.canceled {
  opacity: 0.7;
}
.empty-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-top: 120rpx;
}
.empty-img {
  width: 320rpx;
  height: 320rpx;
  margin-bottom: 32rpx;
}
.empty-text {
  color: #888;
  font-size: 28rpx;
}

.hide-in-wechat {
  display: none !important;
}

.wechat-browser {
  margin-top: -44rpx;
}
.load-more {
  padding: 30rpx 0;
  text-align: center;
}
.loading-text {
  color: #888;
  font-size: 28rpx;
}
.no-more-text {
  color: #999;
  font-size: 26rpx;
}
</style> 
