index.vue 27 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
<!--
 * @Date: 2022-09-19 14:11:06
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-07-14 17:03:37
 * @FilePath: /jgdl/src/pages/myOrders/index.vue
 * @Description: 订单管理页面
-->
<template>
  <view class="order-management-page">
    <nut-sticky>
      <!-- 买车/卖车切换 -->
      <view id="mode-toggle" class="view-mode-toggle">
        <view class="toggle-container">
          <view class="toggle-option" :class="{ active: viewMode === 'buy' }" @click="setViewMode('buy')">
            我买的车
          </view>
          <view class="toggle-option" :class="{ active: viewMode === 'sell' }" @click="setViewMode('sell')">
            我卖的车
          </view>
        </view>
      </view>

      <!-- 状态筛选标签 -->
      <view id="status-tabs" class="status-tabs">
        <view class="tab-item" :class="{ active: activeTab === '' }" @click="setActiveTab('')">
          全部
        </view>
        <view v-if="viewMode === 'buy'" class="tab-item" :class="{ active: activeTab === 3 }"
          @click="setActiveTab(3)">
          待支付
        </view>
        <view class="tab-item" :class="{ active: activeTab === 5 }" @click="setActiveTab(5)">
          已完成
        </view>
        <view class="tab-item" :class="{ active: activeTab === 7 }" @click="setActiveTab(7)">
          已取消
        </view>
      </view>
    </nut-sticky>

    <!-- 订单列表 -->
    <view class="order-list">
      <!-- 滚动列表 -->
      <scroll-view ref="scrollViewRef" class="order-scroll-view" :style="scrollStyle" :scroll-y="true" @scrolltolower="loadMore"
        @scroll="scroll" :lower-threshold="50" :enable-flex="false" :scroll-top="scrollTop">
        <!-- 空状态 -->
        <view v-if="filteredOrders.length === 0" class="empty-state">
          <text class="empty-text">暂无订单</text>
        </view>

        <!-- 订单卡片 -->
        <view v-else>
          <view v-for="order in filteredOrders" :key="order.id" class="order-card">
            <!-- 订单头部信息 -->
            <view class="order-header">
              <text class="order-date">{{ order.created_time }}</text>
              <text class="order-status" :class="getStatusClass(order.status)">
                {{ getStatusText(order.status) }}
              </text>
            </view>

            <!-- 车辆信息 -->
            <nut-row :gutter="12" class="vehicle-info">
              <nut-col :span="6">
                <image :src="order.details.vehicle.front_photo || DEFAULT_COVER_IMG" :alt="order.details.vehicle.brand + ' ' + order.details.vehicle.model" class="vehicle-image"
                  mode="aspectFill" />
              </nut-col>
              <nut-col :span="18">
                <view class="vehicle-details">
                  <text class="vehicle-name">{{ order.details.vehicle.brand }} {{ order.details.vehicle.model }}</text>
                  <text class="vehicle-specs">
                    {{ order.details.vehicle.manufacture_year }}年 | 续航{{ order.details.vehicle.range_km }}km
                  </text>
                  <text class="vehicle-battery">电池容量:{{ order.details.vehicle.battery_capacity_ah }}Ah</text>
                  <text class="vehicle-price">¥{{ order.details.vehicle.price }}</text>
                </view>
              </nut-col>
            </nut-row>

            <!-- 操作按钮 -->
            <view class="order-actions">
              <!-- 买车模式:待支付状态 -->
              <template v-if="viewMode === 'buy' && order.status === 3">
                <nut-button type="default" size="small" @click="handleCancelOrder(order.id)"
                  :loading="cancelingOrderId === order.id" :disabled="cancelingOrderId === order.id">
                  {{ cancelingOrderId === order.id ? '取消中...' : '取消订单' }}
                </nut-button>
                <nut-button type="primary" size="small" @click="handlePayment(order)" color="orange" class="ml-2">
                  去支付
                </nut-button>
              </template>

              <!-- 已完成状态 -->
              <template v-if="order.status === 5">
                <nut-button type="default" size="small" @click="viewOrderDetail(order.id)">
                  查看详情
                </nut-button>
                <nut-button type="primary" size="small" @click="rateOrder(order.id)" class="ml-2" color="orange" plain>
                  {{ order.details.review ? '查看评价' : '评价' }}
                </nut-button>
              </template>

              <!-- 已取消状态 -->
              <template v-if="order.status === 7">
                <nut-button type="default" size="small" @click="deleteOrder(order.id)"
                  :loading="deletingOrderId === order.id" :disabled="deletingOrderId === order.id">
                  {{ deletingOrderId === order.id ? '删除中...' : '删除订单' }}
                </nut-button>
              </template>
            </view>
          </view>
        </view>

        <!-- 加载更多指示器 -->
        <view v-if="loading" class="loading-container">
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 没有更多数据 -->
        <view v-if="!hasMore && filteredOrders.length > 0" class="no-more">
          <text class="no-more-text">没有更多订单了</text>
        </view>
      </scroll-view>
    </view>

    <!-- 支付组件 -->
    <payCard :visible="show_pay" :data="payData" @close="onPayClose" @paySuccess="onPaySuccess" />

    <!-- 评价弹窗 -->
    <nut-popup v-model:visible="showRatePopup" position="right" :style="{ width: '100%', height: '100%' }" closeable
      close-icon-position="top-right" @close="closeRatePopup">
      <view class="rate-popup">
        <view class="rate-header">
          <text class="rate-title">{{ isReadOnlyMode ? '查看评价' : '商品评价' }}</text>
        </view>

        <view class="rate-content">
          <!-- 商品信息展示 -->
          <view class="product-info">
            <image :src="currentRateOrder?.details?.vehicle?.front_photo || DEFAULT_COVER_IMG" class="product-image" mode="aspectFill" />
            <view class="product-details">
              <text class="product-name">{{ currentRateOrder?.details?.vehicle?.brand }} {{ currentRateOrder?.details?.vehicle?.model }}</text>
              <text class="product-specs">{{ currentRateOrder?.details?.vehicle?.manufacture_year }}年 · 里程: {{ currentRateOrder?.details?.vehicle?.range_km }}km</text>
              <text class="product-price">¥ {{ currentRateOrder?.details?.vehicle?.price }}</text>
            </view>
          </view>

          <!-- 评分组件 -->
          <view class="rate-score-section">
            <text class="score-label">{{ isReadOnlyMode ? '评分' : '请给商品评分' }}</text>
            <nut-rate v-model="rateScore" :readonly="isReadOnlyMode" :size="isReadOnlyMode ? '20' : '24'"
              active-color="#ff6b35" void-color="#e5e5e5" class="rate-stars" />
            <!-- <text v-if="isReadOnlyMode" class="score-text">{{ rateScore }}/5分</text> -->
          </view>

          <!-- 评价输入框 -->
          <view class="rate-input-section">
            <text class="input-label">{{ isReadOnlyMode ? '评价内容' : '请输入评价内容' }}</text>
            <view class="border border-gray-100">
              <nut-textarea v-model="rateContent" :placeholder="isReadOnlyMode ? '' : '请输入您的评价内容...'" :max-length="200"
                :rows="4" :show-word-limit="!isReadOnlyMode" :readonly="isReadOnlyMode"
                :class="{ 'readonly': isReadOnlyMode }" />
            </view>
            <!-- <text v-if="isReadOnlyMode && currentRateOrder?.details?.review?.date" class="review-date">
              评价时间:{{ currentRateOrder?.details?.review?.date }}
            </text> -->
          </view>
        </view>

        <!-- 提交按钮 -->
        <view class="rate-footer" v-if="!isReadOnlyMode">
          <nut-button type="primary" size="large" @click="submitRate" :loading="submittingRate" block>
            提交评价
          </nut-button>
        </view>
      </view>
    </nut-popup>

    <!-- 订单详情弹窗 -->
    <nut-popup v-model:visible="showOrderDetailPopup" position="right" :style="{ width: '100%', height: '100%' }"
      @close="closeOrderDetailPopup">
      <view class="order-detail-popup">
        <view class="detail-header">
          <text class="detail-title">订单详情</text>
        </view>

        <view class="detail-content">
          <!-- 订单基本信息 -->
          <view class="detail-section">
            <text class="section-title">订单信息</text>
            <view class="info-row">
              <text class="info-label">订单编号</text>
              <text class="info-value">{{ currentOrderDetail?.id }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">下单时间</text>
              <text class="info-value">{{ currentOrderDetail?.created_time }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">支付时间</text>
              <text class="info-value">{{ currentOrderDetail?.payment_time }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">订单状态</text>
              <text class="info-value" :class="getStatusClass(currentOrderDetail?.status)">
                {{ getStatusText(currentOrderDetail?.status) }}
              </text>
            </view>
            <view class="info-row">
              <text class="info-label">订单金额</text>
              <text class="info-value price">¥ {{ currentOrderDetail?.total_amount }}</text>
            </view>
          </view>

          <!-- 商品信息 -->
          <view class="detail-section">
            <text class="section-title">商品信息</text>
            <view class="product-detail-info">
              <image :src="currentOrderDetail?.details?.vehicle?.front_photo || DEFAULT_COVER_IMG" class="product-detail-image" mode="aspectFill" />
              <view class="product-detail-content">
                <text class="product-detail-name">{{ currentOrderDetail?.details?.vehicle?.brand }} {{ currentOrderDetail?.details?.vehicle?.model }}</text>
                <text class="product-detail-specs">{{ currentOrderDetail?.details?.vehicle?.manufacture_year }}年 · 续航: {{
                  currentOrderDetail?.details?.vehicle?.range_km }}km/h</text>
                <text class="product-detail-battery">电池容量: {{ currentOrderDetail?.details?.vehicle?.battery_capacity_ah }}Ah</text>
                <text class="product-detail-price">¥ {{ currentOrderDetail?.details?.vehicle?.price }}</text>
              </view>
            </view>
          </view>

          <!-- 交易信息 -->
          <view class="detail-section">
            <text class="section-title">交易信息</text>
            <view class="info-row">
              <text class="info-label">{{ viewMode === 'buy' ? '卖家' : '买家' }}</text>
              <text class="info-value">{{ viewMode === 'buy' ? currentOrderDetail?.details?.vehicle?.seller?.nickname : currentOrderDetail?.buyer?.nickname }}</text>
            </view>
            <view class="info-row">
              <text class="info-label">联系电话</text>
              <text class="info-value">{{ viewMode === 'buy' ? currentOrderDetail?.details?.vehicle?.seller?.phone : currentOrderDetail?.buyer?.phone }}</text>
            </view>
            <!-- <view class="info-row">
              <text class="info-label">交易地点</text>
              <text class="info-value">北京市朝阳区望京SOHO</text>
            </view> -->
          </view>

          <!-- 评价信息(如果有) -->
          <view class="detail-section" v-if="currentOrderDetail?.details?.review">
            <text class="section-title">评价信息</text>
            <view class="review-info">
              <view class="review-rating">
                <text class="rating-label">评分:</text>
                <nut-rate :model-value="currentOrderDetail?.details?.review?.rating" readonly size="20" active-color="#ff6b35"
                  void-color="#e5e5e5" />
                <!-- <text class="rating-text">{{ currentOrderDetail?.details?.review?.rating }}/5分</text> -->
              </view>
              <view class="review-content">
                <text class="content-label">评价内容:</text>
                <text class="content-text">{{ currentOrderDetail?.details?.review?.note }}</text>
              </view>
              <view class="review-time">
                <text class="time-text">评价时间:{{ currentOrderDetail?.details?.review?.created_time }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 关闭按钮 -->
        <view class="detail-footer">
          <nut-button type="primary" size="large" @click="closeOrderDetailPopup" block color="orange">
            关闭
          </nut-button>
        </view>
      </view>
    </nut-popup>

    <!-- Delete Confirmation Modal -->
    <nut-dialog
        v-model:visible="showConfirmModal"
        title="温馨提示"
        cancel-text="取消"
        ok-text="确认"
        @cancel="showConfirmModal = false"
        @ok="performDeleteOrder(pendingDeleteOrderId)"
    >
      <template #default>
        <view>
          <text style="font-size: 1rem;">删除订单将无法恢复,请谨慎操作。</text>
        </view>
      </template>
    </nut-dialog>

    <!-- Cancel Order Confirmation Modal -->
    <nut-dialog
        v-model:visible="showCancelConfirmModal"
        title="温馨提示"
        cancel-text="我再想想"
        ok-text="确定取消"
        @cancel="showCancelConfirmModal = false"
        @ok="performCancelOrder(pendingCancelOrderId)"
    >
      <template #default>
        <view>
          <text style="font-size: 1rem;">取消订单后将无法恢复,确定要取消吗?</text>
        </view>
      </template>
    </nut-dialog>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import './index.less'
import { $ } from '@tarojs/extend'
import payCard from '@/components/payCard.vue'
// 导入接口
import { getOrderListAPI, getOrderDetailAPI, reviewOrderAPI, cancelOrderAPI, deleteOrderAPI } from '@/api/orders'
import { DEFAULT_COVER_IMG } from '@/utils/config'

const scrollStyle = ref({
  height: ''
})

// 滚动相关
const scrollViewRef = ref(null)
const scrollTop = ref(0)

// 页面状态
const activeTab = ref('')
const viewMode = ref('buy')
const loading = ref(false)
const hasMore = ref(true)

const show_pay = ref(false)
const payData = ref({
  id: '',
  price: 0,
  remain_time: 0
})

// 评价相关状态
const showRatePopup = ref(false)
const currentRateOrder = ref(null)
const rateContent = ref('')
const rateScore = ref(5)
const submittingRate = ref(false)
const isReadOnlyMode = ref(false)

// 订单详情相关状态
const showOrderDetailPopup = ref(false)
const currentOrderDetail = ref(null)

// 订单数据 - 我买的车
const boughtOrders = ref([])

// 订单数据 - 我卖的车
const soldOrders = ref([])

// 分页相关状态
const currentPage = ref(0)
const pageLimit = ref(10)

/**
 * 根据当前视图模式和筛选条件获取过滤后的订单列表
 */
const filteredOrders = computed(() => {
  const orders = viewMode.value === 'buy' ? boughtOrders.value : soldOrders.value

  if (activeTab.value === '') {
    return orders
  }

  return orders.filter(order => {
    if (activeTab.value === 3) return order.status === 3
    if (activeTab.value === 5) return order.status === 5
    if (activeTab.value === 7) return order.status === 7
    return true
  })
})

/**
 * 设置视图模式(买车/卖车)
 */
const setViewMode = (mode) => {
  viewMode.value = mode
  // 重置状态筛选标签到全部
  activeTab.value = ''
  // 重置列表状态和数据
  resetListState(true)
}

/**
 * 设置活跃的状态标签
 */
const setActiveTab = (tab) => {
  activeTab.value = tab
  // 重置列表加载状态并重新加载数据
  currentPage.value = 0
  loadOrderData(false)
}

/**
 * 加载订单数据
 * @param {boolean} isLoadMore - 是否为加载更多
 */
const loadOrderData = async (isLoadMore = false) => {
  if (loading.value) return

  try {
    loading.value = true

    const type = viewMode.value === 'buy' ? 'buy' : 'sell'
    const status = activeTab.value || undefined
    const page = isLoadMore ? currentPage.value + 1 : 0

    const response = await getOrderListAPI({
      type,
      status,
      page,
      limit: pageLimit.value
    })

    if (response.code && response.data && response.data.list && response.data.list.length > 0) {
      // 处理多个订单数据
      const newOrders = response.data.list.map(orderData => {
        // 处理details数组,取第一个元素作为details对象
        return {
          ...orderData,
          details: orderData.details && orderData.details.length > 0 ? orderData.details[0] : null
        }
      })

      const targetOrders = viewMode.value === 'buy' ? boughtOrders : soldOrders

      if (isLoadMore) {
        targetOrders.value = [...targetOrders.value, ...newOrders]
        currentPage.value = page
      } else {
        targetOrders.value = newOrders
        currentPage.value = 0
      }

      // 判断是否还有更多数据
      hasMore.value = newOrders.length === pageLimit.value
    } else {
      hasMore.value = false
    }
  } catch (error) {
    console.error('加载订单数据失败:', error)
    Taro.showToast({
      title: '加载失败,请重试',
      icon: 'error',
      duration: 2000
    })
    hasMore.value = false
  } finally {
    loading.value = false
  }
}

/**
 * 重置列表状态
 * @param {boolean} resetData - 是否重置已加载的数据
 */
const resetListState = (resetData = false) => {
  loading.value = false
  hasMore.value = true
  currentPage.value = 0

  // 重置滚动位置到顶部
  scrollTop.value = Math.random() // 使用随机数触发scroll-view重新渲染

  if (resetData) {
    // 清空订单数据
    boughtOrders.value = []
    soldOrders.value = []
    // 重新加载数据
    loadOrderData(false)
  }

  // 延迟重置scrollTop为0,确保滚动位置正确
  setTimeout(() => {
    scrollTop.value = 0
  }, 50)
}

/**
 * 滚动事件处理
 */
const scroll = (e) => {
  // 可以在这里处理滚动事件
}



/**
 * 加载更多数据
 */
const loadMore = () => {
  if (loading.value || !hasMore.value) return
  loadOrderData(true)
}

/**
 * 获取订单状态文本
 */
const getStatusText = (status) => {
  switch (status) {
    case 3:
      return '待支付'
    case 5:
      return '已完成'
    case 7:
      return '已取消'
    default:
      return '未知状态'
  }
}

/**
 * 获取订单状态样式类
 */
const getStatusClass = (status) => {
  switch (status) {
    case 3:
      return 'status-pending'
    case 5:
      return 'status-completed'
    case 7:
      return 'status-cancelled'
    default:
      return ''
  }
}

/**
 * 处理支付
 */
const handlePayment = ({ id, total_amount }) => {
  onPay({
    id,
    remain_time: 1800, // 30分钟
    price: total_amount
  })
}

/**
 * 发送订单支付信息到支付组件
 * @param {Object} payInfo - 支付信息
 * @param {string} payInfo.id - 订单ID
 * @param {number} payInfo.remain_time - 剩余时间
 * @param {number} payInfo.price - 价格
 */
const onPay = ({ id, remain_time, price }) => {
  show_pay.value = true
  payData.value.id = id
  payData.value.price = price
  payData.value.remain_time = remain_time
}

/**
 * 关闭支付弹框
 */
const onPayClose = () => {
  show_pay.value = false
}

/**
 * 处理支付成功事件
 * @param {Object} data - 支付成功数据
 * @param {string} data.orderId - 订单ID
 */
const onPaySuccess = ({ orderId }) => {
  // 找到对应的订单并更新状态
  const orders = viewMode.value === 'buy' ? boughtOrders.value : soldOrders.value
  const order = orders.find(o => o.id === orderId)

  if (order) {
    // 更新订单状态为已完成
    order.status = 5

    Taro.showToast({
      title: '支付成功,订单已更新',
      icon: 'success',
      duration: 2000
    })
  }
}

/**
 * 查看订单详情
 */
const viewOrderDetail = async (orderId) => {
  // 找到对应的订单
  const orders = viewMode.value === 'buy' ? boughtOrders.value : soldOrders.value
  const order = orders.find(o => o.id === orderId)

  if (order) {
    const { code, data } = await getOrderDetailAPI({ id: orderId })
    if (code) {
      currentOrderDetail.value = { ...data, details: data.details[0] }
      showOrderDetailPopup.value = true
    }
  }
}

/**
 * 关闭订单详情弹窗
 */
const closeOrderDetailPopup = () => {
  showOrderDetailPopup.value = false
  currentOrderDetail.value = null
}

/**
 * 评价订单
 */
const rateOrder = (orderId) => {
  // 找到对应的订单
  const orders = viewMode.value === 'buy' ? boughtOrders.value : soldOrders.value
  const order = orders.find(o => o.id === orderId)

  if (order) {
    currentRateOrder.value = order

    // 检查是否已有评价
    if (order.details.review) {
      // 已评价,显示只读模式
      isReadOnlyMode.value = true
      rateContent.value = order.details.review.note
      rateScore.value = order.details.review.rating
    } else {
      // 未评价,显示编辑模式
      isReadOnlyMode.value = false
      rateContent.value = ''
      rateScore.value = 5
    }

    showRatePopup.value = true
  }
}

/**
 * 关闭评价弹窗
 */
const closeRatePopup = () => {
  showRatePopup.value = false
  currentRateOrder.value = null
  rateContent.value = ''
  rateScore.value = 5
  isReadOnlyMode.value = false
}

/**
 * 提交评价
 */
const submitRate = async () => {
  if (!rateContent.value.trim()) {
    Taro.showToast({
      title: '请输入评价内容',
      icon: 'error',
      duration: 2000
    })
    return
  }

  try {
    submittingRate.value = true

    const response = await reviewOrderAPI({
      detail_id: currentRateOrder.value.details.id,
      rating: rateScore.value,
      note: rateContent.value
    })
    if (response.code) {
      // API提交成功后的处理
      const currentOrders = viewMode.value === 'buy' ? boughtOrders : soldOrders
      const order = currentOrders.value.find(o => o.id === currentRateOrder.value.id)
      if (order) {
        // 创建评价数据对象
        const reviewData = {
          rating: rateScore.value,
          note: rateContent.value,
          created_time: new Date().toLocaleString('zh-CN')
        }
        
        // 同时更新order.review和order.details.review,确保状态一致
        order.review = reviewData
        if (order.details) {
          order.details.review = reviewData
        }
        
        // 确保订单状态为已完成
        order.status = 5
      }
      
      Taro.showToast({
        title: response.msg || '评价提交成功',
        icon: 'success',
        duration: 2000
      })
      
      closeRatePopup()
    } else {
      throw new Error(response.msg || '提交失败')
    }

  } catch (error) {
    console.error('提交评价失败:', error)
  } finally {
    submittingRate.value = false
  }
}

// 取消订单相关状态
const cancelingOrderId = ref('')

// 删除订单相关状态
const deletingOrderId = ref('')

/**
 * 确认弹窗显示状态
 */
const showConfirmModal = ref(false)

/**
 * 待删除的订单ID
 */
const pendingDeleteOrderId = ref('')

/**
 * 取消订单确认弹窗显示状态
 */
const showCancelConfirmModal = ref(false)

/**
 * 待取消的订单ID
 */
const pendingCancelOrderId = ref('')

/**
 * 取消订单
 * @param {string} orderId - 订单ID
 */
const handleCancelOrder = async (orderId) => {
  try {
    // 保存待取消的订单ID
    pendingCancelOrderId.value = orderId
    showCancelConfirmModal.value = true
  } catch (error) {
     // 用户取消操作或其他错误
     // console.log('取消订单操作被取消或出错:', error)
  }
}

/**
 * 执行取消订单操作
 * @param {string} orderId - 订单ID
 */
const performCancelOrder = async (orderId) => {
  // 关闭确认弹窗
  showCancelConfirmModal.value = false

  // 设置取消状态,用于显示加载效果
  cancelingOrderId.value = orderId

  try {
    // 调用取消订单API
    const response = await cancelOrderAPI({ id: orderId })

    if (response.code) {
      // API取消成功后的处理
      const orders = viewMode.value === 'buy' ? boughtOrders : soldOrders
      const order = orders.value.find(o => o.id === orderId)

      if (order) {
        // 更新订单状态为已取消
        order.status = 7

        Taro.showToast({
          title: '订单已取消',
          icon: 'success',
          duration: 2000
        })
      }
    } else {
      throw new Error(response.msg || '取消失败')
    }
  } catch (error) {
     // console.error('取消订单失败:', error)

    Taro.showToast({
      title: error.msg || '取消订单失败,请重试',
      icon: 'error',
      duration: 2000
    })
  } finally {
    // 清除取消状态
    cancelingOrderId.value = ''
    // 清除待取消订单ID
    pendingCancelOrderId.value = ''
  }
}

/**
 * 删除订单
 * @param {string} orderId - 订单ID
 */
const deleteOrder = async (orderId) => {
  try {
    // 保存待删除的订单ID
    pendingDeleteOrderId.value = orderId
    showConfirmModal.value = true
  } catch (error) {
     // 用户取消删除或其他错误
     // console.log('删除操作被取消或出错:', error)
  }
}

/**
 * 执行删除订单操作
 * @param {string} orderId - 订单ID
 */
const performDeleteOrder = async (orderId) => {
  // 关闭确认弹窗
  showConfirmModal.value = false

  // 设置删除状态,用于显示加载效果
  deletingOrderId.value = orderId

  try {
    // 调用删除订单API
    const response = await deleteOrderAPI({ id: orderId })

    if (response.code) {
      // API删除成功后的处理
      const orders = viewMode.value === 'buy' ? boughtOrders : soldOrders
      const orderIndex = orders.value.findIndex(order => order.id === orderId)

      if (orderIndex !== -1) {
        orders.value.splice(orderIndex, 1)

        Taro.showToast({
          title: response.msg || '订单删除成功',
          icon: 'success',
          duration: 2000
        })
      }
    } else {
      throw new Error(response.msg || '删除失败')
    }

  } catch (error) {
    // console.error('删除订单失败:', error)

    Taro.showToast({
      title: '删除订单失败',
      icon: 'error',
      duration: 2000
    })
  } finally {
    // 清除删除状态
    deletingOrderId.value = ''
    // 清除待删除订单ID
    pendingDeleteOrderId.value = ''
  }
}

// 页面加载时的初始化
onMounted(async () => {
  // 加载订单数据
  loadOrderData(false)

  // 设置滚动列表可视高度
  const windowHeight = wx.getWindowInfo().windowHeight;
  setTimeout(async () => {
    const headerHeight = await $('#mode-toggle').height();
    const navHeight = await $('#status-tabs').height();
    scrollStyle.value = {
      height: windowHeight - headerHeight - navHeight + 'px'
    }
  }, 500);
})
</script>

<script>
export default {
  name: "OrderManagementPage",
};
</script>