<script setup lang="ts">
import { deleteOrderApi, getOrderListApi } from '@/api/order'
import type { orderListResult } from '@/types/order'
import { ref, watch } from 'vue'
import {
  orderState,
  orderStateList,
  orderType,
  orderStateActions,
  refundStateList,
  pageUrl,
} from '@/utils/constants'
import { fullUrl, getPayPageUrl } from '@/utils/common'
import { onShow } from '@dcloudio/uni-app'
import cancelButton from '@/pagesOrder/components/cancelButton.vue'
import { usePopupStore } from '@/stores'
import ReceiveButton from '@/pagesOrder/components/receiveButton.vue'

// eslint-disable-next-line no-undef
const paging = ref<ZPagingInstance>()
const dataList = ref<orderListResult[]>([])
// 当前组件是否已经加载过了
const firstLoaded = ref(false)
// 是否滚动到当前页
const isCurrentPage = ref(false)

const props = withDefaults(
  defineProps<{
    tabIndex: number
    currentIndex: number
    status: string
  }>(),
  {
    tableIndex: 0,
    currentIndex: 0,
    status: '',
  },
)
const queryList = (page: number, page_size: number) => {
  const params = {
    page,
    page_size,
    type: orderType.default,
    status: props.status,
  }
  getOrderListApi(params).then((res) => {
    res.result.data.map((item) => {
      if (item.status == orderState.toPay && item.countdown < 0) {
        item.status = orderState.canceled
      }
    })
    paging.value?.complete(res.result.data)
  })
}

// 删除订单
const onDeleteOrder = (id: number) => {
  uni.showModal({
    content: '确定要删除订单吗？',
    cancelText: '取消',
    confirmText: '确定',
    success: (res) => {
      if (res.confirm) {
        deleteOrderApi({
          id: [id],
        }).then(() => {
          uni.showToast({
            title: '删除成功',
            icon: 'success',
          })
          setTimeout(() => {
            paging.value?.refresh()
          }, 1000)
        })
      }
    },
  })
}

const onCancel = (event: { orderId: number; reason: string }) => {
  const index = dataList.value.findIndex((v) => v.id == event.orderId)
  if (index > -1) {
    dataList.value.splice(index, 1)
  }
}

watch(
  () => props.currentIndex,
  (newVal) => {
    if (newVal === props.tabIndex) {
      // 懒加载，当滑动到当前的item时，才去加载
      if (!firstLoaded.value) {
        // 这里需要延迟渲染z-paging的原因是为了避免在一些平台上立即渲染可能引发的底层报错问题
        setTimeout(() => {
          isCurrentPage.value = true
        }, 100)
      }
    }
  },
  {
    immediate: true,
  },
)

onShow(() => {
  if (props.currentIndex === props.tabIndex) {
    paging.value?.refresh()
  }
})

const backToTop = ref(true)
watch(
  () => usePopupStore().show,
  (newVal) => {
    backToTop.value = !newVal
  },
  { immediate: true },
)
</script>

<!-- 在这个文件对每个tab对应的列表进行渲染 -->
<template>
  <view class="content">
    <!-- 如果当前页已经加载过数据或者当前切换到的tab是当前页，才展示当前页数据（懒加载） -->
    <z-paging
      :enable-back-to-top="currentIndex === tabIndex"
      v-if="firstLoaded || isCurrentPage"
      ref="paging"
      v-model="dataList"
      @query="queryList"
      :fixed="false"
      :auto-show-back-to-top="backToTop"
      :back-to-top-style="{
        display: backToTop ? '' : 'none',
      }"
      bg-color="#f6f6f6"
    >
      <view class="orders" v-for="(item, index) in dataList" :key="index">
        <view class="card">
          <view class="status">
            <text class="date">{{ item.create_time }}</text>
            <text v-if="item.status === orderState.applyCancel">
              {{ refundStateList.find((v) => v.id == item.refund_status)?.text ?? '' }}
            </text>
            <text v-else>{{ orderStateList[item.status].text ?? '' }}</text>
            <text
              class="icon-delete"
              v-show="orderStateActions.deletable.includes(item.status)"
              @tap="onDeleteOrder(item.id)"
            />
          </view>

          <navigator
            v-for="sku in item.detail"
            :key="sku.id"
            class="goods"
            :url="`${pageUrl['order-detail']}?id=${item.id}`"
            hover-class="none"
          >
            <image class="cover" :src="fullUrl(sku.image)"></image>

            <view class="meta">
              <view class="name ellipsis">{{ sku.goods_name }}</view>
              <view class="name meta-spec">{{ sku.spec }}</view>
              <view class="meta-quantity">x{{ sku.num }}</view>
            </view>
          </navigator>

          <view class="payment">
            <text class="quantity">共{{ item.total_num }}件商品</text>
            <text v-if="orderStateActions.normalTransaction.includes(item.status)">实付</text>
            <text v-else>应付</text>
            <text class="amount"> <text class="symbol">¥</text>{{ item.pay_price }}</text>
          </view>

          <view class="action">
            <template v-if="item.status === orderState.toPay && item.countdown > 0">
              <text class="pay-time">支付剩余</text>
              <countdown-timer :time="item.countdown * 1000" :autoStart="true">
                <template v-slot="{ day, hour, minute, second }">
                  <view v-if="item.countdown > 86400">{{ day }}天{{ hour }}时{{ minute }}分</view>
                  <view v-else-if="item.countdown < 60">{{ second }}秒</view>
                  <view v-else>{{ hour }}时{{ minute }}分</view>
                </template>
              </countdown-timer>
              <cancelButton
                :status="item.status"
                :id="item.id"
                className="button secondary"
                @cancel="onCancel"
              />
              <navigator
                class="button primary"
                :url="getPayPageUrl(item.id, item.pay_price)"
                hover-class="none"
              >
                去支付
              </navigator>
            </template>
            <template v-else>
              <cancelButton
                :status="item.status"
                :id="item.id"
                className="button secondary"
                @cancel="onCancel"
              />

              <ReceiveButton
                :status="item.status"
                :id="item.id"
                :paymentTradeInfo="item.payment_trade"
                className="button secondary"
              />

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

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

<style scoped lang="scss">
/* 注意:父节点需要固定高度，z-paging的height:100%才会生效 */
.content {
  height: 100%;
}
page {
  background-color: #f6f6f6;
}
.orders {
  display: flex;
  flex-direction: column;
  background-color: #f6f6f6;

  .card {
    min-height: 100rpx;
    padding: 20rpx;
    margin: 20rpx;
    border-radius: 10rpx;
    background-color: #fff;

    &:last-child {
      padding-bottom: 40rpx;
    }
  }

  .status {
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 28rpx;
    color: #999;
    margin-bottom: 15rpx;

    .date {
      color: #666;
      flex: 1;
    }

    .primary {
      color: #ff9240;
    }

    .icon-delete {
      line-height: 1;
      margin-left: 10rpx;
      padding-left: 10rpx;
      border-left: 1rpx solid #e3e3e3;
    }
  }

  .goods {
    display: flex;
    margin-bottom: 20rpx;

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

    .quantity {
      position: absolute;
      bottom: 0;
      right: 0;
      line-height: 1;
      padding: 6rpx 4rpx 6rpx 8rpx;
      font-size: 24rpx;
      color: #fff;
      border-radius: 10rpx 0 0 0;
      background-color: rgba(0, 0, 0, 0.6);
    }

    .name {
      font-size: 26rpx;
      color: #444;
      max-width: 90%;
    }

    .meta {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;

      .meta-spec {
        font-size: 24rpx;
        color: #999;
        margin-top: 10rpx;
      }

      &-quantity {
        position: absolute;
        right: 20px;
        font-size: 24rpx;
        color: #9e9c9c;
      }
    }

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

    .more {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 22rpx;
      color: #333;
    }
  }

  .payment {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    line-height: 1;
    padding: 20rpx 0;
    text-align: right;
    color: #999;
    font-size: 28rpx;
    border-bottom: 1rpx solid #eee;

    .quantity {
      font-size: 24rpx;
      margin-right: 16rpx;
    }

    .amount {
      color: #444;
      margin-left: 6rpx;
    }

    .symbol {
      font-size: 20rpx;
    }
  }

  .action {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-top: 20rpx;

    .pay-time {
      font-size: 24rpx;
      color: #999;
      margin-right: 20rpx;
    }

    .countdown {
      font-size: 24rpx;
      color: #999;
      margin-left: auto;
      display: flex;
    }

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

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

    .primary {
      color: #fff;
      background-color: #ff5f3c;
    }
  }

  .loading-text {
    text-align: center;
    font-size: 28rpx;
    color: #666;
    padding: 20rpx 0;
  }
}
</style>
