<template>
  <div>
    <lineChartModel :tableData="tableData" :lineListData="seriesData" :totalProfit="totalProfit"
      :legendData="legendData" title="收益" :appList="issuedAppList" @update="getIndexProfitData" />
    <lineChartModel :tableData="tableData" :lineListData="seriesEcpmData" :totalProfit="totalProfit"
      :legendData="legendData" :type="'ecpm'" title="ECPM趋势"  />

    <userDataChart />
  </div>
</template>

<script setup>
import { ref, onBeforeMount } from 'vue'
import { getIndexProfit, getIndexHourReport } from '@/api/dashboard.js'
import { issuedApps } from "@/api/formworkErection.js";
import lineChartModel from './lineChartModel.vue'
import userDataChart from './userDataChart.vue'
import { roundPrice } from '@/utils'

// 表格初始化数据
const tableData = ref([
  { platform: "穿山甲", today: "0.00", yesterday: "0.00", month: "0.00", ecpmToday: "0.00", ecpmYesterday: "0.00", ecpmMonth: "0.00" },
  { platform: "腾讯广告", today: "0.00", yesterday: "0.00", month: "0.00", ecpmToday: "0.00", ecpmYesterday: "0.00", ecpmMonth: "0.00" },
  { platform: "百度联盟", today: "0.00", yesterday: "0.00", month: "0.00", ecpmToday: "0.00", ecpmYesterday: "0.00", ecpmMonth: "0.00" },
  { platform: "快手", today: "0.00", yesterday: "0.00", month: "0.00", ecpmToday: "0.00", ecpmYesterday: "0.00", ecpmMonth: "0.00" },
  { platform: "Sigmob", today: "0.00", yesterday: "0.00", month: "0.00", ecpmToday: "0.00", ecpmYesterday: "0.00", ecpmMonth: "0.00" },
])

const colorData = [
  '#add7f6', '#f7a8b8', '#ffcc5c', '#88d8b0', '#9966cc',
  '#cf9ef1', '#57e7ec', '#fdb301', '#f59a8f', '#fca4bb',
  '#2b908f', '#90ed7d', '#e75fc3', '#5085f2', '#8d7fec'
]

const totalProfit = ref({}) //表格数据汇总
const seriesData = ref([])
const seriesEcpmData = ref([])
const legendData = ref([]) //名称
const getIndexProfitData = async (appId) => {
  const res = await getIndexProfit({appId})

  // 清空现有数据（保留响应式引用）
  tableData.value.splice(0)
  seriesData.value.splice(0)
  seriesEcpmData.value.splice(0)
  legendData.value.splice(0)

  res.data.forEach((item, index) => {
    const { tableRow, chartSeries, chartSeriesEcpm, name } = mapAppRevenueItem(item, index)
    tableData.value.push(tableRow)
    seriesData.value.push(chartSeries)
    seriesEcpmData.value.push(chartSeriesEcpm)
    legendData.value.push(name)
  })

  const summary = tableData.value.reduce((acc, cur) => {
    acc.today += parseFloat(cur.today) || 0
    acc.yesterday += parseFloat(cur.yesterday) || 0
    acc.month += parseFloat(cur.month) || 0
    acc.ecpmToday += parseFloat(cur.ecpmToday) || 0
    acc.ecpmYesterday += parseFloat(cur.ecpmYesterday) || 0
    acc.ecpmMonth += parseFloat(cur.ecpmMonth) || 0
    return acc
  }, {
    today: 0, yesterday: 0, month: 0,
    ecpmToday: 0, ecpmYesterday: 0, ecpmMonth: 0
  })

  // 格式化为两位小数字符串
  totalProfit.value = {
    today: summary.today.toFixed(2),
    yesterday: summary.yesterday.toFixed(2),
    month: summary.month.toFixed(2),
    ecpmToday: summary.ecpmToday.toFixed(2),
    ecpmYesterday: summary.ecpmYesterday.toFixed(2),
    ecpmMonth: summary.ecpmMonth.toFixed(2),
  }
}

const mapAppRevenueItem = (item, index) => {
  return {
    tableRow: {
      platform: item.netowrkName,
      today: roundPrice(item.todayRevenue),
      yesterday: roundPrice(item.yesterdayRevenue),
      month: roundPrice(item.monthRevenue),
      ecpmToday: roundPrice(item.todayEcpm),
      ecpmYesterday: roundPrice(item.yesterdayEcpm),
      ecpmMonth: roundPrice(item.monthEcpm),
    },
    chartSeries: {
      type: 'line',
      name: item.netowrkName,
      symbolSize: 6,
      z: 1,
      label: { show: false },
      itemStyle: { color: colorData[index % colorData.length] },
      lineStyle: { color: colorData[index % colorData.length], width: 2 },
      data: fillHourRevenueMap(item.todayHourRevenueMap)
    },
    chartSeriesEcpm: {
      type: 'line',
      name: item.netowrkName,
      symbolSize: 6,
      z: 1,
      label: { show: false },
      itemStyle: { color: colorData[index % colorData.length] },
      lineStyle: { color: colorData[index % colorData.length], width: 2 },
      data: fillHourRevenueMap(item.todayHourEcpmMap)
    },
    name: item.netowrkName
  }
}

// 提取24小时数据
const fillHourRevenueMap = (map) => {
  const hourMap = {}

  for (const [datetime, value] of Object.entries(map || {})) {
    const hour = new Date(datetime).getHours()
    hourMap[hour] = parseFloat(value) || 0
  }

  const fullMap = []
  for (let i = 0; i < 24; i++) {
    fullMap.push(hourMap[i] ?? 0)
  }

  return fullMap
}

//应用列表
const issuedAppList = ref([])
const getIssuedAppList = async ()=>{
  let res = await issuedApps({})
  issuedAppList.value = res.data
  console.log('res.data',res.data)
  const firstApp =  issuedAppList.value[0].appId
  await getIndexProfitData(firstApp)
}

onBeforeMount(async () => {
  await getIssuedAppList()
})

</script>

<style lang="scss" scoped></style>