<template>
  <div class="target-wrapper">
    <!-- 整体统计卡片 -->
    <div class="overview-stats">
      <div class="stat-card overview-card">
        <div class="stat-icon-circle primary">
          <i class="el-icon-aim"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">本月整体目标</div>
          <div class="stat-value">￥{{ formatMoney(overview.totalTarget) }}</div>
        </div>
      </div>
      <div class="stat-card overview-card">
        <div class="stat-icon-circle success">
          <i class="el-icon-check"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">已完成目标</div>
          <div class="stat-value">￥{{ formatMoney(overview.totalCompleted) }}</div>
        </div>
      </div>
      <div class="stat-card overview-card">
        <div class="stat-icon-circle" :class="overview.completionRate >= 100 ? 'success' : 'warning'">
          <i class="el-icon-data-line"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">完成率</div>
          <div class="stat-value">{{ formatMoney(overview.completionRate) }}%</div>
        </div>
      </div>
      <div class="stat-card overview-card" v-if="overview.isCurrentMonth">
        <div class="stat-icon-circle" :class="overview.estimatedRate >= 100 ? 'success' : 'warning'">
          <i class="el-icon-trends"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">预计完成率</div>
          <div class="stat-value">{{ formatMoney(overview.estimatedRate) }}%</div>
        </div>
      </div>
      <div class="stat-card overview-card" v-else>
        <div class="stat-icon-circle">
          <i class="el-icon-trends"></i>
        </div>
        <div class="stat-content">
          <div class="stat-title">预计完成率</div>
          <div class="stat-value">--</div>
        </div>
      </div>
    </div>

    <!-- 预警提示 -->
    <div class="alert-card" v-if="overview.isCurrentMonth && overview.estimatedRate < 100 && overview.dailyRequiredFor100 > 0">
      <div class="alert-icon">
        <i class="el-icon-warning"></i>
      </div>
      <div class="alert-content">
        <div class="alert-title">完成目标提醒</div>
        <div class="alert-text">
          预计完成率 <span class="highlight">{{ formatMoney(overview.estimatedRate) }}%</span>，未达到100%。
          剩余 <span class="highlight">{{ overview.remainingDays }}</span> 天，建议每天开单金额达到
          <span class="highlight-amount">￥{{ formatMoney(overview.dailyRequiredFor100) }}</span> 才能完成目标。
        </div>
      </div>
    </div>

    <!-- 关键指标卡片 -->
    <div class="key-metrics">
      <div class="metric-card">
        <div class="metric-header">
          <i class="el-icon-success"></i>
          <span>已完成目标门店</span>
        </div>
        <div class="metric-value success">{{ overview.achievedCount }} 家</div>
        <div class="metric-list scrollable" v-if="topAchievedStores.length > 0">
          <div class="metric-item" v-for="(store, idx) in topAchievedStores" :key="store.storeId">
            <span class="rank">{{ idx + 1 }}</span>
            <span class="name">{{ store.storeName || '未知门店' }}</span>
            <span class="rate">{{ formatMoney(store.completionRate) }}%</span>
          </div>
        </div>
      </div>
      <div class="metric-card">
        <div class="metric-header">
          <i class="el-icon-warning"></i>
          <span>未完成目标门店</span>
        </div>
        <div class="metric-value warning">{{ overview.unachievedCount }} 家</div>
        <div class="metric-list scrollable" v-if="topUnachievedStores.length > 0">
          <div class="metric-item" v-for="(store, idx) in topUnachievedStores" :key="store.storeId">
            <span class="rank">{{ idx + 1 }}</span>
            <span class="name">{{ store.storeName || '未知门店' }}</span>
            <span class="rate">{{ formatMoney(store.completionRate) }}%</span>
          </div>
        </div>
      </div>
      <div class="metric-card">
        <div class="metric-header">
          <i class="el-icon-trophy"></i>
          <span>排名第一门店</span>
        </div>
        <div class="metric-value primary" v-if="topStore">
          {{ topStore.storeName }}
        </div>
        <div class="metric-detail" v-if="topStore">
          <div class="detail-item">
            <span>完成率：</span>
            <span class="value">{{ formatMoney(topStore.completionRate) }}%</span>
          </div>
          <div class="detail-item">
            <span>开单业绩：</span>
            <span class="value">￥{{ formatMoney(topStore.actualBilling) }}</span>
          </div>
          <div class="detail-item">
            <span>退卡业绩：</span>
            <span class="value">￥{{ formatMoney(topStore.refundAmount) }}</span>
          </div>
          <div class="detail-item">
            <span>净业绩：</span>
            <span class="value">￥{{ formatMoney(topStore.netBilling) }}</span>
          </div>
        </div>
      </div>
      <div class="metric-card">
        <div class="metric-header">
          <i class="el-icon-data-analysis"></i>
          <span>达成100%每日需完成</span>
        </div>
        <div class="metric-value" v-if="overview.isCurrentMonth" :class="overview.dailyRequiredFor100 > 0 ? 'warning' : 'success'">
          ￥{{ formatMoney(overview.dailyRequiredFor100) }}
        </div>
        <div class="metric-value" v-else>
          --
        </div>
        <div class="metric-detail" v-if="overview.isCurrentMonth && overview.remainingDays > 0">
          <div class="detail-item">
            <span>剩余天数：</span>
            <span class="value">{{ overview.remainingDays }} 天</span>
          </div>
          <div class="detail-item">
            <span>还需完成：</span>
            <span class="value">￥{{ formatMoney(Math.max(0, overview.totalTarget - overview.totalCompleted)) }}</span>
          </div>
        </div>
        <div class="metric-detail" v-else-if="overview.isCurrentMonth">
          <div class="detail-item">
            <span>本月已结束</span>
          </div>
        </div>
        <div class="metric-detail" v-else>
          <div class="detail-item">
            <span>历史月份不显示预计数据</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 门店业绩柱状图 -->
    <div class="chart-section">
      <div class="chart-header">
        <h3>门店目标与净业绩对比</h3>
        <div class="chart-legend">
          <span class="legend-item"><i class="legend-target"></i> 目标业绩</span>
          <span class="legend-item"><i class="legend-completed"></i> 净业绩</span>
        </div>
      </div>
      <div ref="storeChart" class="chart-container"></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: 'TargetAnalysis',
  mixins: [kpiDrillMixin],
  props: {
    filters: {
      type: Object,
      default: () => ({ startTime: null, endTime: null, storeIds: [], month: null })
    },
    extra: { type: Object, default: () => ({}) },
    storeOptions: { type: Array, default: () => [] }
  },
  data() {
    return {
      loading: false,
      list: [],
      displayList: [],
      overview: {
        totalTarget: 0,
        totalCompleted: 0,
        completionRate: 0,
        estimatedRate: 0,
        dailyRequired: 0,
        remainingDays: 0,
        achievedCount: 0,
        unachievedCount: 0,
        lastMonthRate: null,
        lastMonthComparison: 0,
        dailyRequiredFor100: 0,
        isCurrentMonth: true // 是否是当前月份
      },
      topStore: null,
      topAchievedStores: [],
      topUnachievedStores: []
    }
  },
  watch: {
    filters: {
      deep: true,
      handler() {
        this.resetAndFetch()
      }
    }
  },
  mounted() {
    this.fetchData()
  },
  methods: {
    resetAndFetch() {
      this.fetchData()
    },
    async fetchData() {
      this.loading = true
      try {
        // 获取门店目标数据 - 不传分页参数，获取所有数据
        const url = '/api/Extend/LqMdTarget'
        const data = {
          currentPage: 1,
          pageSize: 1000 // 设置一个较大的值，确保获取所有门店
        }
        if (this.filters && this.filters.month) data.Month = this.filters.month
        if (this.filters && this.filters.storeIds && this.filters.storeIds.length > 0) {
          data.StoreId = this.filters.storeIds[0] // 如果只选了一个门店
          // 如果选了多个门店，可能需要调整接口支持
        }

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

      if (res && res.data) {
        if (res.data.list && Array.isArray(res.data.list)) {
          list = res.data.list
        } else if (Array.isArray(res.data)) {
          list = res.data
        }
      }

      const fmtMonth = v => {
        const s = (v || '').toString()
        if (s.length === 6) return `${s.slice(0, 4)}-${s.slice(4)}`
        return s
      }
      // 从storeOptions中查找门店名称
      const getStoreName = (storeId) => {
        if (!storeId) return '未知门店'
        const store = this.storeOptions.find(s => s.id === storeId)
        return store ? (store.fullName || store.dm || store.name || store.label || '未知门店') : '未知门店'
      }

      list = list.map(i => {
        // 注意：接口返回的字段名可能是小写的 storeId, storeTarget
        const storeId = i.StoreId || i.storeId || ''
        const storeTarget = i.StoreTarget || i.storeTarget || i.storeTarget || 0
        return {
          storeId: storeId,
          storeName: getStoreName(storeId),
          month: i.Month || i.month || '',
          monthText: fmtMonth(i.Month || i.month || ''),
          storeTarget: Number(storeTarget)
        }
      })
      
      // 过滤掉没有门店ID的数据
      list = list.filter(item => item.storeId)

      // 获取每个门店的实际业绩
      const timeRange = this.buildDateRange()
      const metrics = await Promise.all(list.map(async row => {
        if (!row.storeId) return null
        try {
          const resKpi = await request({
            url: '/api/Extend/LqReport/get-business-statistics',
            method: 'POST',
            data: {
              startTime: timeRange ? `${timeRange.start} 00:00:00` : null,
              endTime: timeRange ? `${timeRange.end} 23:59:59` : null,
              storeIds: [row.storeId]
            }
          })
          const d = resKpi.data || {}
          return {
            storeId: row.storeId,
            billing: Number(d.TotalBillingAmount || d.billing_amount || 0),
            refund: Number(d.TotalRefundAmount || d.refund_amount || 0),
            net: Number(d.TotalBillingAmount || 0) - Number(d.TotalRefundAmount || 0)
          }
        } catch (error) {
          console.error(`获取门店 ${row.storeId} 业绩失败:`, error)
          return {
            storeId: row.storeId,
            billing: 0,
            refund: 0,
            net: 0
          }
        }
      }))

      const map = {}
      metrics.filter(Boolean).forEach(m => { map[m.storeId] = m })

      // 计算完成率和是否达成
      list = list.map(row => {
        const m = map[row.storeId] || { billing: 0, refund: 0, net: 0 }
        const completionRate = (row.storeTarget || 0) > 0
          ? ((m.net || 0) / row.storeTarget * 100)
          : 0
        const achieved = (row.storeTarget || 0) > 0 ? ((m.net || 0) >= row.storeTarget ? '达成' : '未达成') : '未设置'
        return {
          ...row,
          actualBilling: m.billing || 0,
          refundAmount: m.refund || 0,
          netBilling: m.net || 0,
          completionRate: completionRate,
          achieved
        }
      })

      this.list = list
      // 不再需要displayList，因为列表已删除

      // 计算整体统计
      this.calculateOverview()

      // 获取上月数据
      await this.fetchLastMonthData()

      // 渲染图表
      this.$nextTick(() => {
        this.renderStoreChart()
      })
    },
    calculateOverview() {
      const totalTarget = this.list.reduce((sum, row) => sum + (row.storeTarget || 0), 0)
      const totalCompleted = this.list.reduce((sum, row) => sum + (row.netBilling || 0), 0)
      const completionRate = totalTarget > 0 ? (totalCompleted / totalTarget * 100) : 0

      // 判断是否是当前月份或未来月份
      const now = dayjs()
      const timeRange = this.buildDateRange()
      // 获取查询的月份
      const queryMonth = timeRange ? dayjs(timeRange.start) : now
      const queryMonthStart = queryMonth.startOf('month')
      const queryMonthEnd = queryMonth.endOf('month')
      const currentMonthStart = now.startOf('month')
      
      // 判断是否是当前月份（查询月份等于当前月份）
      const isCurrentMonth = queryMonthStart.isSame(currentMonthStart, 'month')
      // 判断月份是否已过完（查询月份结束时间小于当前时间）
      const isMonthFinished = queryMonthEnd.isBefore(now, 'day')

      let estimatedRate = 0
      let dailyRequiredFor100 = 0
      let remainingDays = 0

      // 只有当前月份且未过完时才计算预计完成率和每日需完成
      if (isCurrentMonth && !isMonthFinished) {
        // 计算预计完成率
        const monthStart = now.startOf('month')
        const monthEnd = now.endOf('month')
        // 已过天数：从月初到现在（包括今天）
        const actualPassedDays = now.diff(monthStart, 'day') + 1
        // 总天数：这个月的总天数
        const actualTotalDays = monthEnd.diff(monthStart, 'day') + 1
        remainingDays = Math.max(0, actualTotalDays - actualPassedDays)

        // 预计完成率计算：已完成业绩 / 已过天数 = 平均每天业绩，然后 * 总天数 = 预计完成业绩，最后 / 目标 * 100
        const avgDailyPerformance = actualPassedDays > 0 ? (totalCompleted / actualPassedDays) : 0
        const estimatedCompleted = avgDailyPerformance * actualTotalDays
        estimatedRate = totalTarget > 0 ? (estimatedCompleted / totalTarget * 100) : 0

        // 计算每天需要达到的金额（用于达成100%）
        const remainingAmount = Math.max(0, totalTarget - totalCompleted)
        dailyRequiredFor100 = remainingDays > 0 ? (remainingAmount / remainingDays) : 0
      }

      // 统计达成情况
      const achievedList = this.list.filter(row => row.achieved === '达成')
      const unachievedList = this.list.filter(row => row.achieved === '未达成')

      // 排名第一的门店
      const sortedByNet = [...this.list].sort((a, b) => (b.netBilling || 0) - (a.netBilling || 0))
      this.topStore = sortedByNet[0] || null

      // 已完成门店排名（按完成率）
      this.topAchievedStores = achievedList.sort((a, b) => (b.completionRate || 0) - (a.completionRate || 0))

      // 未完成门店排名（按完成率，从高到低）
      this.topUnachievedStores = unachievedList.sort((a, b) => (b.completionRate || 0) - (a.completionRate || 0))

      this.overview = {
        totalTarget,
        totalCompleted,
        completionRate,
        estimatedRate,
        dailyRequired: dailyRequiredFor100,
        remainingDays,
        achievedCount: achievedList.length,
        unachievedCount: unachievedList.length,
        lastMonthRate: null,
        lastMonthComparison: 0,
        dailyRequiredFor100,
        isCurrentMonth: isCurrentMonth && !isMonthFinished
      }
    },
    async fetchLastMonthData() {
      try {
        const timeRange = this.buildDateRange()
        const currentMonth = timeRange ? dayjs(timeRange.start) : dayjs()
        const lastMonthStart = currentMonth.subtract(1, 'month').startOf('month')
        const lastMonthEnd = currentMonth.subtract(1, 'month').endOf('month')

        const res = await request({
          url: '/api/Extend/LqReport/get-business-statistics',
          method: 'POST',
          data: {
            startTime: `${lastMonthStart.format('YYYY-MM-DD')} 00:00:00`,
            endTime: `${lastMonthEnd.format('YYYY-MM-DD')} 23:59:59`,
            storeIds: this.filters && this.filters.storeIds ? this.filters.storeIds : []
          }
        })

        const data = res.data || {}
        const lastMonthTarget = data.TargetBillingAmount || 0
        const lastMonthCompleted = data.CompletedBillingAmount || 0
        const lastMonthRate = lastMonthTarget > 0 ? (lastMonthCompleted / lastMonthTarget * 100) : 0

        this.overview.lastMonthRate = lastMonthRate
        this.overview.lastMonthComparison = this.overview.completionRate - lastMonthRate
      } catch (error) {
        console.error('获取上月数据失败:', error)
      }
    },
    renderStoreChart() {
      const dom = this.$refs.storeChart
      if (!dom) return

      const chart = echarts.init(dom)
      // 使用所有门店数据，不限制数量
      const chartData = this.list

      const storeNames = chartData.map(item => item.storeName || '未知门店')
      const targets = chartData.map(item => item.storeTarget || 0)
      // 使用净业绩（开单-退卡），与目标对比
      const completed = chartData.map(item => item.netBilling || 0)

      chart.setOption({
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'shadow' },
          formatter: params => {
            const p = Array.isArray(params) ? params : [params]
            let result = `${p[0].name}<br/>`
            p.forEach(item => {
              const value = Number(item.value || 0)
              result += `${item.seriesName}: ￥${this.formatMoney(value)}<br/>`
            })
            return result
          }
        },
        legend: {
          data: ['目标业绩', '净业绩'],
          top: 10,
          textStyle: { color: '#606266' }
        },
        grid: {
          left: '12%',
          right: '4%',
          top: '15%',
          bottom: chartData.length > 20 ? '25%' : '15%',
          containLabel: false
        },
        xAxis: {
          type: 'category',
          data: storeNames,
          axisLabel: {
            color: '#606266',
            fontSize: chartData.length > 20 ? 9 : 11,
            rotate: chartData.length > 15 ? 45 : 0,
            interval: 0
          },
          axisLine: { lineStyle: { color: '#dcdfe6' } }
        },
        yAxis: {
          type: 'value',
          name: '金额',
          axisLabel: { color: '#606266' },
          splitLine: { lineStyle: { color: '#ebeef5' } }
        },
        series: [
          {
            name: '目标业绩',
            type: 'bar',
            data: targets,
            itemStyle: { color: '#E6A23C' },
            barWidth: chartData.length > 20 ? 8 : 12
          },
          {
            name: '净业绩',
            type: 'bar',
            data: completed,
            itemStyle: { color: '#67C23A' },
            barWidth: chartData.length > 20 ? 8 : 12
          }
        ]
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.target-wrapper {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.overview-stats {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 8px;
}

.stat-card.overview-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 10px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  display: flex;
  align-items: center;
  gap: 16px;

  .stat-icon-circle {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    flex-shrink: 0;
    font-size: 24px;

    &.primary {
      background: #409EFF;
    }

    &.success {
      background: #67C23A;
    }

    &.warning {
      background: #E6A23C;
    }
  }

  .stat-content {
    flex: 1;
    min-width: 0;
  }

  .stat-title {
    font-size: 13px;
    color: #606266;
    margin-bottom: 8px;
  }

  .stat-value {
    font-size: 20px;
    font-weight: 700;
    color: #303133;
  }
}

.alert-card {
  background: #fff3cd;
  border: 1px solid #ffc107;
  border-radius: 10px;
  padding: 16px;
  display: flex;
  align-items: flex-start;
  gap: 12px;

  .alert-icon {
    color: #ffc107;
    font-size: 24px;
    flex-shrink: 0;
  }

  .alert-content {
    flex: 1;
  }

  .alert-title {
    font-size: 14px;
    font-weight: 600;
    color: #856404;
    margin-bottom: 8px;
  }

  .alert-text {
    font-size: 13px;
    color: #856404;
    line-height: 1.6;

    .highlight {
      font-weight: 700;
      color: #d9534f;
    }

    .highlight-amount {
      font-weight: 700;
      color: #d9534f;
      font-size: 16px;
    }
  }
}

.key-metrics {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  align-items: stretch; // 让所有卡片高度一致
  
  // 确保所有卡片高度一致
  .metric-card {
    height: 100%;
    min-height: 200px; // 设置最小高度，确保右边两个卡片高度一致
  }
}

.metric-card {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 10px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  display: flex;
  flex-direction: column;

  .metric-header {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    color: #606266;
    margin-bottom: 12px;

    i {
      color: #409EFF;
    }
  }

  .metric-value {
    font-size: 24px;
    font-weight: 700;
    margin-bottom: 12px;
    flex-shrink: 0;

    &.success {
      color: #67C23A;
    }

    &.warning {
      color: #E6A23C;
    }

    &.primary {
      color: #409EFF;
    }

    &.danger {
      color: #F56C6C;
    }
  }

  .metric-list {
    &.scrollable {
      // 3个item的高度：每个item padding 6px*2=12px + line-height 18px + border 1px = 31px，3个 = 93px
      max-height: 93px;
      overflow-y: auto;
      // 无缝滚动
      scroll-behavior: smooth;
      // 美化滚动条
      &::-webkit-scrollbar {
        width: 4px;
      }
      &::-webkit-scrollbar-track {
        background: #f5f5f5;
        border-radius: 2px;
      }
      &::-webkit-scrollbar-thumb {
        background: #c0c4cc;
        border-radius: 2px;
        &:hover {
          background: #909399;
        }
      }
      // 隐藏滚动条但保持滚动功能（可选，如果需要更美观）
      // scrollbar-width: none; /* Firefox */
      // &::-webkit-scrollbar { display: none; } /* Chrome/Safari */
    }

    .metric-item {
      display: flex;
      align-items: center;
      gap: 8px;
      padding: 6px 0;
      font-size: 12px;
      line-height: 18px;
      height: 31px; // 固定高度：padding 6px*2 + line-height 18px + border 1px = 31px
      box-sizing: border-box;
      border-bottom: 1px solid #f5f7fa;

      &:last-child {
        border-bottom: none;
      }

      .rank {
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background: #f5f7fa;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        color: #606266;
        flex-shrink: 0;
      }

      .name {
        flex: 1;
        color: #303133;
        min-width: 0;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .rate {
        color: #909399;
        font-weight: 600;
        flex-shrink: 0;
      }
    }
  }

  .metric-detail {
    margin-top: auto; // 让detail自动推到卡片底部
    flex-shrink: 0;
    
    .detail-item {
      display: flex;
      justify-content: space-between;
      padding: 6px 0;
      font-size: 12px;
      color: #606266;

      .value {
        font-weight: 600;
        color: #303133;
      }
    }
  }
}

.chart-section {
  background: #fff;
  border: 1px solid #ebeef5;
  border-radius: 10px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);

  .chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
    }

    .chart-legend {
      display: flex;
      gap: 16px;

      .legend-item {
        display: flex;
        align-items: center;
        gap: 6px;
        font-size: 12px;
        color: #606266;

        i {
          width: 12px;
          height: 12px;
          border-radius: 2px;

          &.legend-target {
            background: #E6A23C;
          }

          &.legend-completed {
            background: #67C23A;
          }
        }
      }
    }
  }

  .chart-container {
    width: 100%;
    height: 500px;
    min-height: 500px;
  }
}
</style>
