<template>
  <scroll-view scroll-y class="sp-scroll" enable-back-to-top :show-scrollbar="false">
    <view class="sp-section">
      <view class="sp-section__head">
        <text class="sp-section__title">交易数据</text>
        <view class="sp-range-tabs">
          <view
            v-for="tab in rangeTabs"
            :key="tab.value"
            class="sp-range-tab"
            :class="{ 'sp-range-tab--on': activeRange === tab.value }"
            @tap="switchRange(tab.value)"
          >
            <text class="sp-range-tab__txt">{{ tab.label }}</text>
          </view>
        </view>
      </view>

      <view v-if="loading" class="sp-loading">
        <text class="sp-loading__txt">加载中…</text>
      </view>
      <view v-else class="sp-metrics">
        <view v-for="item in metricCards" :key="item.key" class="sp-metric">
          <text class="sp-metric__label">{{ item.label }}</text>
          <text class="sp-metric__value">{{ item.value }}</text>
        </view>
      </view>
    </view>

    <view class="sp-section sp-section--chart">
      <view class="sp-section__head sp-section__head--chart">
        <text class="sp-section__title">交易金额</text>
        <text class="sp-updated">更新时间：{{ updatedAt }}</text>
      </view>
      <view class="sp-chart-host">
        <mpvueEcharts
          ref="amountChart"
          :onInit="onChartInit"
          canvasId="supplierHomeAmount"
          :disableTouch="true"
        />
      </view>
    </view>

    <view class="sp-section">
      <text class="sp-section__title sp-section__title--block">实时牦牛状态</text>
      <view class="sp-yak-row">
        <view v-for="item in yakStatusItems" :key="item.key" class="sp-yak-col">
          <text class="sp-yak-col__num">{{ item.value }}</text>
          <text class="sp-yak-col__label">{{ item.label }}</text>
        </view>
      </view>
    </view>

    <view class="sp-footer-spacer" />
  </scroll-view>
</template>

<script>
import * as echarts from '@/uni_modules/mpvue-echarts/components/echarts.esm.min.js'
import mpvueEcharts from '@/uni_modules/mpvue-echarts/components/echarts.vue'
import { getSupplierDashboard } from '@/api/supplier/home'
import { DASH, formatCount, formatWanAmount, formatYuanAmount, toWanNumber } from '@/utils/format'
import { clearHomeRealtimePoll, syncHomeRealtimePoll } from '@/utils/homeRealtimePoll'

const RANGE_TABS = [
  { label: '实时', value: 'TODAY' },
  { label: '昨日', value: 'YESTERDAY' },
  { label: '7日', value: 'DAYS_7' },
  { label: '30日', value: 'DAYS_30' }
]

export default {
  components: { mpvueEcharts },
  data() {
    return {
      rangeTabs: RANGE_TABS,
      activeRange: 'TODAY',
      loading: false,
      updatedAt: DASH,
      tradeSummary: {},
      settlementSummary: {},
      amountTrend: [],
      yakStatus: {},
      trendGranularity: 'HOUR'
    }
  },
  computed: {
    metricCards() {
      const t = this.tradeSummary || {}
      const s = this.settlementSummary || {}
      return [
        { key: 'totalAmount', label: '交易金额', value: formatWanAmount(t.totalAmount) },
        { key: 'orderCount', label: '交易订单数', value: formatCount(t.orderCount, '笔') },
        { key: 'payingBuyerCount', label: '支付买家数', value: formatCount(t.payingBuyerCount, '个') },
        { key: 'totalHeads', label: '交易牦牛数', value: formatCount(t.totalHeads, '头') },
        { key: 'payableAmount', label: '结算金额', value: formatWanAmount(s.payableAmount) },
        { key: 'serviceFeeAmount', label: '服务费金额', value: formatYuanAmount(s.serviceFeeAmount) }
      ]
    },
    yakStatusItems() {
      const y = this.yakStatus || {}
      return [
        { key: 'tradedHeads', label: '已交易', value: y.tradedHeads != null ? y.tradedHeads : DASH },
        { key: 'isolationEarTags', label: '隔离中', value: y.isolationEarTags != null ? y.isolationEarTags : DASH },
        { key: 'enteredPenEarTags', label: '已进栏', value: y.enteredPenEarTags != null ? y.enteredPenEarTags : DASH },
        { key: 'pendingPayHeads', label: '待支付', value: y.pendingPayHeads != null ? y.pendingPayHeads : DASH }
      ]
    }
  },
  beforeDestroy() {
    clearHomeRealtimePoll(this)
  },
  methods: {
    /** Tab 页 onShow 时刷新数据 */
    reload() {
      this.loadDashboard()
      this.syncRealtimePoll()
    },
    /** Tab 页 onHide 时停止轮询 */
    stopRealtimePoll() {
      clearHomeRealtimePoll(this)
    },
    syncRealtimePoll() {
      syncHomeRealtimePoll(this, () => this.loadDashboard(true))
    },
    switchRange(range) {
      if (this.activeRange === range) return
      this.activeRange = range
      this.loadDashboard()
      this.syncRealtimePoll()
    },
    loadDashboard(silent = false) {
      if (!silent) {
        this.loading = true
      }
      getSupplierDashboard(this.activeRange)
        .then((res) => {
          const d = res.data || {}
          this.updatedAt = d.updatedAt || DASH
          this.tradeSummary = d.tradeSummary || {}
          this.settlementSummary = d.settlementSummary || {}
          this.amountTrend = d.amountTrend || []
          this.yakStatus = d.yakStatus || {}
          this.trendGranularity = d.trendGranularity || 'HOUR'
          this.refreshChart()
        })
        .catch(() => {
          this.tradeSummary = {}
          this.settlementSummary = {}
          this.amountTrend = []
          this.yakStatus = {}
          this.refreshChart()
        })
        .finally(() => {
          if (!silent) {
            this.loading = false
          }
        })
    },
    refreshChart() {
      this.$nextTick(() => {
        const inst = this.$refs.amountChart
        if (inst && inst.chart) {
          inst.chart.setOption(this.buildChartOption(), true)
        }
      })
    },
    onChartInit(canvas, width, height) {
      const chart = echarts.init(canvas, null, { width, height })
      canvas.setChart(chart)
      chart.setOption(this.buildChartOption())
      return chart
    },
    buildChartOption() {
      const trend = this.amountTrend || []
      const labels = trend.map((p) => p.bucketLabel || '')
      const values = trend.map((p) => toWanNumber(p.amount))
      const rotate = labels.length > 8 ? 30 : 0
      return {
        animation: false,
        backgroundColor: '#f0f6fb',
        color: ['#3b82f6'],
        grid: { left: 10, right: 14, top: 28, bottom: 10, containLabel: true },
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const p = params && params[0]
            if (!p) return ''
            const raw = trend[p.dataIndex]
            const amt = raw && raw.amount != null ? Number(raw.amount).toFixed(2) : '0'
            return `${p.name}<br/>${amt} 元`
          }
        },
        xAxis: [{
          type: 'category',
          data: labels,
          boundaryGap: false,
          axisLine: { lineStyle: { color: '#cbd5e1' } },
          axisLabel: { color: '#64748b', fontSize: 10, rotate }
        }],
        yAxis: [{
          type: 'value',
          name: '万元',
          nameTextStyle: { color: '#64748b', fontSize: 10 },
          splitLine: { lineStyle: { color: '#e2e8f0' } },
          axisLabel: { color: '#64748b', fontSize: 10 }
        }],
        series: [{
          type: 'line',
          data: values,
          step: 'end',
          symbol: 'circle',
          symbolSize: 5,
          lineStyle: { width: 2, color: '#3b82f6' },
          itemStyle: { color: '#3b82f6' },
          areaStyle: { color: 'rgba(59, 130, 246, 0.08)' }
        }]
      }
    }
  }
}
</script>

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

.sp-scroll {
  @include flex-scroll-y;
  background: $morandi-bg-page;
}

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

.sp-section--chart {
  padding-bottom: 16rpx;
}

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

.sp-section__head--chart {
  flex-wrap: wrap;
}

.sp-section__title {
  font-size: 30rpx;
  font-weight: 600;
  color: $morandi-text;
  flex-shrink: 0;
}

.sp-section__title--block {
  display: block;
  margin-bottom: 20rpx;
}

.sp-updated {
  font-size: 22rpx;
  color: $morandi-text-muted;
  flex: 1;
  text-align: right;
}

.sp-range-tabs {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 8rpx;
  justify-content: flex-end;
}

.sp-range-tab {
  padding: 6rpx 16rpx;
  border-radius: 8rpx;
  border: 1rpx solid $morandi-border-strong;
  background: #ffffff;
}

.sp-range-tab--on {
  border-color: #3b82f6;
  background: rgba(59, 130, 246, 0.1);
}

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

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

.sp-loading {
  padding: 32rpx 0;
  text-align: center;
}

.sp-loading__txt {
  font-size: 26rpx;
  color: $morandi-text-muted;
}

.sp-metrics {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  gap: 16rpx;
}

.sp-metric {
  width: calc(50% - 8rpx);
  padding: 20rpx 16rpx;
  border-radius: 12rpx;
  background: #f5f7fa;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

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

.sp-metric__value {
  font-size: 30rpx;
  font-weight: 600;
  color: $morandi-text;
  word-break: break-word;
}

.sp-chart-host {
  width: 100%;
  height: 360rpx;
  border-radius: 8rpx;
  overflow: hidden;
  background: #f0f6fb;
}

.sp-chart-host :deep(.ec-canvas) {
  display: block;
  width: 100% !important;
  height: 100% !important;
}

.sp-yak-row {
  display: flex;
  flex-direction: row;
  align-items: stretch;
}

.sp-yak-col {
  flex: 1;
  min-width: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8rpx;
}

.sp-yak-col__num {
  font-size: 40rpx;
  font-weight: 700;
  color: $morandi-text;
}

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

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