<template>
  <view class="sp-order-page">
    <view class="sp-tabs">
      <view
        v-for="tab in tabs"
        :key="tab.key"
        class="sp-tab"
        :class="{ 'sp-tab--on': activeTab === tab.key }"
        @tap="switchTab(tab.key)"
      >
        <text class="sp-tab__txt">{{ tab.label }}</text>
      </view>
    </view>

    <scroll-view
      scroll-y
      class="sp-order-scroll"
      enable-back-to-top
      :show-scrollbar="false"
      @scrolltolower="loadMore"
    >
      <view v-if="loading && !rows.length" class="sp-empty">
        <text class="sp-empty__txt">加载中…</text>
      </view>
      <view v-else-if="!rows.length" class="sp-empty">
        <text class="sp-empty__txt">暂无订单</text>
      </view>
      <view v-else class="sp-order-list">
        <view
          v-for="item in rows"
          :key="item._key"
          class="sp-order-card"
          @tap="openDetail(item)"
        >
          <view class="sp-order-card__head">
            <text class="sp-order-card__no">订单编号 {{ item.displayNo }}</text>
            <text class="sp-order-card__status" :class="item.statusClass">{{ item.statusName }}</text>
          </view>
          <view class="sp-order-card__body">
            <view class="sp-order-card__thumb">
              <text class="sp-order-card__thumb-txt">牦</text>
            </view>
            <view class="sp-order-card__info">
              <text class="sp-order-card__line">承销商：{{ item.partnerName }}</text>
              <text class="sp-order-card__line">订单支付时间：{{ item.payTime }}</text>
              <text class="sp-order-card__line">订单结算时间：{{ item.settleTime }}</text>
            </view>
          </view>
          <view class="sp-order-card__foot">
            <text class="sp-order-card__amount">订单合计：{{ item.amountText }}</text>
            <text class="sp-order-card__heads">共 {{ item.totalHeads || 0 }} 头牦牛</text>
          </view>
        </view>
      </view>
      <view v-if="rows.length && (loadingMore || noMore)" class="sp-list-foot">
        <text class="sp-list-foot__txt">{{ loadingMore ? '加载中…' : '没有更多了' }}</text>
      </view>
      <view class="sp-footer-spacer" />
    </scroll-view>
  </view>
</template>

<script>
import { listSupplierOrders, listSupplierSettlements } from '@/api/supplier/order'
import { DASH, formatCurrency, formatDateTime } from '@/utils/format'

const TABS = [
  { key: 'ALL', label: '全部订单' },
  { key: 'PENDING', label: '待支付' },
  { key: 'SETTLEMENT', label: '待结算' },
  { key: 'COMPLETED', label: '已完成' }
]

export default {
  data() {
    return {
      tabs: TABS,
      activeTab: 'ALL',
      rows: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      loadingMore: false
    }
  },
  computed: {
    noMore() {
      return this.rows.length > 0 && this.rows.length >= this.total
    }
  },
  methods: {
    /** Tab 页 onShow 时刷新列表 */
    reload() {
      this.reloadList()
    },
    switchTab(key) {
      if (this.activeTab === key) return
      this.activeTab = key
      this.reloadList()
    },
    reloadList() {
      this.pageNum = 1
      this.rows = []
      this.total = 0
      this.fetchList(true)
    },
    loadMore() {
      if (this.loading || this.loadingMore || this.noMore) return
      this.pageNum += 1
      this.fetchList(false)
    },
    fetchList(reset) {
      if (reset) {
        this.loading = true
      } else {
        this.loadingMore = true
      }
      const params = { pageNum: this.pageNum, pageSize: this.pageSize }
      const req = this.activeTab === 'SETTLEMENT'
        ? listSupplierSettlements(params)
        : listSupplierOrders({ ...params, statusTab: this.activeTab })

      req
        .then((res) => {
          const list = (res.rows || []).map((row) => this.mapRow(row))
          this.total = res.total != null ? Number(res.total) : 0
          this.rows = reset ? list : this.rows.concat(list)
        })
        .catch(() => {
          if (reset) {
            this.rows = []
            this.total = 0
          } else {
            this.pageNum -= 1
          }
        })
        .finally(() => {
          this.loading = false
          this.loadingMore = false
        })
    },
    mapRow(row) {
      const isSettlement = this.activeTab === 'SETTLEMENT'
      const statusName = isSettlement
        ? (row.settlementStatusName || '待结算')
        : (row.orderStatusName || DASH)
      const statusClass = this.resolveStatusClass(statusName)
      return {
        _key: `${isSettlement ? 's' : 'o'}-${row.id}`,
        id: row.id,
        kind: isSettlement ? 'settlement' : 'order',
        displayNo: isSettlement ? (row.settlementNo || row.orderNo) : row.orderNo,
        statusName,
        statusClass,
        partnerName: row.distributorName || DASH,
        payTime: formatDateTime(row.finishTime),
        settleTime: formatDateTime(row.settleFinishTime),
        amountText: formatCurrency(row.totalAmount),
        totalHeads: row.totalHeads
      }
    },
    resolveStatusClass(name) {
      const text = String(name || '')
      if (text.includes('完成')) return 'sp-order-card__status--done'
      if (text.includes('待')) return 'sp-order-card__status--pending'
      return ''
    },
    openDetail(item) {
      uni.navigateTo({
        url: `/pages/supplier/order-detail/index?kind=${item.kind}&id=${item.id}`
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/morandi.scss';
@import '@/styles/scroll-fill.scss';

.sp-order-page {
  @include tab-panel-root;
  background: $morandi-bg-page;
}

.sp-tabs {
  display: flex;
  flex-direction: row;
  background: #ffffff;
  border-bottom: 1rpx solid $morandi-border-soft;
  flex-shrink: 0;
}

.sp-tab {
  flex: 1;
  min-width: 0;
  padding: 24rpx 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-bottom: 4rpx solid transparent;
}

.sp-tab--on {
  border-bottom-color: #3b82f6;
}

.sp-tab__txt {
  font-size: 26rpx;
  color: $morandi-text-secondary;
}

.sp-tab--on .sp-tab__txt {
  color: #2563eb;
  font-weight: 600;
}

.sp-order-scroll {
  @include flex-scroll-y;
}

.sp-order-list {
  padding: 16rpx 24rpx 0;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.sp-order-card {
  padding: 24rpx;
  border-radius: 16rpx;
  background: $morandi-bg-card;
  border: 1rpx solid $morandi-border-soft;
  box-sizing: border-box;
}

.sp-order-card__head {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  gap: 16rpx;
  margin-bottom: 20rpx;
}

.sp-order-card__no {
  flex: 1;
  min-width: 0;
  font-size: 26rpx;
  color: $morandi-text;
  word-break: break-all;
}

.sp-order-card__status {
  flex-shrink: 0;
  font-size: 26rpx;
  color: $morandi-text-secondary;
}

.sp-order-card__status--pending {
  color: #ea580c;
}

.sp-order-card__status--done {
  color: #16a34a;
}

.sp-order-card__body {
  display: flex;
  flex-direction: row;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.sp-order-card__thumb {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  background: #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.sp-order-card__thumb-txt {
  font-size: 40rpx;
  font-weight: 700;
  color: #6b7280;
}

.sp-order-card__info {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.sp-order-card__line {
  font-size: 24rpx;
  color: $morandi-text-secondary;
  line-height: 1.45;
}

.sp-order-card__foot {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  gap: 16rpx;
  padding-top: 16rpx;
  border-top: 1rpx solid $morandi-border-soft;
}

.sp-order-card__amount {
  font-size: 28rpx;
  font-weight: 600;
  color: #dc2626;
}

.sp-order-card__heads {
  font-size: 24rpx;
  color: $morandi-text-muted;
}

.sp-empty,
.sp-list-foot {
  padding: 48rpx 24rpx;
  text-align: center;
}

.sp-empty__txt,
.sp-list-foot__txt {
  font-size: 26rpx;
  color: $morandi-text-muted;
}

.sp-footer-spacer {
  height: 40rpx;
}
</style>
