<template>
  <div class="tk-wrapper">
    <div class="tk-layout">
      <!-- 左侧：走势图 + 列表 -->
      <div class="tk-left">
        <div class="chart-card trend-card">
          <div class="chart-title">
            <i class="el-icon-date"></i>
            活动时间走势图
          </div>
          <div ref="dailyTrendChart" class="chart-mini"></div>
        </div>

        <div v-if="selectedDate" class="chart-card hourly-card">
          <div class="chart-title" style="justify-content: space-between;">
            <span style="display: flex; align-items: center; gap: 6px;">
              <i class="el-icon-time"></i>
              {{ selectedDate }} 24小时走势图
            </span>
            <el-button type="text" size="mini" icon="el-icon-close" style="padding: 0 4px;"
              @click="closeHourlyChart">关闭</el-button>
          </div>
          <div ref="hourlyTrendChart" 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.eventId" size="mini" placeholder="活动" style="width: 200px;" clearable
                @change="applyListFilter">
                <el-option v-for="e in eventList" :key="e.EventId || e.eventId" 
                  :label="e.EventName || e.eventName" 
                  :value="e.EventId || e.eventId" />
              </el-select>
            </div>
          </div>

          <el-table v-loading="loading" :data="displayList" size="small" height="600" 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>{{ 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="tk-right">
        <div class="table-card ranking-card">
          <div class="table-title">
            <i class="el-icon-s-data"></i>
            门店本月拓客人数排名
          </div>
          <div class="ranking-list">
            <div v-for="(item, index) in storeRanking" :key="index" class="ranking-item">
              <div class="ranking-number" :class="getRankingClass(index)">{{ index + 1 }}</div>
              <div class="ranking-content">
                <div class="ranking-name">{{ item.StoreName || item.storeName || '未知' }}</div>
                <div class="ranking-value">{{ item.TkCount || item.tkCount || 0 }} 人</div>
              </div>
            </div>
            <div v-if="!storeRanking || storeRanking.length === 0" class="empty-ranking">
              暂无数据
            </div>
          </div>
        </div>

        <div class="chart-card">
          <div class="chart-title">
            <i class="el-icon-trophy"></i>
            拓客人员拓客人数排名前五
          </div>
          <div ref="personRankingChart" 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: 'TkAnalysis',
  mixins: [kpiDrillMixin],
  props: {
    filters: {
      type: Object,
      default: () => ({ startTime: null, endTime: null, storeIds: [], month: null })
    },
    storeOptions: { type: Array, default: () => [] }
  },
  data() {
    return {
      loading: false,
      list: [],
      displayList: [],
      pagination: { pageIndex: 1, pageSize: 10, total: 0 },
      listFilter: { eventId: null },
      eventList: [],
      storeRanking: [],
      personRanking: [],
      dailyTrend: [],
      hourlyTrend: [],
      selectedDate: null,
      columns: [
        { prop: 'expansionTime', label: '拓客时间', minWidth: 140 },
        { prop: 'storeName', label: '门店', minWidth: 120 },
        { prop: 'customerName', label: '客户', minWidth: 100 },
        { prop: 'expansionUserName', label: '拓客人员', minWidth: 100 },
        { prop: 'eventName', label: '活动', minWidth: 120 },
        { prop: 'hasInvite', label: '是否邀约', width: 90 },
        { prop: 'hasAppointment', label: '是否预约', width: 90 },
        { prop: 'hasConsume', label: '是否消耗', width: 90 },
        { prop: 'hasBilling', label: '是否开卡', width: 90 }
      ],
      charts: {
        dailyTrend: null,
        hourlyTrend: null,
        personRanking: null
      }
    }
  },
  watch: {
    filters: {
      deep: true,
      handler() {
        this.resetAndFetch()
      }
    }
  },
  mounted() {
    this.fetchData()
    this.fetchStatistics()
  },
  beforeDestroy() {
    Object.values(this.charts).forEach(chart => {
      if (chart) chart.dispose()
    })
  },
  methods: {
    resetAndFetch() {
      this.pagination = { ...this.pagination, pageIndex: 1 }
      this.listFilter = { eventId: null }
      this.selectedDate = null
      this.fetchData()
      this.fetchStatistics()
    },
    handleSizeChange(size) {
      this.pagination.pageSize = size
      this.pagination.pageIndex = 1
      this.fetchData()
    },
    handleCurrentChange(page) {
      this.pagination.pageIndex = page
      this.fetchData()
    },
    applyListFilter() {
      this.pagination.pageIndex = 1
      this.fetchData()
      this.fetchStatistics()
    },
    async fetchStatistics() {
      try {
        const range = this.buildDateRange()
        if (!range) {
          console.warn('No date range available for statistics')
          return
        }
        
        const url = '/api/Extend/LqReport/get-tk-drill-statistics'
        const data = {
          startTime: dayjs(range.start).format('YYYY-MM-DD HH:mm:ss'),
          endTime: dayjs(range.end).format('YYYY-MM-DD HH:mm:ss'),
          storeIds: this.filters.storeIds || [],
          eventId: this.listFilter.eventId || null,
          selectedDate: this.selectedDate
        }

        const res = await request({ url, method: 'POST', data })
        if (res && res.data) {
          // 兼容不同的响应格式
          const stats = res.data.Success ? res.data.Data : (res.data.data || res.data)
          if (stats) {
            this.storeRanking = stats.StoreRanking || stats.storeRanking || []
            this.personRanking = stats.PersonRanking || stats.personRanking || []
            this.eventList = stats.EventList || stats.eventList || []
            this.dailyTrend = stats.DailyTrend || stats.dailyTrend || []
            this.hourlyTrend = stats.HourlyTrend || stats.hourlyTrend || []
            
            // 调试：打印原始数据
            console.log('DailyTrend received:', this.dailyTrend)
            if (this.dailyTrend && this.dailyTrend.length > 0) {
              console.log('First item keys:', Object.keys(this.dailyTrend[0]))
              console.log('First item:', this.dailyTrend[0])
            }
            
            this.$nextTick(() => {
              this.renderCharts()
            })
          }
        }
      } catch (error) {
        console.error('Tk statistics load error:', error)
        this.$message.error('加载统计数据失败: ' + (error.message || '未知错误'))
      }
    },
    async fetchData() {
      this.loading = true
      try {
        const range = this.buildDateRange()
        const storeId = this.getStoreId()
        const url = '/api/Extend/LqTkjlb'
        const data = {
          currentPage: this.pagination.pageIndex,
          pageSize: this.pagination.pageSize
        }
        if (range) data.expansionTime = `${range.startTs},${range.endTs}`
        if (storeId) data.storeId = storeId
        if (this.listFilter.eventId) data.eventId = this.listFilter.eventId

        const res = await request({ url, method: 'GET', data })
        await this.handleResponse(res)
      } catch (error) {
        console.error('Tk analysis load error:', error)
        this.$message.error(error.message || '加载数据失败')
        this.list = []
        this.displayList = []
      } finally {
        this.loading = false
      }
    },
    async handleResponse(res) {
      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
          }
        } else if (Array.isArray(res.data.list)) {
          list = res.data.list
        } else if (Array.isArray(res.data)) {
          list = res.data
        }
      }

      list = list.map(i => ({
        expansionTime: i.expansionTime || i.ExpansionTime ? dayjs(i.expansionTime || i.ExpansionTime).format('YYYY-MM-DD HH:mm') : '',
        storeName: i.storeName || i.StoreName || i.dm,
        customerName: i.customerName || i.CustomerName,
        expansionUserName: i.expansionUserName || i.ExpansionUserName || '—',
        eventName: i.eventName || i.EventName || '—',
        hasInvite: i.hasInvite || i.HasInvite || '否',
        hasAppointment: i.hasAppointment || i.HasAppointment || '否',
        hasConsume: i.hasConsume || i.HasConsume || '否',
        hasBilling: i.hasBilling || i.HasBilling || '否'
      }))

      this.list = list
      this.displayList = list
      this.pagination = pagination
    },
    renderCharts() {
      this.renderDailyTrendChart()
      this.renderHourlyTrendChart()
      this.renderPersonRankingChart()
    },
    closeHourlyChart() {
      this.selectedDate = null
      this.hourlyTrend = []
      if (this.charts.hourlyTrend) {
        this.charts.hourlyTrend.dispose()
        this.charts.hourlyTrend = null
      }
    },
    getRankingClass(index) {
      if (index === 0) return 'rank-first'
      if (index === 1) return 'rank-second'
      if (index === 2) return 'rank-third'
      return ''
    },
    renderDailyTrendChart() {
      if (!this.$refs.dailyTrendChart) {
        console.warn('dailyTrendChart ref not found')
        return
      }
      if (this.charts.dailyTrend) {
        this.charts.dailyTrend.dispose()
      }
      
      const chart = echarts.init(this.$refs.dailyTrendChart)
      if (!chart) {
        console.error('Failed to initialize chart')
        return
      }
      
      if (!this.dailyTrend || this.dailyTrend.length === 0) {
        chart.setOption({
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'middle',
            textStyle: { color: '#909399', fontSize: 14 }
          }
        })
        this.charts.dailyTrend = chart
        return
      }
      
      // 获取时间范围，生成完整的月份日期数组
      const range = this.buildDateRange()
      if (!range) {
        console.warn('No date range available')
        return
      }
      
      const startDate = dayjs(range.start)
      const endDate = dayjs(range.end)
      
      // 生成从开始日期到结束日期的所有日期
      const allDates = []
      let currentDate = startDate
      while (currentDate.isBefore(endDate) || currentDate.isSame(endDate, 'day')) {
        allDates.push(currentDate.format('YYYY-MM-DD'))
        currentDate = currentDate.add(1, 'day')
      }
      
      // 构建日期和数量的映射
      const dateCountMap = new Map()
      console.log('DailyTrend raw data:', this.dailyTrend) // 调试日志
      this.dailyTrend.forEach((d, index) => {
        // 获取所有可能的键名（不区分大小写）
        const keys = Object.keys(d || {})
        const keysLower = keys.map(k => k.toLowerCase())
        
        // 尝试获取日期 - 查找 DateStr 或 dateStr
        let dateKey = ''
        const dateStrIndex = keysLower.indexOf('datestr')
        if (dateStrIndex >= 0) {
          const originalKey = keys[dateStrIndex]
          const dateValue = d[originalKey]
          if (dateValue) {
            dateKey = String(dateValue).trim()
            // 确保日期格式正确（yyyy-MM-dd）
            if (dateKey.length > 10) {
              dateKey = dateKey.substring(0, 10)
            }
          }
        }
        
        // 尝试获取数量 - 查找 TkCount 或 tkCount
        let count = 0
        const tkCountIndex = keysLower.indexOf('tkcount')
        if (tkCountIndex >= 0) {
          const originalKey = keys[tkCountIndex]
          const countValue = d[originalKey]
          if (countValue !== undefined && countValue !== null) {
            count = Number(countValue) || 0
          }
        }
        
        if (dateKey) {
          dateCountMap.set(dateKey, count)
          console.log(`[${index}] Mapped date: ${dateKey}, count: ${count}`, d) // 调试日志
        } else {
          console.warn(`[${index}] Could not extract date from:`, d, 'Keys:', keys) // 调试日志
        }
      })
      
      console.log('Date count map:', Array.from(dateCountMap.entries())) // 调试日志
      console.log('All dates to map:', allDates.slice(0, 5), '...', allDates.slice(-5)) // 调试日志
      
      // 使用完整的日期数组，缺失的日期补0
      const finalDates = allDates
      const finalCounts = allDates.map(date => {
        const count = dateCountMap.get(date)
        return count !== undefined ? count : 0
      })
      
      console.log('Final dates count:', finalDates.length)
      console.log('Final counts sample (first 5):', finalCounts.slice(0, 5))
      console.log('Final counts sample (last 5):', finalCounts.slice(-5))
      console.log('Non-zero counts:', finalCounts.filter(c => c > 0).length)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const param = Array.isArray(params) ? params[0] : params
            return `${param.name}<br/>拓客人数: ${param.value}`
          }
        },
        grid: { left: '10%', right: '5%', bottom: '15%', top: '10%' },
        xAxis: {
          type: 'category',
          data: finalDates,
          axisLabel: { rotate: 45, fontSize: 11 }
        },
        yAxis: { type: 'value', name: '人数' },
        series: [{
          name: '拓客人数',
          type: 'line',
          data: finalCounts,
          smooth: true,
          itemStyle: { color: '#409EFF' },
          areaStyle: { color: 'rgba(64, 158, 255, 0.1)' }
        }]
      }

      chart.setOption(option)
      chart.on('click', (params) => {
        if (params && params.name) {
          this.selectedDate = params.name
          this.fetchStatistics()
        }
      })
      this.charts.dailyTrend = chart
    },
    renderHourlyTrendChart() {
      if (!this.$refs.hourlyTrendChart || !this.selectedDate) {
        return
      }
      if (this.charts.hourlyTrend) {
        this.charts.hourlyTrend.dispose()
      }
      
      const chart = echarts.init(this.$refs.hourlyTrendChart)
      if (!chart) {
        console.error('Failed to initialize hourly chart')
        return
      }
      
      if (!this.hourlyTrend || this.hourlyTrend.length === 0) {
        chart.setOption({
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'middle',
            textStyle: { color: '#909399', fontSize: 14 }
          }
        })
        this.charts.hourlyTrend = chart
        return
      }
      
      // 生成完整的24小时数据（0-23点），缺失的小时补0
      const allHours = Array.from({ length: 24 }, (_, i) => {
        const hourStr = `${String(i).padStart(2, '0')}:00`
        const existing = this.hourlyTrend.find(h => {
          const hStr = h.HourStr || h.hourStr
          const hNum = h.Hour || h.hour
          return hStr === hourStr || (hNum !== undefined && hNum === i)
        })
        return {
          hour: i,
          hourStr: hourStr,
          count: existing ? Number(existing.TkCount || existing.tkCount || 0) : 0
        }
      })
      
      const hours = allHours.map(h => h.hourStr)
      const counts = allHours.map(h => h.count)

      const option = {
        tooltip: { 
          trigger: 'axis',
          formatter: (params) => {
            const param = Array.isArray(params) ? params[0] : params
            return `${param.name}<br/>拓客人数: ${param.value}`
          }
        },
        grid: { left: '10%', right: '5%', bottom: '15%', top: '10%' },
        xAxis: {
          type: 'category',
          data: hours,
          axisLabel: { 
            fontSize: 11,
            interval: 0, // 显示所有标签
            rotate: 45 // 旋转45度避免重叠
          }
        },
        yAxis: { type: 'value', name: '人数' },
        series: [{
          name: '拓客人数',
          type: 'bar',
          data: counts,
          itemStyle: { color: '#67C23A' }
        }]
      }

      chart.setOption(option)
      this.charts.hourlyTrend = chart
    },
    renderPersonRankingChart() {
      if (!this.$refs.personRankingChart) {
        console.warn('personRankingChart ref not found')
        return
      }
      if (this.charts.personRanking) {
        this.charts.personRanking.dispose()
      }
      
      const chart = echarts.init(this.$refs.personRankingChart)
      if (!chart) {
        console.error('Failed to initialize chart')
        return
      }
      
      if (!this.personRanking || this.personRanking.length === 0) {
        chart.setOption({
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'middle',
            textStyle: { color: '#909399', fontSize: 14 }
          }
        })
        this.charts.personRanking = chart
        return
      }
      
      const persons = this.personRanking.map(p => p.UserName || p.userName || '未知')
      const counts = this.personRanking.map(p => Number(p.TkCount || p.tkCount || 0))

      const option = {
        tooltip: { 
          trigger: 'axis', 
          axisPointer: { type: 'shadow' },
          formatter: (params) => {
            const param = Array.isArray(params) ? params[0] : params
            return `${param.name}<br/>拓客人数: ${param.value}`
          }
        },
        grid: { left: '15%', right: '5%', bottom: '20%', top: '10%' },
        xAxis: {
          type: 'value',
          name: '人数'
        },
        yAxis: {
          type: 'category',
          data: persons,
          axisLabel: { fontSize: 11 }
        },
        series: [{
          name: '拓客人数',
          type: 'bar',
          data: counts,
          itemStyle: { color: '#67C23A' }
        }]
      }

      chart.setOption(option)
      this.charts.personRanking = chart
    }
  }
}
</script>

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

.tk-wrapper {
  width: 100%;
  overflow: hidden;

  .tk-layout {
    display: flex;
    align-items: stretch;
    justify-content: space-between;
    gap: 16px;
    width: 100%;
  }

  .tk-left {
    flex: 0 0 75%;
    max-width: 75%;
    display: flex;
    flex-direction: column;
    gap: 12px;
    min-width: 0;
  }

      .tk-right {
    flex: 0 0 25%;
    max-width: 23.5%;
    display: flex;
    flex-direction: column;
    gap: 12px;
    min-width: 0;
  }

  .ranking-card {
    background: #fff;
    border: 1px solid #ebeef5;
    border-radius: 10px;
    padding: 10px 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    flex-shrink: 0;
    max-height: 400px;
    overflow-y: auto;

    .table-title {
      font-size: 13px;
      font-weight: 600;
      color: #303133;
      margin-bottom: 10px;
      display: flex;
      align-items: center;
      gap: 6px;

      i {
        color: #409EFF;
      }
    }

    .ranking-list {
      display: flex;
      flex-direction: column;
      gap: 8px;
    }

    .ranking-item {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 8px;
      border-radius: 6px;
      background: #f5f7fa;
      transition: all 0.3s;

      &:hover {
        background: #ecf5ff;
      }

      .ranking-number {
        width: 28px;
        height: 28px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 700;
        font-size: 14px;
        flex-shrink: 0;
        background: #909399;
        color: #fff;

        &.rank-first {
          background: #FFD700;
          color: #333;
        }

        &.rank-second {
          background: #C0C0C0;
          color: #333;
        }

        &.rank-third {
          background: #CD7F32;
          color: #fff;
        }
      }

      .ranking-content {
        flex: 1;
        min-width: 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .ranking-name {
        font-size: 13px;
        color: #303133;
        font-weight: 500;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }

      .ranking-value {
        font-size: 13px;
        color: #409EFF;
        font-weight: 600;
        white-space: nowrap;
        margin-left: 8px;
      }
    }

    .empty-ranking {
      text-align: center;
      color: #909399;
      padding: 20px;
      font-size: 13px;
    }
  }

  // 复用 common-styles 中的样式
  .chart-card {
    background: #fff;
    border: 1px solid #ebeef5;
    border-radius: 10px;
    padding: 10px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    flex-shrink: 0;

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

      i {
        color: #409EFF;
      }
    }

    .chart-mini {
      height: 220px;
      width: 100%;
    }
  }

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

    .table-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 8px;
      flex-shrink: 0;
    }

    .table-title {
      font-size: 14px;
      font-weight: 600;
      color: #303133;
      display: flex;
      align-items: center;
      gap: 6px;

      i {
        color: #409EFF;
      }
    }

    .el-table {
      flex: 1;
      min-height: 0;
    }

    .pagination-bar {
      flex-shrink: 0;
      margin-top: 8px;
      display: flex;
      justify-content: flex-end;
      padding: 10px 0 4px 0;
    }
  }
}
</style>
