<template>
  <div class="order-value-view order-dashboard-page">
    <header class="page-header">
      <h1 class="page-title">订单价值</h1>
    </header>

    <OrderDateRangeFilter
      :max-date="maxDate"
      default-period="day"
      storage-key="dtm-order-date-filter"
      @change="handleFilterChange"
    />

    <section class="kpi-cards-grid">
      <OrderLoadingPanel
        v-if="dashboardLoading"
        compact
        title="正在加载核心指标"
        detail="正在读取 GMV、贡献比与支付响应"
      />
      <KpiCard title="总交易额 (GMV)" :value="kpiData.gmv" :trend="kpiData.gmvTrend" :trend-color="getTrendColor(kpiData.gmvTrend)" icon="$" />
      <KpiCard title="P80 订单贡献比" :value="kpiData.p80Contribution" :trend="kpiData.p80Trend" :trend-color="getTrendColor(kpiData.p80Trend)" icon="P" />
      <KpiCard title="Top 5 商品贡献比" :value="kpiData.top5Contribution" :trend="kpiData.top5Trend" :trend-color="getTrendColor(kpiData.top5Trend)" icon="5" />
      <KpiCard title="平均支付响应" :value="kpiData.averagePaymentTime" :trend="kpiData.avgTimeTrend" :trend-color="getTrendColor(kpiData.avgTimeTrend)" icon="T" />
    </section>

    <section class="charts-area">
      <div class="chart-wrapper funnel-chart-wrapper">
        <FunnelChart :date-range="currentDateRange" />
      </div>
      <div class="chart-wrapper">
        <Top5PieChart :date-range="currentDateRange" />
      </div>
    </section>

    <section class="leakage-section">
      <div class="chart-wrapper leakage-card-wrapper full-width">
        <LeakageCard :date-range="currentDateRange" />
      </div>
    </section>
  </div>
</template>

<script>
import KpiCard from './KpiCard/index.vue'
import FunnelChart from './FunnelChart/index.vue'
import Top5PieChart from './Top5PieChart/index.vue'
import LeakageCard from './LeakageCard/index.vue'
import OrderLoadingPanel from '../components/OrderLoadingPanel.vue'
import OrderDateRangeFilter from '../components/OrderDateRangeFilter.vue'
import {
  getOrderAveragePaymentTime,
  getOrderGmv,
  getOrderMaxDate,
  getOrderRBig,
  getOrderTop5Percentage
} from '@/api/order'

export default {
  name: 'OrderValue',
  components: {
    KpiCard,
    FunnelChart,
    Top5PieChart,
    LeakageCard,
    OrderLoadingPanel,
    OrderDateRangeFilter
  },
  data() {
    return {
      selectedDate: '',
      activeTab: '7d',
      maxDate: '',
      currentDateRange: { start: '', end: '' },
      dashboardLoading: true,
      pickerOptions: {
        disabledDate: time => {
          if (!this.maxDate) return false
          return time.getTime() > new Date(`${this.maxDate}T23:59:59`).getTime()
        }
      },
      kpiData: {
        gmv: '¥0',
        gmvTrend: '+0%',
        p80Contribution: '0%',
        p80Trend: '+0%',
        top5Contribution: '0%',
        top5Trend: '+0%',
        averagePaymentTime: '00:00 秒',
        avgTimeTrend: '+0%'
      }
    }
  },
  mounted() {
    this.initDashboard()
  },
  methods: {
    handleFilterChange(params) {
      const range = {
        start: params.startDate || this.maxDate,
        end: params.endDate || this.maxDate
      }
      this.activeTab = params.periodType || 'day'
      this.currentDateRange = range
      this.fetchAllApiData(range).finally(() => this.finishDashboardLoading())
    },
    handleDateChange() {
      if (!this.selectedDate) {
        this.selectedDate = this.maxDate
      }
      this.selectDateRange(this.activeTab)
    },
    pad2(value) {
      return String(value).padStart(2, '0')
    },
    toDate(value) {
      if (value instanceof Date) return new Date(value.getTime())
      if (!value) return new Date()
      return new Date(`${value}T00:00:00`)
    },
    formatYmd(value) {
      const date = this.toDate(value)
      return `${date.getFullYear()}-${this.pad2(date.getMonth() + 1)}-${this.pad2(date.getDate())}`
    },
    addDays(value, days) {
      const date = this.toDate(value)
      date.setDate(date.getDate() + days)
      return date
    },
    addMonths(value, months) {
      const date = this.toDate(value)
      date.setMonth(date.getMonth() + months)
      return date
    },
    startOfMonth(value) {
      const date = this.toDate(value)
      return new Date(date.getFullYear(), date.getMonth(), 1)
    },
    endOfMonth(value) {
      const date = this.toDate(value)
      return new Date(date.getFullYear(), date.getMonth() + 1, 0)
    },
    getCurrentRange(type = this.activeTab) {
      const baseDate = this.toDate(this.selectedDate || this.maxDate || new Date())
      if (type === 'day') {
        const day = this.formatYmd(baseDate)
        return { start: day, end: day }
      }
      if (type === '7d') {
        return {
          start: this.formatYmd(this.addDays(baseDate, -6)),
          end: this.formatYmd(baseDate)
        }
      }
      if (type === 'tm') {
        return {
          start: this.formatYmd(this.startOfMonth(baseDate)),
          end: this.formatYmd(this.endOfMonth(baseDate))
        }
      }
      if (type === 'lm') {
        const lastMonth = this.addMonths(baseDate, -1)
        return {
          start: this.formatYmd(this.startOfMonth(lastMonth)),
          end: this.formatYmd(this.endOfMonth(lastMonth))
        }
      }
      return {
        start: '2022-01-01',
        end: this.maxDate || this.formatYmd(baseDate)
      }
    },
    async fetchAllApiData(customRange = null) {
      this.dashboardLoading = true
      try {
        const { start, end } = customRange || this.getCurrentRange()
        const [gmvRes, p80Res, top5Res, avgTimeRes] = await Promise.all([
          getOrderGmv({ startDate: start, endDate: end }),
          getOrderRBig({ startDate: start, endDate: end }),
          getOrderTop5Percentage({ startDate: start, endDate: end }),
          getOrderAveragePaymentTime({ startDate: start, endDate: end })
        ])

        const gmvValue = gmvRes || 0
        this.kpiData.gmv = new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(gmvValue)
        this.kpiData.p80Contribution = `${Math.round(p80Res?.rBigRatio || 0)}%`
        this.kpiData.top5Contribution = `${Math.round(top5Res?.data?.top5Percentage || 0)}%`

        const avgSeconds = avgTimeRes?.averagePaymentSeconds || 0
        const minutes = Math.floor(avgSeconds / 60)
        const seconds = Math.round(avgSeconds % 60)
        this.kpiData.averagePaymentTime = `${this.pad2(minutes)}:${this.pad2(seconds)} 秒`

        if (this.activeTab !== 'tm') {
          this.kpiData.gmvTrend = '+0%'
          this.kpiData.p80Trend = '+0%'
          this.kpiData.top5Trend = '+0%'
          this.kpiData.avgTimeTrend = '+0%'
        }
      } catch (error) {
        console.error('获取订单价值数据失败:', error)
      }
    },
    finishDashboardLoading() {
      this.dashboardLoading = false
    },
    calculateTrend(currentValue, previousValue) {
      if (previousValue === 0) return '+0%'
      const change = ((currentValue - previousValue) / previousValue) * 100
      const sign = change >= 0 ? '+' : ''
      return `${sign}${change.toFixed(1)}%`
    },
    parseTimeString(timeString) {
      const timeMatch = String(timeString || '').match(/(\d{2}):(\d{2})/)
      if (!timeMatch) return 0
      return parseInt(timeMatch[1], 10) * 60 + parseInt(timeMatch[2], 10)
    },
    getTrendColor(trend) {
      return parseFloat(trend) >= 0 ? 'green' : 'red'
    },
    async fetchPreviousMonthData(currentStart) {
      try {
        const currentStartDate = this.toDate(currentStart)
        const previousMonthBase = this.addMonths(currentStartDate, -1)
        const previousMonthStart = this.formatYmd(this.startOfMonth(previousMonthBase))
        const previousMonthEnd = this.formatYmd(this.endOfMonth(previousMonthBase))

        const [gmvRes, p80Res, top5Res, avgTimeRes] = await Promise.all([
          getOrderGmv({ startDate: previousMonthStart, endDate: previousMonthEnd }),
          getOrderRBig({ startDate: previousMonthStart, endDate: previousMonthEnd }),
          getOrderTop5Percentage({ startDate: previousMonthStart, endDate: previousMonthEnd }),
          getOrderAveragePaymentTime({ startDate: previousMonthStart, endDate: previousMonthEnd })
        ])

        return {
          gmv: gmvRes || 0,
          p80: p80Res?.rBigRatio || 0,
          top5: top5Res?.data?.top5Percentage || 0,
          avgTime: avgTimeRes?.averagePaymentSeconds || 0
        }
      } catch (error) {
        console.error('获取上月订单价值数据失败:', error)
        return null
      }
    },
    async initDashboard() {
      try {
        const res = await getOrderMaxDate()
        this.maxDate = res
      } catch (error) {
        console.error('获取订单最大日期失败:', error)
        const today = this.formatYmd(new Date())
        this.maxDate = today
      }
    },
    async selectDateRange(type) {
      this.activeTab = type
      const range = this.getCurrentRange(type)
      this.currentDateRange = range

      if (type === 'tm') {
        await this.fetchAllApiData(range)
        const previousMonthData = await this.fetchPreviousMonthData(range.start)
        if (previousMonthData) {
          const currentGmv = parseFloat(this.kpiData.gmv.replace(/[¥,]/g, '')) || 0
          const currentP80 = parseFloat(this.kpiData.p80Contribution.replace('%', '')) || 0
          const currentTop5 = parseFloat(this.kpiData.top5Contribution.replace('%', '')) || 0
          const currentAvgTime = this.parseTimeString(this.kpiData.averagePaymentTime)

          this.kpiData.gmvTrend = this.calculateTrend(currentGmv, previousMonthData.gmv)
          this.kpiData.p80Trend = this.calculateTrend(currentP80, previousMonthData.p80)
          this.kpiData.top5Trend = this.calculateTrend(currentTop5, previousMonthData.top5)
          this.kpiData.avgTimeTrend = this.calculateTrend(currentAvgTime, previousMonthData.avgTime)
        }
        this.finishDashboardLoading()
      } else {
        await this.fetchAllApiData(range)
        this.finishDashboardLoading()
      }
    }
  }
}
</script>

<style scoped>
.order-value-view {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #fff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.page-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.control-label {
  font-size: 14px;
  color: #666;
}

.control-item-group {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-picker {
  width: 150px;
}

.time-tab {
  padding: 6px 14px;
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s;
}

.time-tab:hover {
  border-color: #188df0;
  color: #188df0;
}

.time-tab.active {
  background-color: #188df0;
  color: #fff;
  border-color: #188df0;
}

.kpi-cards-grid {
  position: relative;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  min-height: 146px;
}

.charts-area {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.leakage-section {
  display: flex;
}

.full-width {
  width: 100%;
}

.chart-wrapper {
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}
</style>
