<template>
  <view class="container">
    <!-- 头部菜单 -->
    <view class="order-tit">
      <!-- 动态生成订单状态标签，点击切换显示不同状态的订单列表 -->
      <text v-for="(status, index) in statuses"
            :key="index"
            :data-sts="status.value"
            :class="sts === status.value ? 'on' : ''"
            @tap="onStsTap">
        {{ status.label }}
      </text>
    </view>
    <!-- end 头部菜单 -->

    <view class="main">
      <!-- 如果订单列表为空，则显示提示信息 -->
      <view v-if="list.length === 0" class="empty">
        还没有任何相关订单
      </view>

      <!-- 订单列表 -->
      <block v-for="(item, index) in list" :key="index">
        <view class="prod-item">
          <!-- 订单编号和状态 -->
          <view class="order-num">
            <text>订单编号：{{ item.orderNumber }}</text>
            <view class="order-state">
              <!-- 根据订单状态动态设置文本颜色，并显示相应的状态 -->
              <text :class="[
                  'order-sts',
                  item.status === 1 ? 'red' : '',
                  (item.status === 5 || item.status === 6) ? 'gray' : ''
                ]">
                {{
                  getStatusLabel(item.status)
                }}
              </text>

              <!-- 已完成或已取消的订单显示清除按钮 -->
              <view v-if="item.status === 5 || item.status === 6"
                    class="clear-btn">
                <image src="@/static/images/icon/clear-his.png"
                       class="clear-list-btn"
                       :data-ordernum="item.orderNumber"
                       @tap="delOrderList" />
              </view>
            </view>
          </view>

          <!-- 商品列表 -->
          <!-- 单个商品时直接显示商品详情 -->
          <block v-if="item.orderItemDtos.length === 1">
            <block v-for="(prod, index2) in item.orderItemDtos" :key="index2">
              <view>
                <view class="item-cont"
                      :data-ordernum="item.orderNumber"
                      @tap="toOrderDetailPage">
                  <view class="prod-pic">
                    <image :src="prod.pic" />
                  </view>
                  <view class="prod-info">
                    <view class="prodname">{{ prod.prodName }}</view>
                    <view class="prod-info-cont">{{ prod.skuName }}</view>
                    <view class="price-nums">
                      <text class="prodprice">
                        <text class="symbol">￥</text>
                        <text class="big-num">{{ wxs.parsePrice(prod.price)[0] }}</text>
                        <text class="small-num">.{{ wxs.parsePrice(prod.price)[1] }}</text>
                      </text>
                      <text class="prodcount">x{{ prod.prodCount }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </block>
          </block>
          <!-- 多个商品时使用横向滚动视图展示所有商品图片 -->
          <block v-else>
            <view class="item-cont"
                  :data-ordernum="item.orderNumber"
                  @tap="toOrderDetailPage">
              <scroll-view scroll-x="true"
                           scroll-left="0"
                           scroll-with-animation="false"
                           class="categories">
                <block v-for="(prod, index2) in item.orderItemDtos" :key="index2">
                  <view class="prod-pic">
                    <image :src="prod.pic" />
                  </view>
                </block>
              </scroll-view>
            </view>
          </block>

          <!-- 显示订单总价 -->
          <view class="total-num">
            <text class="prodcount">共1件商品</text>
            <view class="prodprice">
              合计：
              <text class="symbol">￥</text>
              <text class="big-num">{{ wxs.parsePrice(item.actualTotal)[0] }}</text>
              <text class="small-num">.{{ wxs.parsePrice(item.actualTotal)[1] }}</text>
            </view>
          </view>

          <!-- 操作按钮 -->
          <view class="prod-foot">
            <view class="btn">
              <!-- 根据订单状态显示不同的操作按钮 -->
              <text v-if="item.status === 1"
                    class="button"
                    :data-ordernum="item.orderNumber"
                    hover-class="none"
                    @tap="onCancelOrder">
                取消订单
              </text>
              <text v-if="item.status === 1"
                    class="button warn"
                    :data-ordernum="item.orderNumber"
                    hover-class="none"
                    @tap="normalPay">
                付款
              </text>
              <text v-if="item.status === 3 || item.status === 5"
                    class="button"
                    :data-ordernum="item.orderNumber"
                    hover-class="none"
                    @tap="toDeliveryPage">
                查看物流
              </text>
              <text v-if="item.status === 3"
                    class="button warn"
                    :data-ordernum="item.orderNumber"
                    hover-class="none"
                    @tap="onConfirmReceive">
                确认收货
              </text>
            </view>
          </view>
        </view>
      </block>
    </view>
  </view>
</template>

<script setup>
  import { ref, onMounted, onReachBottom } from 'vue'
  import { onLoad } from '@dcloudio/uni-app'
  import http from '@/utils/http'
  import number from '@/wxs/number.wxs'

  // 定义订单状态选项
  const statuses = [
    { label: '全部', value: 0 },
    { label: '待支付', value: 1 },
    { label: '待发货', value: 2 },
    { label: '待收货', value: 3 },
    { label: '已完成', value: 5 }
  ]

  // 当前选中的订单状态
  const sts = ref(0)

  // 页面加载时处理函数
  onLoad((options) => {
    if (options.sts) {
      sts.value = parseInt(options.sts)
    }
    loadOrderData(sts.value, 1)
  })

  // 分页参数
  const current = ref(1)
  const pages = ref(0)

  // 订单列表数据
  const list = ref([])

  // 加载订单数据
  const loadOrderData = (status, currentPage) => {
    uni.showLoading() // 显示加载中提示
    http.request({
      url: '/p/myOrder/myOrder',
      method: 'GET',
      data: {
        current: currentPage,
        size: 10,
        status: status
      }
    })
      .then(({ data }) => {
        // 更新订单列表数据
        let listParam = []
        if (currentPage === 1) {
          listParam = data.records
        } else {
          listParam = list.value
          Array.prototype.push.apply(listParam, data.records)
        }
        list.value = listParam
        pages.value = data.pages
        current.value = currentPage
        uni.hideLoading() // 隐藏加载中提示
      })
  }

  // 状态点击事件
  const onStsTap = (e) => {
    const selectedStatus = e.currentTarget.dataset.sts
    sts.value = parseInt(selectedStatus)
    loadOrderData(sts.value, 1)
  }

  // 获取订单状态标签
  const getStatusLabel = (status) => {
    return statuses.find(s => s.value === status)?.label || '未知状态'
  }

  // 查看物流
  const toDeliveryPage = (e) => {
    uni.navigateTo({
      url: `/pages/express-delivery/express-delivery?orderNum=${e.currentTarget.dataset.ordernum}`
    })
  }

  // 取消订单
  const onCancelOrder = (e) => {
    const ordernum = e.currentTarget.dataset.ordernum
    uni.showModal({
      title: '',
      content: '要取消此订单？',
      confirmColor: '#3e62ad',
      cancelColor: '#3e62ad',
      cancelText: '否',
      confirmText: '是',

      success(res) {
        if (res.confirm) {
          uni.showLoading({ mask: true })
          http.request({
            url: `/p/myOrder/cancel/${ordernum}`,
            method: 'PUT'
          })
            .then(() => {
              loadOrderData(sts.value, 1)
              uni.hideLoading()
            })
        }
      }
    })
  }

  // 模拟支付，直接提交成功
  const normalPay = (e) => {
    uni.showLoading({ mask: true })
    http.request({
      url: '/p/order/normalPay',
      method: 'POST',
      data: {
        orderNumbers: e.currentTarget.dataset.ordernum
      }
    })
      .then(({ data }) => {
        uni.hideLoading()
        if (data) {
          uni.showToast({
            title: '模拟支付成功',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateTo({
              url: `/pages/pay-result/pay-result?sts=1&orderNumbers=${e.currentTarget.dataset.ordernum}`
            })
          }, 1200)
        } else {
          uni.showToast({
            title: '支付失败！',
            icon: 'none'
          })
        }
      })
  }

  // 查看订单详情
  const toOrderDetailPage = (e) => {
    uni.navigateTo({
      url: `/pages/order-detail/order-detail?orderNum=${e.currentTarget.dataset.ordernum}`
    })
  }

  // 确认收货
  const onConfirmReceive = (e) => {
    uni.showModal({
      title: '',
      content: '我已收到货？',
      confirmColor: '#eb2444',

      success(res) {
        if (res.confirm) {
          uni.showLoading({ mask: true })
          http.request({
            url: `/p/myOrder/receipt/${e.currentTarget.dataset.ordernum}`,
            method: 'PUT'
          })
            .then(() => {
              loadOrderData(sts.value, 1)
              uni.hideLoading()
            })
        }
      }
    })
  }

  // 删除已完成或已取消的订单
  const delOrderList = (e) => {
    uni.showModal({
      title: '',
      content: '确定要删除此订单吗？',
      confirmColor: '#eb2444',

      success(res) {
        if (res.confirm) {
          const ordernum = e.currentTarget.dataset.ordernum
          uni.showLoading()

          http.request({
            url: `/p/myOrder/${ordernum}`,
            method: 'DELETE'
          })
            .then(() => {
              loadOrderData(sts.value, 1)
              uni.hideLoading()
            })
        }
      }
    })
  }
</script>

<style scoped lang="scss">
  @use './orderList.scss';
</style>
