<template>
  <div>
    <el-card>
      <template #header>
        <span>花费图表</span>
      </template>
      <el-button type="primary" @click="downloadExcel" style="margin-bottom: 20px">
        导出订单Excel
      </el-button>

      <el-select
        v-model="selectedBranch"
        placeholder="选择店铺"
        style="width: 200px; margin-bottom: 20px"
      >
        <el-option
          v-for="branch in branchList"
          :key="branch.branchId"
          :label="branch.branchName"
          :value="branch.branchId"
        />
      </el-select>
      <div id="chart" style="width: 100%; height: 400px"></div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/userStores/user' // 根据你的路径调整
const userStore = useUserStore()
// 定义订单类型和店铺类型
interface Order {
  orderId: number
  accountId: number
  orderTime: string
  branchId: number
  orderMoney: string
}

interface Branch {
  branchId: number
  branchName: string
}

const customerId = userStore.getUserId // 获取用户ID
const orders = ref<Order[]>([]) // 用户订单
const branchList = ref<Branch[]>([]) // 店铺列表
const selectedBranch = ref<number | null>(null) // 当前选择的店铺ID
let chart: echarts.ECharts | null = null // ECharts 实例

// 获取订单数据
const fetchOrders = async () => {
  try {
    const res = await axios.get(`http://localhost:8080/user/orders/user/${customerId}`) //ok
    orders.value = res.data || []
    await fetchBranchNames()
  } catch (err) {
    ElMessage.error('获取订单数据失败')
  }
}

// 获取店铺名称
const fetchBranchNames = async () => {
  const branchIds = [...new Set(orders.value.map((o) => o.branchId))]
  const promises = branchIds.map((id) => axios.get(`http://localhost:8080/user/branch/${id}`)) //ok
  try {
    const results = await Promise.all(promises)
    branchList.value = results.map((res) => res.data)
  } catch (err) {
    ElMessage.error('获取店铺数据失败')
  }
}

// 渲染图表
const renderChart = () => {
  if (!selectedBranch.value || !chart) return

  // 过滤出选中店铺的订单
  const filtered = orders.value.filter((o) => o.branchId === selectedBranch.value)

  // 按日期汇总消费金额
  const dailyTotals: Record<string, number> = {}
  filtered.forEach((o) => {
    const date = o.orderTime.split('T')[0] // 格式化为 YYYY-MM-DD
    if (!dailyTotals[date]) {
      dailyTotals[date] = 0
    }
    dailyTotals[date] += parseFloat(o.orderMoney)
  })

  const dates = Object.keys(dailyTotals).sort()
  const amounts = dates.map((date) => dailyTotals[date].toFixed(2))

  chart.setOption({
    title: {
      text: '每日消费金额',
      left: 'center',
    },
    tooltip: {
      trigger: 'axis',
    },
    xAxis: {
      type: 'category',
      data: dates,
    },
    yAxis: {
      type: 'value',
      axisLabel: {
        formatter: '¥{value}',
      },
    },
    series: [
      {
        data: amounts,
        type: 'bar',
        smooth: true,
        name: '消费金额',
      },
    ],
  })
}

// 初始化图表并请求数据
onMounted(async () => {
  await fetchOrders()
  chart = echarts.init(document.getElementById('chart') as HTMLDivElement)
})

// 当选择店铺时重新渲染图表
watch(selectedBranch, renderChart)

const downloadExcel = async () => {
  try {
    const response = await axios.get(`/api/user/orders/export/${customerId}`, {
      responseType: 'blob', // 一定要是 blob，否则文件下载不了
    })

    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    // 你可以自定义文件名，也可以从后端 header 获取 filename
    link.setAttribute('download', `订单数据_${new Date().toISOString().slice(0, 10)}.xlsx`)
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (error) {
    ElMessage.error('导出失败，请稍后再试')
  }
}
</script>

<style scoped>
#chart {
  margin-top: 20px;
}
</style>
