<script setup lang="ts">
import { orderState, orderStateActions, orderStateList, pageUrl } from '@/utils/constants'
import { deleteOrderApi, getOrderDetailByIdApi, putOrderCancelByIdApi } from '@/api/order'
import type { orderResult } from '@/types/order'
import { ref, computed } from 'vue'
import { fullUrl, getPayPageUrl, formatPrice, onShowRefreshData } from '@/utils/common'
import receiveButton from '@/pagesOrder/components/receiveButton.vue'
import cancelButton from '@/pagesOrder/components/cancelButton.vue'
import { safeBottom } from '@/utils/constants'

//订单详情
const detailData = ref<orderResult>()
const getDetailData = async () => {
  const res = await getOrderDetailByIdApi(orderId)
  detailData.value = res.result
}

// 复制内容
const onCopy = () => {
  // 设置系统剪贴板的内容
  uni.setClipboardData({ data: detailData.value!.order_no })
}
// 获取页面参数
const query = defineProps<{
  id: string
}>()

//订单ID
const orderId = Number(query.id)

//倒计时结束事件
const onTimeUp = () => {
  if (detailData.value?.status != orderState.canceled) {
    putOrderCancelByIdApi({
      id: detailData.value!.id,
      time_out: true,
    })
  }
  detailData.value!.status = orderState.canceled
}

//删除订单
const onDeleteOrder = () => {
  uni.showModal({
    title: '提示',
    content: '确定要删除订单吗',
    showCancel: true,
    success: async ({ confirm, cancel }) => {
      if (confirm) {
        await deleteOrderApi({
          id: [orderId],
        })
        uni.showToast({
          title: '删除成功',
          icon: 'success',
          mask: true,
        })
        setTimeout(() => {
          uni.redirectTo({ url: `${pageUrl['order-list']}` })
        }, 500)
      }
    },
  })
}

onShowRefreshData(() => {
  getDetailData()
}, true)

const showDelivery = computed(() => {
  return (
    [orderState.toReceived, orderState.toEvaluate, orderState.completed].includes(
      detailData.value!.status,
    ) && detailData.value!.delivery.length > 0
  )
})

const onCancel = () => {
  if (detailData.value?.pay_time) {
    detailData.value!.status = orderState.applyCancel
  } else {
    detailData.value!.status = orderState.canceled
  }
}
</script>

<template>
  <scroll-view scroll-y class="viewport" id="scroller">
    <template v-if="detailData">
      <!-- 订单状态 -->
      <view class="overview" :style="{ paddingTop: '30rpx' }">
        <!-- 待付款状态:展示去支付按钮和倒计时 -->
        <template v-if="detailData.status === orderState.toPay">
          <view class="status icon-clock">{{ orderStateList[detailData.status].text }}</view>
          <view class="tips">
            <view class="time">
              <view>还剩</view>
              <uni-countdown
                :second="detailData.countdown"
                @timeup.once="onTimeUp"
                color="#fff"
                splitor-color="#fff"
                :show-day="false"
                :show-colon="false"
              />
              <view>自动取消</view>
            </view>
          </view>
          <navigator
            class="button primary"
            :url="getPayPageUrl(orderId, detailData.pay_price)"
            hover-class="none"
          >
            去支付
          </navigator>
        </template>
        <!-- 其他订单状态:展示再次购买按钮 -->
        <template v-else>
          <!-- 订单状态文字 -->
          <view class="status"> {{ orderStateList[detailData.status].text }} </view>
        </template>
      </view>

      <view class="shipment" v-show="detailData.address">
        <view class="locate">
          <view class="user"> {{ detailData.address.name }} {{ detailData.address.phone }} </view>
          <view class="address">{{ detailData.address.full_address }} </view>
        </view>
        <!-- 配送状态 -->
        <view class="item" v-if="showDelivery">
          <view class="delivery-card">
            <template v-if="detailData.delivery.length > 1">
              <navigator
                class="delivery"
                :url="`${pageUrl['order-delivery']}?order_id=${orderId}`"
                hover-class="none"
              >
                <view v-if="detailData.status == orderState.toReceived" class="delivery-tip">
                  <text>订单拆分为 {{ detailData.delivery.length }} 个包裹发货</text>
                </view>
                <view v-else class="delivery-tip">
                  <text>订单拆分为多个包裹发货</text>
                  <text>已发货 {{ detailData.delivery.length }} 个包裹</text>
                </view>
                <view class="more">
                  <text class="icon-right"></text>
                </view>
              </navigator>
            </template>
            <template v-else>
              <navigator
                class="delivery"
                :url="`${pageUrl['order-delivery']}?order_id=${orderId}`"
                hover-class="none"
                v-for="(item, idx) in detailData.delivery"
                :key="idx"
              >
                <view class="delivery-info">
                  <view class="info-item">
                    <view class="item-label">物流公司</view>
                    <view class="item-content">
                      {{ item.delivery_company?.name || '无需物流' }}
                    </view>
                  </view>
                  <view class="info-item">
                    <view class="item-label">物流单号</view>
                    <view class="item-content">{{ item.delivery_no || '' }}</view>
                  </view>
                </view>
                <view class="more">
                  <text class="icon-right"></text>
                </view>
              </navigator>
            </template>
          </view>
        </view>
      </view>

      <!-- 商品信息 -->
      <view class="goods" v-if="detailData.detail.length > 0">
        <view class="item" v-for="detail in detailData.detail" :key="detail.id">
          <navigator
            class="navigator"
            :url="`${pageUrl['shopping-mall-goods-detail']}?id=${detail.goods_id}`"
            hover-class="none"
          >
            <view> <image class="cover" :src="fullUrl(detail.image)"></image> </view>
            <view class="meta">
              <view class="name ellipsis">{{ detail.goods_name }}</view>
              <view class="type">{{ detail.spec_text }}</view>
              <view class="price">
                <view class="actual">
                  <text class="symbol">¥</text>
                  <text>{{ detail.price }}</text>
                </view>
              </view>
              <view class="quantity">x{{ detail.num }}</view>
            </view>
          </navigator>

          <view class="operate">
            <view
              v-if="
                orderStateActions.evaluatable.includes(detailData.status) &&
                detail.evaluate_time <= 0
              "
            >
              <navigator
                :url="`${pageUrl['order-evaluate']}?detail_id=${detail.id}`"
                open-type="navigate"
                hover-class="navigator-hover"
                class="button"
              >
                去评价
              </navigator>
            </view>

            <view v-if="detail.apply_refund">
              <navigator
                :url="`${pageUrl['order-refund']}?order_id=${
                  detailData.id
                }&detail_data=${JSON.stringify(detail)}`"
                open-type="navigate"
                hover-class="navigator-hover"
                class="button"
              >
                申请售后
              </navigator>
            </view>
          </view>
        </view>
      </view>

      <view class="goods">
        <view class="total">
          <view class="row">
            <view class="text">商品总价</view>
            <view class="symbol">{{ formatPrice(detailData.total_price) }}</view>
          </view>
          <view class="row">
            <view class="text">商品运费</view>
            <view class="symbol">{{ formatPrice(detailData.freight) }}</view>
          </view>
          <view class="row">
            <view class="text">优惠折扣</view>
            <view class="symbol discount">
              {{ formatPrice(detailData.discount_data.coupon_discount) }}
            </view>
          </view>
          <view class="row">
            <view class="text">应付金额</view>
            <view class="symbol">{{ formatPrice(detailData.pay_price) }}</view>
          </view>
        </view>
      </view>

      <!-- 订单信息 -->
      <view class="detail">
        <view class="row">
          <view class="item">
            <view class="item-title"> 订单编号</view>
            <view>
              {{ detailData.order_no }}
              <text class="copy" @tap="onCopy">复制</text>
            </view>
          </view>
          <view class="item">
            <view class="item-title">下单时间</view>
            <view>{{ detailData.create_time }}</view>
          </view>
          <view class="item" v-if="detailData.pay_time">
            <view class="item-title">支付时间</view>
            <view> {{ detailData.pay_time }}</view>
          </view>
          <view class="item">
            <view class="item-title">买家留言</view>
            <view style="width: 80%">{{ detailData.remark || '--' }}</view>
          </view>
        </view>
      </view>

      <!-- 底部操作栏 -->
      <view class="toolbar-height" :style="safeBottom"></view>
      <view class="toolbar" :style="safeBottom">
        <!-- 待付款状态:展示支付按钮 -->
        <template v-if="detailData.status === orderState.toPay">
          <cancelButton
            :status="detailData.status"
            :id="detailData.id"
            className="button secondary"
            @cancel="onCancel"
          />
          <navigator
            class="button primary"
            :url="getPayPageUrl(detailData.id, detailData.pay_price)"
            hover-class="none"
          >
            去支付
          </navigator>
        </template>
        <!-- 其他订单状态:按需展示按钮 -->
        <template v-else>
          <view v-if="orderStateActions.deletable.includes(detailData.status)">
            <view class="button secondary" @tap="onDeleteOrder"> 删除订单 </view>
          </view>

          <cancelButton
            :status="detailData.status"
            :id="detailData.id"
            className="button secondary"
            @cancel="onCancel"
          />

          <receiveButton
            :status="detailData.status"
            :id="detailData.id"
            :payment-trade-info="detailData.payment_trade"
            className="button secondary"
          />

          <view v-if="orderStateActions.evaluatable.includes(detailData.status)">
            <navigator
              :url="`${pageUrl['order-evaluate']}?order_id=${orderId}`"
              class="button secondary"
              hover-class="none"
            >
              一键评价
            </navigator>
          </view>

          <navigator
            class="button primary"
            :url="`${pageUrl['order-create']}?orderId=${orderId}`"
            hover-class="none"
          >
            再次购买
          </navigator>
        </template>
      </view>
    </template>
  </scroll-view>
</template>

<style lang="scss" scoped>
page {
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
}

.card {
  display: flex;
  flex-direction: column;
  line-height: 1.6;
  padding: 20rpx;
  margin: 20rpx;
  border-radius: 30rpx;
  background-color: #fff;
}

.navbar {
  width: 750rpx;
  color: #000;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9;
  /* background-color: #f8f8f8; */
  background-color: transparent;

  .wrap {
    position: relative;

    .title {
      height: 44px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 32rpx;
      /* color: #000; */
      color: transparent;
    }

    .back {
      position: absolute;
      left: 0;
      height: 44px;
      width: 44px;
      font-size: 44rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      /* color: #000; */
      color: #fff;
    }
  }
}

.viewport {
  background-color: #f7f7f8;
}

.overview {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding-bottom: 35rpx;
  color: #fff;
  background-image: url('~@/static/images/bg.png');
  background-size: cover;

  .status {
    font-size: 36rpx;
  }

  .status::before {
    margin-right: 6rpx;
    font-weight: 500;
  }

  .tips {
    margin: 30rpx 0;
    display: flex;
    flex-direction: column;
    font-size: 14px;
    align-items: center;

    .money {
      margin-right: 30rpx;
    }

    .time {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 10rpx;
      padding-top: 10rpx;
    }
  }

  .button-group {
    margin-top: 30rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .button {
    width: 260rpx;
    height: 64rpx;
    margin: 0 10rpx;
    text-align: center;
    line-height: 64rpx;
    font-size: 28rpx;
    color: #ff5f3c;
    border-radius: 68rpx;
    background-color: #fff;
  }
}

.shipment {
  line-height: 1.4;
  padding: 0 20rpx;
  margin: 20rpx 20rpx 20rpx;
  border-radius: 30rpx;
  background-color: #fff;

  .locate,
  .item {
    // min-height: 120rpx;
    padding: 30rpx 30rpx 25rpx 75rpx;
    background-size: 50rpx;
    background-repeat: no-repeat;
    background-position: 6rpx center;
  }

  .locate {
    background-image: url('~@/static/images/locate.png');
    border-bottom: 1rpx solid #eee;

    .user {
      font-size: 26rpx;
      color: #444;
    }

    .address {
      font-size: 24rpx;
      color: #666;
    }
  }

  .item {
    background-image: url('~@/static/images/car.png');
    border-bottom: 1rpx solid #eee;
    position: relative;

    .message {
      font-size: 26rpx;
      color: #444;
    }

    .date {
      font-size: 24rpx;
      color: #666;
    }
  }

  .delivery {
    display: flex;
    align-items: center;

    .delivery-tip {
      font-size: 24rpx;
      display: flex;
      flex-direction: column;
    }

    .info-item {
      display: flex;
      font-size: 24rpx;
      padding-bottom: 10rpx;
    }

    .item-label {
      color: #999999;
      margin-right: 20rpx;
    }

    .item-content {
      font-size: 26rpx;
    }

    .more {
      margin-left: auto;
    }
  }
}

.goods {
  margin: 20rpx;
  padding: 0 20rpx;
  border-radius: 30rpx;
  background-color: #fff;

  .item {
    padding: 30rpx 0;
    border-bottom: 1rpx solid #eee;

    .navigator {
      display: flex;
      // margin: 20rpx 0;
    }

    .cover {
      width: 170rpx;
      height: 170rpx;
      border-radius: 10rpx;
      margin-right: 20rpx;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      position: relative;
    }

    .name {
      font-size: 26rpx;
      color: #444;
    }

    .type {
      line-height: 1.8;
      padding: 0 15rpx;
      margin-top: 6rpx;
      font-size: 24rpx;
      align-self: flex-start;
      border-radius: 4rpx;
      color: #888;
      background-color: #f7f7f8;
      max-width: 91%;
    }

    .price {
      display: flex;
      margin-top: 6rpx;
      font-size: 24rpx;
    }

    .symbol {
      font-size: 20rpx;
    }

    .original {
      color: #999;
      text-decoration: line-through;
    }

    .actual {
      margin-left: 10rpx;
      color: #444;
    }

    .text {
      font-size: 22rpx;
    }

    .operate {
      display: flex;
      align-items: center;
      flex-direction: row-reverse;

      .button {
        display: flex;
        justify-content: center;
        border-radius: 60rpx;
        height: 50rpx;
        width: 150rpx;
        align-items: center;
        border: 1rpx solid #ccc;
        color: #444;
        font-size: 20rpx;
        margin-left: 20rpx;
      }
    }

    .quantity {
      position: absolute;
      right: 0;
      font-size: 24rpx;
      color: #444;
    }

    .action {
      display: flex;
      flex-direction: row-reverse;
      justify-content: flex-start;
      padding: 30rpx 0 0;

      .button {
        width: 200rpx;
        height: 60rpx;
        text-align: center;
        justify-content: center;
        line-height: 60rpx;
        margin-left: 20rpx;
        border-radius: 60rpx;
        border: 1rpx solid #ccc;
        font-size: 26rpx;
        color: #444;
      }

      .primary {
        color: #ff5f3c;
        border-color: #ff5f3c;
      }
    }
  }

  .total {
    line-height: 1.4;
    font-size: 26rpx;
    padding: 20rpx 0;
    color: #666;

    .row {
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 10rpx 0;
    }

    .symbol::before {
      content: '¥';
      font-size: 80%;
      margin-right: 3rpx;
    }

    .discount::before {
      content: '- ¥';
      font-size: 80%;
      margin-right: 3rpx;
    }

    .primary {
      color: #cf4444;
      font-size: 36rpx;
    }
  }
}

.detail {
  line-height: 1.4;
  padding: 20rpx;
  margin: 20rpx;
  font-size: 26rpx;
  color: #666;
  border-radius: 30rpx;
  background-color: #fff;

  .title {
    font-size: 30rpx;
    color: #444;
  }

  .row {
    padding: 20rpx 0;

    .item {
      padding: 10rpx 0;
      display: flex;

      .item-title {
        margin-right: 30rpx;
      }
    }

    .copy {
      border-radius: 20rpx;
      font-size: 20rpx;
      border: 1px solid #ccc;
      padding: 5rpx 20rpx;
      margin-left: 10rpx;
    }
  }
}

.toolbar-height {
  height: 100rpx;
  box-sizing: content-box;
}

.toolbar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: calc(var(--window-bottom));
  z-index: 1;

  height: 100rpx;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  flex-direction: row;
  justify-content: flex-end;
  border-top: 1rpx solid #ededed;
  border-bottom: 1rpx solid #ededed;
  background-color: #fff;
  box-sizing: content-box;

  .button {
    display: flex;
    justify-content: center;
    align-items: center;

    width: 150rpx;
    height: 60rpx;
    margin-left: 15rpx;
    font-size: 26rpx;
    border-radius: 72rpx;
    border: 1rpx solid #ccc;
    color: #444;
  }

  .delete {
    order: 4;
  }

  .button {
    order: 3;
  }

  .secondary {
    order: 2;
    color: #ff5f3c;
    border-color: #ff5f3c;
  }

  .primary {
    order: 1;
    color: #fff;
    background-color: #ff5f3c;
  }
}
</style>
