<template>
  <el-row :gutter="24" class="row-container">
    <el-col :span="24">
      <el-card title="" class="dashboard-chart-card">
        <div class="condition">
          <el-tabs v-model="tabActive" @tab-click="changeTab">
            <el-tab-pane
              v-for="(item, index) in tabData"
              :key="index"
              :value="item.id"
              :label="item.name"
              :name="index"
            >
            </el-tab-pane>
          </el-tabs>

          <div class="times">
            <ul class="date">
              <li
                v-for="(item, index) in dateData"
                :key="index"
                :class="active === index ? 'active' : ''"
                @click="changeActive(index)"
              >
                {{ item }}
              </li>
            </ul>
            <div class="dateCon">{{ startDate }} 至 {{ endDate }}</div>
          </div>
        </div>
        
        <!-- 加载状态 -->
        <div v-if="loading" style="text-align: center; padding: 50px;">
          <el-icon class="is-loading"><Loading /></el-icon>
          <p>加载中...</p>
        </div>
        
        <!-- 按摩时长趋势 -->
        <div v-else-if="tabActive === 0">
          <MassageDurationChart
            :dateData="durationData"
            :timeRange="timeRangeType"
          />
        </div>
        
        <!-- 按摩头类型分布 -->
        <div v-else-if="tabActive === 1">
          <HeadTypeChart
            :chartData="headTypeData"
          />
        </div>
        
        <!-- 按摩部位统计 -->
        <div v-else-if="tabActive === 2">
          <BodyPartChart
            :chartData="bodyPartData"
          />
        </div>
      </el-card>
    </el-col>
  </el-row>
</template>

<script setup>
import { onMounted, ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { getDateInfo } from '@/utils/date'
import MassageDurationChart from './MassageDurationChart.vue'
import HeadTypeChart from './HeadTypeChart.vue'
import BodyPartChart from './BodyPartChart.vue'
import {
  getDailyStats,
  getHeadTypeStats,
  getBodyPartStats
} from '@/api/task/task'

const dateData = ref(['今日', '本周', '本月'])
const tabData = ref([
  { id: 0, name: '按摩时长趋势' },
  { id: 1, name: '按摩头类型' },
  { id: 2, name: '按摩部位' }
])

const active = ref(1) // 默认选中本周
const tabActive = ref(0)
const startDate = ref('')
const endDate = ref('')
const loading = ref(false)
const timeRangeType = ref('week') // today, week, month

// 图表数据
const durationData = ref([])
const headTypeData = ref([])
const bodyPartData = ref([])
// 获取图表数据
const fetchChartData = async () => {
  loading.value = true
  try {
    const params = {
      startTime: startDate.value,
      endTime: endDate.value
    }
    
    if (tabActive.value === 0) {
      // 按摩时长趋势
      const res = await getDailyStats(params)
      durationData.value = res.data || []
    } else if (tabActive.value === 1) {
      // 按摩头类型分布
      const res = await getHeadTypeStats(params)
      headTypeData.value = res.data || []
    } else if (tabActive.value === 2) {
      // 按摩部位统计
      const res = await getBodyPartStats(params)
      bodyPartData.value = res.data || []
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 默认加载本周数据
  getWeekDate()
  nextTick(() => {
    fetchChartData()
  })
})
// 触发 tab切换
const changeTab = () => {
  // 切换tab时保持当前时间范围
  nextTick(() => {
    fetchChartData()
  })
}
// 触发本日、本周、本月
const changeActive = (i) => {
  active.value = i
  
  if (i === 0) {
    getDate()
    timeRangeType.value = 'today'
  } else if (i === 1) {
    getWeekDate()
    timeRangeType.value = 'week'
  } else {
    getMonthDate()
    timeRangeType.value = 'month'
  }
  
  nextTick(() => {
    fetchChartData()
  })
}
// 获取本日
const getDate = () => {
  const today = getDateInfo(new Date())
  startDate.value = today
  endDate.value = today
}

// 获取本周
const getWeekDate = () => {
  const now = new Date();
  
  // 获取本周的周一
  const monday = new Date(now);
  monday.setDate(now.getDate() - (now.getDay() || 7) + 1);
  
  // 获取本周的周日
  const sunday = new Date(monday);
  sunday.setDate(monday.getDate() + 6);
  
  startDate.value = formatDate(monday);
  endDate.value = formatDate(sunday);
}

// 获取本月
const getMonthDate = () => {
  const date = getMonthDates()
  startDate.value = getDateInfo(date.firstDay)
  endDate.value = getDateInfo(date.lastDay)
}
// 获得本周的开始时间：
const getStartDayOfWeek = (time) => {
  const now = new Date(time) // 当前日期
  const nowDayOfWeek = now.getDay() // 今天本周的第几天
  const day = nowDayOfWeek || 7
  const nowDay = now.getDate() // 当前日
  const nowMonth = now.getMonth() // 当前月
  return formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 0 - day)) // 0代表从周日至周六；1代表周一至周日
}
// 获得本周的结束时间：
const getEndDayOfWeek = (time) => {
  const now = new Date(time) // 当前日期
  const nowDayOfWeek = now.getDay() // 今天本周的第几天
  const day = nowDayOfWeek || 7
  const nowDay = now.getDate() // 当前日
  const nowMonth = now.getMonth() // 当前月
  return formatDate(new Date(now.getFullYear(), nowMonth, nowDay + 6 - day)) // 6代表从周日至周六；7代表周一至周日
}
// 日期格式化
const formatDate = (date) => {
  const myyear = date.getFullYear()
  let mymonth = date.getMonth() + 1
  let myweekday = date.getDate()
  if (mymonth < 10) {
    mymonth = `0${mymonth}`
  }
  if (myweekday < 10) {
    myweekday = `0${myweekday}`
  }
  return `${myyear}-${mymonth}-${myweekday}`
}
// 本月的开始结束时间
const getMonthDates = () => {
  const today = new Date()
  // 获取当前月份的第一天
  const firstDay = new Date(today.getFullYear(), today.getMonth(), 1)
  // 获取当前月份的最后一天
  const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0)
  return {
    firstDay,
    lastDay
  }
}
</script>

<style lang="scss" scoped>
.condition {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  
  .times {
    display: flex;
    align-items: center;
    
    .date {
      display: flex;
      list-style: none;
      padding: 0;
      margin: 0;
      margin-right: 20px;
      
      li {
        padding: 5px 15px;
        margin: 0 5px;
        cursor: pointer;
        border-radius: 4px;
        transition: all 0.3s;
        
        &:hover {
          background-color: #f0f2f5;
        }
        
        &.active {
          background-color: #409eff;
          color: #fff;
        }
      }
    }
    
    .dateCon {
      color: #666;
      font-size: 14px;
    }
  }
}

.dashboard-chart-card {
  min-height: 450px;
  max-height: 550px;
  :deep(.el-card__body) {
    padding: 15px 20px;
    min-height: 450px;
    max-height: 550px;
    overflow-y: auto;
    overflow-x: hidden;
  }
  
  /* 自定义滚动条样式 */
  :deep(.el-card__body::-webkit-scrollbar) {
    width: 6px;
  }
  
  :deep(.el-card__body::-webkit-scrollbar-track) {
    background: #f1f1f1;
    border-radius: 3px;
  }
  
  :deep(.el-card__body::-webkit-scrollbar-thumb) {
    background: #888;
    border-radius: 3px;
  }
  
  :deep(.el-card__body::-webkit-scrollbar-thumb:hover) {
    background: #555;
  }
}

/* 响应式高度调整 */
@media (max-height: 768px) {
  .dashboard-chart-card :deep(.el-card__body) {
    min-height: 380px;
    max-height: 420px;
  }
}

@media (min-height: 1080px) {
  .dashboard-chart-card :deep(.el-card__body) {
    min-height: 500px;
    max-height: 600px;
  }
}
</style>
