<template>
    <div class="chart-container">
      <div class="panel-title">
        <div class="title">整体设备借用次数趋势</div>
       <!--  <div class="more">更多</div> -->
      </div>
  
      <div class="filter-bar">
        <button
          v-for="range in ranges"
          :key="range.value"
          :class="{ active: selectedRange === range.value }"
          @click="selectedRange = range.value"
        >
          {{ range.label }}
        </button>
      </div>
  
      <div v-if="hasData" class="chart-wrapper">
        <v-chart :option="chartOption" autoresize class="chart" />
      </div>
      <div v-else class="empty-tip">暂无数据</div>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, watch, onMounted } from 'vue'
  import VChart from 'vue-echarts'
  import { use } from 'echarts/core'
  import {
    CanvasRenderer
  } from 'echarts/renderers'
  import {
    // LineChart,
    BarChart
  } from 'echarts/charts'
  import {
    TitleComponent,
    TooltipComponent,
    GridComponent,
    LegendComponent
  } from 'echarts/components'
  import * as api from '../api'
  import { Session, Local } from '/@/utils/storage'
  
  // use([
  //   CanvasRenderer,
  //   LineChart,
  //   TitleComponent,
  //   TooltipComponent,
  //   GridComponent,
  //   LegendComponent
  // ])
  
  use([
  CanvasRenderer,
  BarChart, 
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
])

  interface BorrowTrend {
    date: string
    borrow_count: number
    total_duration: number
  }
  
  const ranges = [
    { label: '周', value: 'week' },
    { label: '月', value: 'month' },
    { label: '年', value: 'year' }
  ]
  
  const selectedRange = ref('week')
  const rawData = ref<BorrowTrend[]>([])
  
  // 本地存储相关配置 - 使用不同的键名避免与BorrowRankingList冲突
  const STORAGE_KEY = 'borrow_trends_filters'
  
  const fetchData = async () => {
    const res = await api.GetBorrowTrends(selectedRange.value)
    // const res = await api.GetBorrowTrends()
    if (res.code === 2000) {
      rawData.value = res.data.trends
    } else {
      rawData.value = []
    }
    
    // 保存当前筛选条件到本地存储
    saveFiltersToStorage()
  }
  
  // 保存筛选条件到本地存储
  const saveFiltersToStorage = () => {
    try {
      const userInfo = Session.get('userInfo')
      if (!userInfo?.username) return
      
      const filters = {
        selectedRange: selectedRange.value,
        timestamp: Date.now(), // 添加时间戳用于数据有效期控制
        version: '1.0', // 版本号用于后续数据结构升级
        component: 'BorrowTrendsChart' // 标识组件来源，便于调试和维护
      }
      
      // 使用用户名作为存储键的一部分，实现用户级别的数据隔离
      const storageKey = `${STORAGE_KEY}_${userInfo.username}`
      Local.set(storageKey, filters)
      
      console.log('BorrowTrendsChart筛选条件已保存到本地存储', filters)
    } catch (error) {
      console.error('保存BorrowTrendsChart筛选条件失败:', error)
    }
  }

  // 从本地存储恢复筛选条件
  const loadFiltersFromStorage = () => {
    try {
      const userInfo = Session.get('userInfo')
      if (!userInfo?.username) return
      
      const storageKey = `${STORAGE_KEY}_${userInfo.username}`
      const storedData = Local.get(storageKey)
      
      if (!storedData) return
      
      // 检查数据有效期（7天）
      const now = Date.now()
      const maxAge = 7 * 24 * 60 * 60 * 1000 // 7天
      if (storedData.timestamp && (now - storedData.timestamp) > maxAge) {
        Local.remove(storageKey)
        console.log('BorrowTrendsChart筛选条件已过期，已清除本地数据')
        return
      }
      
      // 验证数据来源，确保是BorrowTrendsChart组件的数据
      if (storedData.component && storedData.component !== 'BorrowTrendsChart') {
        console.warn('检测到非BorrowTrendsChart组件的数据，跳过恢复')
        return
      }
      
      // 恢复筛选条件
      if (storedData.selectedRange && ['week', 'month', 'year'].includes(storedData.selectedRange)) {
        selectedRange.value = storedData.selectedRange
        console.log('BorrowTrendsChart筛选条件已从本地存储恢复:', storedData.selectedRange)
      }
    } catch (error) {
      console.error('恢复BorrowTrendsChart筛选条件失败:', error)
      // 发生错误时清除可能损坏的数据
      const userInfo = Session.get('userInfo')
      if (userInfo?.username) {
        const storageKey = `${STORAGE_KEY}_${userInfo.username}`
        Local.remove(storageKey)
      }
    }
  }

  // 清除本地存储的筛选条件
  const clearStoredFilters = () => {
    try {
      const userInfo = Session.get('userInfo')
      if (!userInfo?.username) return
      
      const storageKey = `${STORAGE_KEY}_${userInfo.username}`
      Local.remove(storageKey)
      console.log('已清除BorrowTrendsChart本地存储的筛选条件')
    } catch (error) {
      console.error('清除BorrowTrendsChart筛选条件失败:', error)
    }
  }

  watch(selectedRange, fetchData)
  
  onMounted(() => {
    // 先恢复筛选条件，再获取数据
    loadFiltersFromStorage()
    fetchData()
  })
  
  const hasData = computed(() => rawData.value.length > 0)


  const chartOption = computed(() => {
  const dates = rawData.value.map(item => item.date)
  const borrowCounts = rawData.value.map(item => item.borrow_count)
  const durations = rawData.value.map(item => item.total_duration)

  return {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['借用次数']/* , '使用时长' */
    },
    xAxis: {
      type: 'category',
      data: dates,
      axisTick: { alignWithLabel: true }
    },
    yAxis: {
      type: 'value',
      name: '数量'
    },
    series: [
      {
        name: '借用次数',
        type: 'bar',
        data: borrowCounts,
        barWidth: '40%',
        itemStyle: {
          color: '#409EFF'
        }
      },
     /*  {
        name: '使用时长',
        type: 'bar',
        data: durations,
        barWidth: '40%',
        itemStyle: {
          color: '#67C23A'
        }
      } */
    ]
  }
})


  
  // const chartOption = computed(() => {
  //   const dates = rawData.value.map(item => item.date)
  //   const borrowCounts = rawData.value.map(item => item.borrow_count)
  //   const durations = rawData.value.map(item => item.total_duration)
  
  //   return {
  //     tooltip: {
  //       trigger: 'axis'
  //     },
  //     legend: {
  //       data: ['借用次数', '使用时长']
  //     },
  //     xAxis: {
  //       type: 'category',
  //       data: dates
  //     },
  //     yAxis: {
  //       type: 'value',
  //       name: '数量'
  //     },
  //     series: [
  //       {
  //         name: '借用次数',
  //         type: 'line',
  //         data: borrowCounts,
  //         smooth: true
  //       },
  //       {
  //         name: '使用时长',
  //         type: 'line',
  //         data: durations,
  //         smooth: true
  //       }
  //     ]
  //   }
  // })




  </script>
  
  <style scoped>
  .chart-container {
    width: 100%;
    padding: 16px;
    background: #fff;
    border-radius: 20px;
    box-sizing: border-box;
    
    @media (max-width: 768px) {
      padding: 12px;
      border-radius: 15px;
    }
    
    @media (max-width: 576px) {
      padding: 10px;
      border-radius: 12px;
    }
  }

  .panel-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
  }
  .panel-title .title {
    font-size: 20px;
    font-weight: 600;
    color: #2c3e50;
    position: relative;
    
    @media (max-width: 768px) {
      font-size: 18px;
    }
    
    @media (max-width: 576px) {
      font-size: 16px;
    }
  }
  .filter-bar {
    margin-bottom: 10px;
    
    @media (max-width: 576px) {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;
    }
  }
  .filter-bar button {
    margin-right: 8px;
    padding: 6px 12px;
    border: none;
    background: #eee;
    cursor: pointer;
    
    @media (max-width: 576px) {
      margin-right: 0;
      padding: 5px 10px;
      font-size: 14px;
      flex: 1;
      min-width: calc(33.333% - 6px);
    }
  }
  .filter-bar button.active {
    background: #409eff;
    color: white;
  }
  .empty-tip {
    text-align: center;
    color: #999;
    padding: 20px;
  }
  
  .chart-wrapper {
    width: 100%;
    height: 360px;
    
    @media (max-width: 768px) {
      height: 300px;
    }
    
    @media (max-width: 576px) {
      height: 250px;
    }
  }
  
  .chart {
    width: 100%;
    height: 100%;
  }
  </style>
  