<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" @touchmove.stop>
        <mpvueEcharts
          ref="amountChart"
          :onInit="onChartInit"
          canvasId="distributorHomeAmount"
          :disableTouch="false"
        />
      </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 { getDistributorDashboard } from '@/api/distributor/home'
import {
  DASH,
  formatCount,
  formatPercent,
  formatWanAmount,
  formatWanPerHead,
  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,
      summary: {},
      amountTrend: []
    }
  },
  computed: {
    metricCards() {
      const s = this.summary || {}
      return [
        { key: 'orderCount', label: '累计下单数', value: formatCount(s.orderCount, '笔') },
        { key: 'totalAmount', label: '采购总金额', value: formatWanAmount(s.totalAmount) },
        { key: 'totalHeads', label: '已购牦牛数', value: formatCount(s.totalHeads, '头') },
        { key: 'completionRate', label: '订单完成率', value: formatPercent(s.completionRate) },
        {key: 'supplierCount', label: '成交供应商数', value: formatCount(s.supplierCount, '个') },
        { key: 'avgUnitPrice', label: '近期交易均价', value: formatWanPerHead(s.avgUnitPrice) }
      ]
    }
  },
  beforeDestroy() {
    clearHomeRealtimePoll(this)
  },
  methods: {
    reload() {
      this.loadDashboard()
      this.syncRealtimePoll()
    },
    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
      }
      getDistributorDashboard(this.activeRange)
        .then((res) => {
          const d = res.data || {}
          this.updatedAt = d.updatedAt || DASH
          this.summary = d.summary || {}
          this.amountTrend = d.amountTrend || []
          this.refreshChart()
        })
        .catch(() => {
          this.summary = {}
          this.amountTrend = []
          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',
          triggerOn: 'click',
          confine: true,
          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-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-footer-spacer {
  height: 40rpx;
}
</style>
