<template>
  <div class="billing-wrapper">
    <div class="billing-layout">
      <!-- 左侧：趋势 + 列表 -->
      <div class="billing-left">
        <div class="chart-card trend-card">
          <div class="chart-title">
            <i class="el-icon-date"></i>
            每日开单金额 & 人数
          </div>
          <div ref="billingTrendChart" class="chart-mini"></div>
        </div>

        <div class="table-card">
          <div class="table-header">
            <div class="table-title">
              <i class="el-icon-document"></i>
              本月成交明细
            </div>
            <div class="list-filters inline">
              <el-select v-model="listFilter.store" size="mini" placeholder="门店" style="width: 180px;" clearable
                @change="applyListFilter">
                <el-option v-for="s in storeOptions" :key="s.id" :label="s.fullName || s.dm || s.name || s.label"
                  :value="s.id" />
              </el-select>
            </div>
          </div>

          <el-table v-loading="loading" :data="displayList" size="small" height="650" border stripe>
            <el-table-column v-for="col in columns" :key="col.prop" :prop="col.prop" :label="col.label"
              :width="col.width" :min-width="col.minWidth">
              <template slot-scope="scope">
                <span v-if="col.type === 'money'">￥{{ formatMoney(scope.row[col.prop]) }}</span>
                <span v-else>{{ scope.row[col.prop] || '—' }}</span>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-bar">
            <el-pagination layout="total, sizes, prev, pager, next" :page-sizes="[10, 20, 50]"
              :total="pagination.total" :current-page="pagination.pageIndex" :page-size="pagination.pageSize"
              @size-change="handleSizeChange" @current-change="handleCurrentChange" />
          </div>
        </div>
      </div>

      <!-- 右侧：关键指标 + 雷达图 -->
      <div class="billing-right">
        <div class="stat-card neon-green compact">
          <div class="stat-icon-circle">
            <i class="el-icon-trophy"></i>
          </div>
          <div class="stat-content">
            <div class="stat-title">开单金额最高会员</div>
            <div class="stat-body">
              <div class="highlight text-ellipsis-2">
                {{ billingStats.topMemberAmount.name || '无' }}
                <span class="value-inline">￥{{ formatMoney(billingStats.topMemberAmount.value) }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="stat-card neon-orange compact">
          <div class="stat-icon-circle">
            <i class="el-icon-user"></i>
          </div>
          <div class="stat-content">
            <div class="stat-title">开单次数最多会员</div>
            <div class="stat-body">
              <div class="highlight text-ellipsis-2">
                {{ billingStats.topMemberTimes.name || '无' }}
                <span class="value-inline">{{ billingStats.topMemberTimes.count || 0 }} 次</span>
              </div>
            </div>
          </div>
        </div>

        <div class="chart-card">
          <div class="chart-title">
            <i class="el-icon-data-analysis"></i>
            品项类型雷达图
          </div>
          <div ref="itemTypeRadarChart" class="chart-mini"></div>
        </div>

        <div class="chart-card" style="display: none;">
          <div class="chart-title">
            <i class="el-icon-pie-chart"></i>
            业绩类型占比
          </div>
          <div ref="performanceTypePieChart" class="chart-mini"></div>
        </div>

        <div class="chart-card">
          <div class="chart-title">
            <i class="el-icon-s-data"></i>
            科美类型业绩
          </div>
          <div ref="beautyTypeBarChart" class="chart-mini"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import request from '@/utils/request'
import dayjs from 'dayjs'
import * as echarts from 'echarts'
import { kpiDrillMixin } from './mixins'

export default {
  name: 'BillingAnalysis',
  mixins: [kpiDrillMixin],
  props: {
    filters: {
      type: Object,
      default: () => ({ startTime: null, endTime: null, storeIds: [], month: null })
    },
    storeOptions: { type: Array, default: () => [] }
  },
  data() {
    return {
      loading: false,
      list: [],
      displayList: [],
      billingStats: {
        itemTypeTop: [],
        topMemberAmount: { name: '', value: 0 },
        topMemberTimes: { name: '', count: 0 },
        debtTotal: 0,
        topDebtMember: { name: '', value: 0 }
      },
      pagination: { pageIndex: 1, pageSize: 10, total: 0 },
      listFilter: {
        store: ''
      },
      columns: [
        { prop: 'billingTime', label: '开单时间', minWidth: 120 },
        { prop: 'storeName', label: '门店', minWidth: 120 },
        { prop: 'memberName', label: '会员', minWidth: 120 },
        { prop: 'itemName', label: '品项', minWidth: 140 },
        { prop: 'itemType', label: '品项类型', minWidth: 120 },
        { prop: 'projectNumber', label: '项目数', width: 90 },
        { prop: 'actualPrice', label: '实付金额', width: 110, type: 'money' },
        { prop: 'sourceType', label: '来源类型', minWidth: 110 },
        { prop: 'performanceType', label: '业绩类型', minWidth: 110 },
        { prop: 'beautyType', label: '科美类型', minWidth: 110 }
      ]
    }
  },
  watch: {
    filters: {
      deep: true,
      handler() {
        this.resetAndFetch()
      }
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    resetAndFetch() {
      this.pagination = { ...this.pagination, pageIndex: 1 }
      this.fetchData()
    },
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.pagination.pageIndex = 1
      this.fetchData()
    },
    handleCurrentChange(page) {
      this.pagination.pageIndex = page
      this.fetchData()
    },
    async fetchData() {
      this.loading = true
      try {
        const range = this.buildDateRange()
        const storeId = this.getStoreId()
        const url = '/api/Extend/LqKdKdjlb/billing-item-detail-list'
        const data = {
          currentPage: this.pagination.pageIndex,
          pageSize: this.pagination.pageSize
        }
        if (range) {
          data.startTime = `${range.start} 00:00:00`
          data.endTime = `${range.end} 23:59:59`
        }
        if (this.listFilter.store) {
          data.StoreId = this.listFilter.store
        } else if (storeId) {
          data.StoreId = storeId
        }

        // 获取统计数据
        const month = this.getMonth()
        const statsRes = await request({
          url: '/api/Extend/LqReport/get-billing-drill-statistics',
          method: 'POST',
          data: {
            statisticsMonth: month,
            storeIds: this.filters && this.filters.storeIds ? this.filters.storeIds : []
          }
        })
        this.applyBillingStatistics(statsRes && statsRes.data)

        // 获取列表数据
        const res = await request({ url, method: 'GET', data })
        await this.handleResponse(res, range)
      } catch (error) {
        console.error('Billing analysis load error:', error)
        this.$message.error(error.message || '加载数据失败')
        this.list = []
        this.displayList = []
      } finally {
        this.loading = false
      }
    },
    async handleResponse(res, range) {
      let list = []
      let pagination = this.pagination

      if (res && res.data) {
        if (res.data.list && res.data.pagination) {
          list = res.data.list
          pagination = {
            pageIndex: res.data.pagination.pageIndex || res.data.pagination.pageNumber || 1,
            pageSize: res.data.pagination.pageSize || this.pagination.pageSize,
            total: res.data.pagination.total || res.data.pagination.totalCount || 0
          }
        }
      }

      list = list.map(i => ({
        billingTime: i.billingTime || i.yjsj || i.CreateTime ? dayjs(i.billingTime || i.yjsj || i.CreateTime).format('YYYY-MM-DD HH:mm') : '',
        storeName: i.storeName || i.djmdmc || i.store,
        storeId: i.djmd || i.Djmd || i.storeId,
        memberName: i.memberName || i.kdhyc || i.MemberName,
        itemName: i.itemName || i.ItemName,
        itemType: i.itemType || i.ItemType,
        projectNumber: i.projectNumber || i.ProjectNumber,
        actualPrice: i.actualPrice || i.ActualPrice || 0,
        totalPrice: i.zdyj || i.Zdyj || 0,
        debt: (i.qk || i.Qk || 0) - (i.paidDebt || i.PaidDebt || 0),
        paidDebt: i.paidDebt || i.PaidDebt || 0,
        orderNo: i.id || i.Id || '',
        sourceType: i.sourceType || i.SourceType || '',
        performanceType: i.performanceType || i.PerformanceType || '',
        beautyType: i.beautyType || i.BeautyType || ''
      }))

      this.list = list
      this.displayList = list
      if (res && res.data && res.data.pagination) {
        this.pagination = {
          pageIndex: res.data.pagination.pageIndex || res.data.pagination.pageNumber || this.pagination.pageIndex,
          pageSize: res.data.pagination.pageSize || this.pagination.pageSize,
          total: res.data.pagination.total || res.data.pagination.totalCount || 0
        }
      }
    },
    applyBillingStatistics(statistics) {
      if (!statistics) {
        this.billingStats = {
          itemTypeTop: [],
          topMemberAmount: { name: '', value: 0 },
          topMemberTimes: { name: '', count: 0 },
          debtTotal: 0,
          topDebtMember: { name: '', value: 0 }
        }
        this.renderBillingTrend([])
        this.renderItemTypeRadar([])
        this.renderSourceAndTypeCharts(null)
        return
      }

      const trend = (statistics.DailyTrend || []).map(i => ({
        date: i.Date,
        amount: i.Amount,
        memberCount: i.MemberCount
      }))
      this.renderBillingTrend(trend)

      const itemTypeRadar = statistics.ItemTypeRadar || []
      this.renderItemTypeRadar(itemTypeRadar)

      this.renderSourceAndTypeCharts({
        performanceTypeStats: statistics.PerformanceTypeStats || [],
        beautyTypeStats: statistics.BeautyTypeStats || []
      })

      const memberStats = statistics.MemberStats || {}
      this.billingStats = {
        itemTypeTop: (itemTypeRadar || []).sort((a, b) => (b.Amount || 0) - (a.Amount || 0)).slice(0, 3),
        topMemberAmount: {
          name: memberStats.TopAmountMemberName || '—',
          value: memberStats.TopAmountValue || 0
        },
        topMemberTimes: {
          name: memberStats.TopTimesMemberName || '—',
          count: memberStats.TopTimesCount || 0
        },
        debtTotal: memberStats.DebtTotal || 0,
        topDebtMember: { name: '', value: 0 }
      }
    },
    renderBillingTrend(trend) {
      const dom = this.$refs.billingTrendChart
      if (!dom) return
      const chart = echarts.init(dom)
      const dates = trend.map(i => i.date)
      chart.setOption({
        tooltip: { trigger: 'axis' },
        legend: { data: ['开单金额', '开单人数'], textStyle: { color: '#606266' } },
        grid: { left: '6%', right: '4%', top: '10%', bottom: '14%' },
        xAxis: { type: 'category', data: dates, axisLine: { lineStyle: { color: '#dcdfe6' } }, axisLabel: { color: '#606266', rotate: 40 } },
        yAxis: [
          { type: 'value', name: '金额', axisLabel: { color: '#606266' }, splitLine: { lineStyle: { color: '#ebeef5' } } },
          { type: 'value', name: '人数', axisLabel: { color: '#606266' }, splitLine: { show: false } }
        ],
        series: [
          { name: '开单金额', type: 'bar', data: trend.map(i => i.amount), itemStyle: { color: '#409EFF' }, barWidth: 12 },
          { name: '开单人数', type: 'line', yAxisIndex: 1, data: trend.map(i => i.memberCount), smooth: true, itemStyle: { color: '#67C23A' } }
        ]
      })
    },
    renderItemTypeRadar(list) {
      const dom = this.$refs.itemTypeRadarChart
      if (!dom) return
      const chart = echarts.init(dom)
      if (!list || !list.length) {
        chart.clear()
        return
      }
      const maxVal = Math.max(...list.map(x => Number(x.value || x.Amount || 0))) || 1
      const indicators = list.map(i => ({
        name: i.name || i.Name,
        max: maxVal
      }))
      chart.setOption({
        tooltip: {},
        radar: {
          indicator: indicators,
          splitNumber: 4,
          radius: '70%',
          name: { textStyle: { color: '#606266', fontSize: 11 } },
          splitLine: { lineStyle: { color: ['#dcdfe6', '#ebeef5'] } },
          splitArea: { areaStyle: { color: ['#f5f7fa', '#fff'] } },
          axisLine: { lineStyle: { color: '#dcdfe6' } }
        },
        series: [{
          type: 'radar',
          data: [{
            value: list.map(i => Number(i.value || i.Amount || 0)),
            name: '金额',
            areaStyle: { color: 'rgba(64,158,255,0.25)' },
            lineStyle: { color: '#409EFF' },
            symbol: 'circle',
            symbolSize: 3
          }]
        }]
      })
    },
    renderSourceAndTypeCharts(payload) {
      if (!payload) {
        ['performanceTypePieChart', 'beautyTypeBarChart'].forEach(refName => {
          const dom = this.$refs[refName]
          if (dom) {
            const chart = echarts.init(dom)
            chart.clear()
          }
        })
        return
      }

      const perfStats = payload.performanceTypeStats || []
      const beautyStats = payload.beautyTypeStats || []

      // 业绩类型金额饼图
      const perfDom = this.$refs.performanceTypePieChart
      if (perfDom) {
        const chart = echarts.init(perfDom)
        chart.setOption({
          tooltip: {
            trigger: 'item',
            formatter: params => {
              const val = Number(params.value || 0)
              return `${params.name}<br/>金额：￥${this.formatMoney(val)}`
            }
          },
          legend: {
            bottom: 0,
            left: 'center',
            textStyle: { fontSize: 10, color: '#606266' }
          },
          series: [
            {
              type: 'pie',
              radius: ['35%', '70%'],
              avoidLabelOverlap: false,
              label: { show: false },
              labelLine: { show: false },
              data: perfStats.map(i => ({
                name: i.Name,
                value: i.Amount
              }))
            }
          ]
        })
      }

      // 科美类型金额柱状图
      const beautyDom = this.$refs.beautyTypeBarChart
      if (beautyDom) {
        const chart = echarts.init(beautyDom)
        chart.setOption({
          tooltip: {
            trigger: 'axis',
            formatter: params => {
              const p = Array.isArray(params) ? params[0] : params
              const val = Number(p.value || 0)
              return `${p.name}<br/>金额：￥${this.formatMoney(val)}`
            }
          },
          grid: { left: '8%', right: '4%', top: '10%', bottom: '18%' },
          xAxis: {
            type: 'category',
            data: beautyStats.map(i => i.Name),
            axisLabel: { color: '#606266', fontSize: 10 }
          },
          yAxis: {
            type: 'value',
            axisLabel: { color: '#606266' },
            splitLine: { lineStyle: { color: '#ebeef5' } }
          },
          series: [
            {
              type: 'bar',
              data: beautyStats.map(i => i.Amount),
              barWidth: 14,
              itemStyle: { color: '#909399' }
            }
          ]
        })
      }
    },
    applyListFilter() {
      this.pagination.pageIndex = 1
      this.fetchData()
    }
  }
}
</script>

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

