<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import Chart from '@/components/Chart.vue'
import { dataQueryService } from '@/api/reservation'
import { ElLoading } from 'element-plus'
import { baseURL } from '@/utils/request.js'
// 时间范围选项
const timeRangeOptions = ref([
  { label: '全部数据', value: '全部数据' },
  { label: '今年', value: '今年' },
  { label: '本月', value: '本月' },
  { label: '近三月', value: '近三月' }
])

// 账单年份选项
const yearOptions = ref([
  { label: '本年账单', value: 'current' },
  { label: '去年账单', value: 'last' }
])

// 选中的时间范围
const selectedTimeRange = ref('全部数据')

// 选中的账单年份
const selectedYear = ref('current')

// 模拟从后端获取的预约数据
const reservationData = ref([])
const isLoading = ref(true)

// 模拟数据加载
const loadData = async (timeRange = '全部数据') => {
  isLoading.value = true
  try {
    const {
      data: { data }
    } = await dataQueryService(timeRange)
    // 确保数据是一个数组
    if (Array.isArray(data)) {
      reservationData.value = data
    } else {
      console.error('数据格式不正确，预期为数组')
      reservationData.value = []
    }
  } catch (error) {
    console.error('数据加载失败:', error)
    reservationData.value = []
  } finally {
    isLoading.value = false
  }
}

// 监听时间范围变化，重新加载数据
watch(selectedTimeRange, (newValue) => {
  loadData(newValue)
})

// 数据分析
const totalReservations = computed(() => reservationData.value.length)
const totalUsers = computed(() => {
  const userIds = reservationData.value.map((item) => item.userId)
  return [...new Set(userIds)].length
})

const averageDuration = computed(() => {
  if (reservationData.value.length === 0) return '0.00'
  const durations = reservationData.value.map((item) => {
    const start = item.startTime.split(':').map(Number)
    const end = item.endTime.split(':').map(Number)
    const startInMinutes = start[0] * 60 + start[1]
    const endInMinutes = end[0] * 60 + end[1]
    return (endInMinutes - startInMinutes) / 60
  })
  return (durations.reduce((a, b) => a + b, 0) / durations.length).toFixed(2)
})

// 折线图
const lineOption = computed(() => {
  const dailyCounts = getDailyReservationCounts()
  return {
    title: {
      text: `(${getRangeText(selectedTimeRange.value)})每日预约数量趋势`
    },
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: Object.keys(dailyCounts) },
    yAxis: { type: 'value' },
    series: [
      {
        data: Object.values(dailyCounts),
        type: 'line'
      }
    ]
  }
})

// 辅助函数
const getDailyReservationCounts = () => {
  const counts = {}
  reservationData.value.forEach((item) => {
    const date = item.reservationDate
    counts[date] = (counts[date] || 0) + 1
  })
  return counts
}

// 获取时间范围文本
const getRangeText = (range) => {
  const textMap = {
    all: '全部数据',
    thisYear: '今年',
    thisMonth: '本月',
    lastThreeMonths: '近三月'
  }
  return textMap[range] || range
}

// 账单导出函数
const exportPayments = async () => {
  const loadingInstance = ElLoading.service({
    lock: true,
    text: `账单导出中...`,
    background: 'rgba(0,0,0,0.7)'
  })

  try {
    // 创建隐藏下载链接
    const iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    iframe.src = baseURL + `/reservation/payment?year=${selectedYear.value}`
    document.body.appendChild(iframe)

    // 3秒后清理资源
    setTimeout(() => {
      document.body.removeChild(iframe)
      loadingInstance.close()
      ElMessage.success(`账单导出成功，即将开始下载`)
    }, 3000)
  } catch (error) {
    loadingInstance.close()
    ElMessage.error('导出失败: ' + error.message)
  }
}

// 页面加载时执行
onMounted(() => {
  loadData()
})
</script>

<template>
  <page-container title="预约数据分析">
    <template #extra>
      <el-row>
        <el-select
          v-model="selectedYear"
          placeholder="选择年份"
          style="width: 150px"
        >
          <el-option
            v-for="option in yearOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
        <el-button
          type="primary"
          @click="exportPayments"
          style="margin-left: 10px"
        >
          账单导出
        </el-button>
      </el-row>
    </template>

    <!-- 添加时间范围选择下拉框 -->
    <el-row :gutter="20" class="mb-30">
      <el-col :span="6">
        <el-select
          v-model="selectedTimeRange"
          placeholder="请选择时间范围"
          style="width: 200px"
        >
          <el-option
            v-for="option in timeRangeOptions"
            :key="option.value"
            :label="option.label"
            :value="option.value"
          />
        </el-select>
      </el-col>
    </el-row>

    <div class="chart-container">
      <Chart
        :option="lineOption"
        width="100%"
        height="500px"
        v-if="!isLoading"
      />

      <div class="data-summary" v-if="!isLoading">
        <div class="summary-item">
          <span class="label">总预约数：</span>
          <span class="value">{{ totalReservations }}</span>
        </div>
        <div class="summary-item">
          <span class="label">总用户数：</span>
          <span class="value">{{ totalUsers }}</span>
        </div>
        <div class="summary-item">
          <span class="label">平均预约时长：</span>
          <span class="value">{{ averageDuration }} 小时</span>
        </div>
      </div>
    </div>
  </page-container>
</template>

<style scoped>
.chart-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  position: relative;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-spinner {
  text-align: center;
}

.loading-spinner i {
  font-size: 40px;
  color: #409eff;
  animation: spin 1s linear infinite;
}

.loading-spinner p {
  margin-top: 20px;
  color: #606266;
  font-size: 16px;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.data-summary {
  margin-top: 30px;
  padding: 20px;
  background: #f5f7fa;
  border-radius: 8px;
  display: flex;
  justify-content: space-around;
}

.summary-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.label {
  font-weight: 500;
  color: #606266;
  margin-bottom: 8px;
}

.value {
  font-weight: 600;
  color: #303133;
  font-size: 18px;
}
</style>
