<template>
  <div class="ranking-panel">
    <div class="panel-title">
      <div class="title">单台设备累计借用次数排名</div>
      <!--  <div class="more">更多</div> -->
    </div>
    <div class="panel-header">
      <el-row :gutter="16">
        <el-col :span="4">
          <el-select v-model="borrowType" clearable placeholder="借用类型" style="width: 100%;" @change="fetchRanking">
            <el-option label="全部" value="all" />
            <el-option label="常规借用" value="regular" />
            <el-option label="课堂借用" value="classroom" />
            <el-option label="特殊借用" value="special" />
          </el-select>
        </el-col>
        <el-col :span="10">
          <el-date-picker v-model="dateRange" type="daterange" start-placeholder="开始日期" end-placeholder="结束日期" clearable
            @change="fetchRanking" style="width: 100%;" />
        </el-col>
        <el-col :span="10">
          <el-select 
            multiple 
            v-model="deviceTagIds" 
            placeholder="标签名" 
            style="width: 270px;"
            @change="handleTagChange"
            class="select-tags">
            <el-option :value="'selectAll'" @click.native.stop="handleSelectAll">
              <el-checkbox 
                :model-value="isSelectAll" 
                @change="handleSelectAll"
                @click.native.stop>
                全选
              </el-checkbox>
            </el-option>
            <el-option v-for="item in labelType" :key="item.id" :label="item.name" :value="item.id" >
            </el-option>
          </el-select>
        </el-col>
      </el-row>
    </div>

    <el-table v-if="rankingData.length" :data="rankingData" style="width: 100%; margin-top: 20px; height: 350px"
      max-height="500" class="ranking-table">
      <el-table-column type="index" label="排名" width="60" />
      <el-table-column prop="device_name" label="设备名" min-width="120" />
      <!-- <el-table-column prop="device_name" label="标签名">
        <template #default="scope">
          <el-tag v-for="tag in scope.row.device_tags" :key="tag" :type="tag.type">{{ tag.name }}</el-tag>
        </template>
      </el-table-column> -->
      <el-table-column prop="device_code" label="设备编号" min-width="120" />
      <el-table-column prop="borrow_count" label="借用次数" min-width="100" />
      <!-- <el-table-column prop="total_quantity" label="累计借用册数" /> -->
    </el-table>

    <div v-else class="empty-tip">暂无数据</div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as api from '../api'
import { GetList } from '../../devicelabel/api'
import { Session, Local } from '/@/utils/storage';

interface RankingItem {
  user_id: number
  user_name: string
  user_code: string
  borrow_count: number
  total_quantity: number
}

interface LabelItem {
  id: number
  name: string
}

const borrowType = ref('all')
const dateRange = ref<[string, string] | null>(null)
const keyword = ref('')
const rankingData = ref<RankingItem[]>([])
// const deviceTagId = ref('')
const deviceTagIds = ref<number[]>([])

// 全选相关状态
const isSelectAll = ref(false)

// 本地存储相关配置
const STORAGE_KEY = 'borrow_ranking_filters'

// 全选/反选处理函数
const handleSelectAll = () => {
  if (isSelectAll.value) {
    // 如果当前是全选状态，则清空选择
    deviceTagIds.value = []
    isSelectAll.value = false
  } else {
    // 如果当前不是全选状态，则选择所有标签
    deviceTagIds.value = labelType.value.map(item => item.id)
    isSelectAll.value = true
  }
  fetchRanking()
}

// 监听标签选择变化，更新全选状态
const handleTagChange = () => {
  const allTagIds = labelType.value.map(item => item.id)
  isSelectAll.value = deviceTagIds.value.length === allTagIds.length && 
                     allTagIds.every(id => deviceTagIds.value.includes(id))
  fetchRanking()
}

const fetchRanking = async () => {
  const params: Record<string, any> = {
    type: borrowType.value
  }

  if (dateRange.value) {
    params.start = dateRange.value[0]
    params.end = dateRange.value[1]
  }

  if (keyword.value) {
    params.keyword = keyword.value
  }
  // if (deviceTagId.value) {
  //   params.tag_id = deviceTagId.value
  // }
  if (deviceTagIds.value.length) {
    params.tag_id = deviceTagIds.value
    // console.log("params.tag_id::",params.tag_id)
  }

  const res = await api.GetBorrowRankingComposite(params)
  if (res.code === 2000) {
    rankingData.value = res.data.device_rankings.borrow_count_ranking
  } else {
    rankingData.value = []
  }
  
  // 保存当前筛选条件到本地存储
  saveFiltersToStorage()
}

const labelType = ref<LabelItem[]>([])
const getList = async () => {
  const res = await GetList({
    page: 1,
    page_size: 20,
  })
  if (res.code === 2000) {
    labelType.value = res.data
    // 若未从本地恢复过选择，初始化为"全选"并刷新数据
    if (!deviceTagIds.value.length && Array.isArray(labelType.value) && labelType.value.length) {
      deviceTagIds.value = labelType.value.map(item => item.id)
      isSelectAll.value = true
      fetchRanking()
    } else {
      // 更新全选状态
      const allTagIds = labelType.value.map(item => item.id)
      isSelectAll.value = deviceTagIds.value.length === allTagIds.length && 
                         allTagIds.every(id => deviceTagIds.value.includes(id))
    }
  }
}

// 保存筛选条件到本地存储（无加密版本）
const saveFiltersToStorage = () => {
  try {
    const userInfo = Session.get('userInfo')
    if (!userInfo?.username) return
    
    const filters = {
      borrowType: borrowType.value,
      dateRange: dateRange.value,
      deviceTagIds: deviceTagIds.value,
      isSelectAll: isSelectAll.value,
      timestamp: Date.now(), // 添加时间戳用于数据有效期控制
      version: '1.0' // 版本号用于后续数据结构升级
    }
    
    // 使用用户名作为存储键的一部分，实现用户级别的数据隔离
    const storageKey = `${STORAGE_KEY}_${userInfo.username}`
    Local.set(storageKey, filters)
    
    console.log('筛选条件已保存到本地存储',filters)
  } catch (error) {
    console.error('保存筛选条件失败:', 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('筛选条件已过期，已清除本地数据')
      return
    }
    
    // 恢复筛选条件
    if (storedData.borrowType) {
      borrowType.value = storedData.borrowType
    }
    if (storedData.dateRange) {
      dateRange.value = storedData.dateRange
    }
    if (storedData.deviceTagIds && Array.isArray(storedData.deviceTagIds)) {
      deviceTagIds.value = storedData.deviceTagIds
    }
    if (typeof storedData.isSelectAll === 'boolean') {
      isSelectAll.value = storedData.isSelectAll
    }
    
    console.log('筛选条件已从本地存储恢复')
  } catch (error) {
    console.error('恢复筛选条件失败:', 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('已清除本地存储的筛选条件')
  } catch (error) {
    console.error('清除筛选条件失败:', error)
  }
}

// 重置筛选条件
const resetFilters = () => {
  borrowType.value = 'all'
  dateRange.value = null
  deviceTagIds.value = []
  isSelectAll.value = false
  
  // 清除本地存储
  clearStoredFilters()
  
  // 重新获取数据
  fetchRanking()
}

onMounted(() => {
  // 先恢复筛选条件，再获取数据
  loadFiltersFromStorage()
  fetchRanking()
  if(Session.get('userInfo').username =='平台管理员') return
  getList()
})
</script>

<style scoped>
.ranking-panel {
  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;
  }
}

.panel-title .more {
  font-size: 14px;
  color: #999;
  cursor: pointer;
}

.panel-header {
  width: 100%;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 16px;
  
  @media (max-width: 768px) {
    margin-bottom: 12px;
    
    :deep(.el-row) {
      margin: 0 !important;
    }
    
    :deep(.el-col) {
      margin-bottom: 10px;
    }
  }
  
  @media (max-width: 576px) {
    margin-bottom: 10px;
    
    :deep(.el-select),
    :deep(.el-date-picker) {
      width: 100% !important;
    }
  }
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 20px;
}

:deep(.el-table) {
  border: none !important;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: 400;
  border-bottom: 1px solid #EBEEF5;
}

:deep(.el-table td) {
  color: #606266;
}

:deep(.el-table--border) {
  border: none;
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}

/* 多选下拉框样式优化 */
:deep(.el-select__tags) {
  max-width: 100%;
  overflow: hidden;
  white-space: nowrap;
  flex-wrap: nowrap;
}

:deep(.el-tag) {
  margin-right: 6px;
  margin-bottom: 0;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.el-select__input) {
  min-width: 60px;
}
:deep(.select-tags .el-select__selection){
  overflow: auto;
  flex-wrap: nowrap;
  /* 隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

:deep(.select-tags .el-select__selection)::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

/* 全选选项样式优化 */
:deep(.el-select-dropdown__item) {
  padding: 8px 20px;
}

:deep(.el-select-dropdown__item .el-checkbox) {
  margin-right: 8px;
}

:deep(.el-select-dropdown__item .el-checkbox__label) {
  font-size: 14px;
  color: #606266;
}

/* 表格响应式优化 */
.ranking-table {
  @media (max-width: 768px) {
    :deep(.el-table__body-wrapper) {
      overflow-x: auto;
    }
    
    :deep(.el-table__header-wrapper) {
      overflow-x: auto;
    }
  }
  
  @media (max-width: 576px) {
    font-size: 14px;
    
    :deep(.el-table th),
    :deep(.el-table td) {
      padding: 8px 5px;
      font-size: 12px;
    }
    
    :deep(.el-table-column--index) {
      width: 50px !important;
    }
  }
}
</style>