<template>
  <div class="app-container">
    <!-- 顶部工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          size="mini"
          @click="handleRefresh"
          v-hasPermi="['resource:dashboard:refresh']"
        >刷新数据</el-button>
      </el-col>
    </el-row>

    <!-- 资源总览统计卡片 -->
    <el-row :gutter="20" class="mb20">
      <!-- 队伍统计 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="3" class="mb20">
        <el-card class="stat-card" shadow="hover" @click.native="handleCardClick('/resource/team')">
          <div class="stat-content">
            <div class="stat-title">队伍总数</div>
            <div class="stat-value">{{ (resourceStats.teams && resourceStats.teams.total) || 0 }}</div>
            <div class="stat-details">
              <el-tag size="mini" type="success">可用: {{ (resourceStats.teams && resourceStats.teams.available) || 0 }}</el-tag>
              <el-tag size="mini" type="warning">忙碌: {{ (resourceStats.teams && resourceStats.teams.busy) || 0 }}</el-tag>
              <el-tag size="mini" type="info">离线: {{ (resourceStats.teams && resourceStats.teams.offline) || 0 }}</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      <!-- 车辆统计 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="3" class="mb20">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-title">车辆总数</div>
            <div class="stat-value">{{ (resourceStats.vehicles && resourceStats.vehicles.total) || 0 }}</div>
            <div class="stat-details">
              <el-tag size="mini" type="success">可用: {{ (resourceStats.vehicles && resourceStats.vehicles.available) || 0 }}</el-tag>
              <el-tag size="mini" type="warning">忙碌: {{ (resourceStats.vehicles && resourceStats.vehicles.busy) || 0 }}</el-tag>
              <el-tag size="mini" type="danger">维修: {{ (resourceStats.vehicles && resourceStats.vehicles.repair) || 0 }}</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      <!-- 专家统计 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="3" class="mb20">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-title">专家总数</div>
            <div class="stat-value">{{ (resourceStats.experts && resourceStats.experts.total) || 0 }}</div>
            <div class="stat-details">
              <el-tag size="mini" type="success">活跃: {{ (resourceStats.experts && resourceStats.experts.active) || 0 }}</el-tag>
              <el-tag size="mini" type="info">停用: {{ (resourceStats.experts && resourceStats.experts.inactive) || 0 }}</el-tag>
              <el-tag size="mini" type="danger">黑名单: {{ (resourceStats.experts && resourceStats.experts.blacklisted) || 0 }}</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      <!-- 装备统计 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="3" class="mb20">
        <el-card class="stat-card" shadow="hover" @click.native="handleCardClick('/resource/equipment')">
          <div class="stat-content">
            <div class="stat-title">装备总数</div>
            <div class="stat-value">{{ (resourceStats.equipment && resourceStats.equipment.total) || 0 }}</div>
            <div class="stat-details">
              <el-tag size="mini" type="success">可用: {{ (resourceStats.equipment && resourceStats.equipment.available) || 0 }}</el-tag>
              <el-tag size="mini" type="warning">忙碌: {{ (resourceStats.equipment && resourceStats.equipment.busy) || 0 }}</el-tag>
              <el-tag size="mini" type="danger">维修: {{ (resourceStats.equipment && resourceStats.equipment.repair) || 0 }}</el-tag>
              <el-tag size="mini" type="info">报废: {{ (resourceStats.equipment && resourceStats.equipment.scrap) || 0 }}</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      <!-- 物资统计 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="3" class="mb20">
        <el-card class="stat-card" shadow="hover" @click.native="handleCardClick('/resource/material')">
          <div class="stat-content">
            <div class="stat-title">物资统计</div>
            <div class="stat-value">{{ (resourceStats.materials && resourceStats.materials.totalMaterials) || 0 }}</div>
            <div class="stat-details">
              <el-tag size="mini" type="info">分类: {{ (resourceStats.materials && resourceStats.materials.totalCategories) || 0 }}</el-tag>
              <el-tag size="mini" type="danger" v-if="resourceStats.materials && resourceStats.materials.alertCount > 0">
                预警: {{ (resourceStats.materials && resourceStats.materials.alertCount) || 0 }}
              </el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      <!-- 采购统计 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="3" class="mb20">
        <el-card class="stat-card" shadow="hover" @click.native="handleCardClick('/resource/procurement')">
          <div class="stat-content">
            <div class="stat-title">采购总数</div>
            <div class="stat-value">{{ (resourceStats.procurement && resourceStats.procurement.total) || 0 }}</div>
            <div class="stat-details">
              <el-tag size="mini" type="info">草稿: {{ (resourceStats.procurement && resourceStats.procurement.draft) || 0 }}</el-tag>
              <el-tag size="mini" type="primary">已提交: {{ (resourceStats.procurement && resourceStats.procurement.submitted) || 0 }}</el-tag>
              <el-tag size="mini" type="success">已审核: {{ (resourceStats.procurement && resourceStats.procurement.approved) || 0 }}</el-tag>
              <el-tag size="mini" type="warning">进行中: {{ (resourceStats.procurement && resourceStats.procurement.inProgress) || 0 }}</el-tag>
              <el-tag size="mini" type="success">已入库: {{ (resourceStats.procurement && resourceStats.procurement.received) || 0 }}</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
      <!-- 征用统计 -->
      <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="3" class="mb20">
        <el-card class="stat-card" shadow="hover" @click.native="handleCardClick('/resource/requisition')">
          <div class="stat-content">
            <div class="stat-title">征用总数</div>
            <div class="stat-value">{{ (resourceStats.requisition && resourceStats.requisition.total) || 0 }}</div>
            <div class="stat-details">
              <el-tag size="mini" type="info">草稿: {{ (resourceStats.requisition && resourceStats.requisition.draft) || 0 }}</el-tag>
              <el-tag size="mini" type="success">已审批: {{ (resourceStats.requisition && resourceStats.requisition.approved) || 0 }}</el-tag>
              <el-tag size="mini" type="warning">进行中: {{ (resourceStats.requisition && resourceStats.requisition.active) || 0 }}</el-tag>
              <el-tag size="mini" type="primary">已结束: {{ (resourceStats.requisition && resourceStats.requisition.ended) || 0 }}</el-tag>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第二行：库存预警（占据一整行） -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>库存预警</span>
            <el-button
              v-if="inventoryAlerts.length > 10"
              type="text"
              size="mini"
              @click="handleViewMoreAlerts"
            >查看更多</el-button>
          </div>
          <el-table
            v-loading="loadingAlerts"
            :data="inventoryAlerts.slice(0, 10)"
            border empty-text="暂无库存预警"
            style="width: 100%"
            @row-click="handleAlertRowClick"
          >
            <el-table-column label="物资名称" prop="materialName" :show-overflow-tooltip="true" min-width="150" />
            <el-table-column label="物资编码" prop="materialCode" width="120" />
            <el-table-column label="仓库名称" prop="warehouseName" width="120" />
            <el-table-column label="当前库存" prop="currentQty" width="100" align="right" />
            <el-table-column label="报警阈值" prop="threshold" width="100" align="right" />
            <el-table-column label="预警级别" prop="alertLevel" width="100" align="center">
              <template slot-scope="scope">
                <el-tag
                  :type="scope.row.alertLevel === 'critical' ? 'danger' : 'warning'"
                  size="mini"
                >
                  {{ scope.row.alertLevel === 'critical' ? '严重' : '警告' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <!-- <div v-if="inventoryAlerts.length === 0 && !loadingAlerts" class="empty-tip">
            暂无库存预警
          </div> -->
        </el-card>
      </el-col>
    </el-row>

    <!-- 第三行：采购状态统计和征用状态统计 -->
    <el-row :gutter="20" class="mb20">
      <!-- 采购状态统计 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" class="mb20">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>采购状态分布</span>
          </div>
          <div v-if="hasProcurementData" ref="procurementChart" style="width: 100%; height: 350px;" v-loading="loadingProcurement"></div>
          <div v-if="!hasProcurementData && !loadingProcurement" class="empty-tip">
            暂无数据
          </div>
        </el-card>
      </el-col>
      <!-- 征用状态统计 -->
      <el-col :xs="24" :sm="24" :md="12" :lg="12" class="mb20">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>征用状态分布</span>
          </div>
          <div v-if="hasRequisitionData" ref="requisitionChart" style="width: 100%; height: 350px;" v-loading="loadingRequisition"></div>
          <div v-if="!hasRequisitionData && !loadingRequisition" class="empty-tip">
            暂无数据
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第四行：资源状态分布（占据一整行） -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>资源状态分布</span>
          </div>
          <div v-if="hasDistributionData" ref="distributionChart" style="width: 100%; height: 350px;" v-loading="loadingDistribution"></div>
          <div v-if="!hasDistributionData && !loadingDistribution" class="empty-tip">
            暂无数据
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 第五行：资源使用趋势 -->
    <el-row :gutter="20" class="mb20">
      <el-col :span="24">
        <el-card shadow="hover">
          <div slot="header" class="card-header">
            <span>资源使用趋势</span>
            <div>
              <el-radio-group v-model="trendDays" size="mini" @change="handleTrendDaysChange">
                <el-radio-button :label="7">最近7天</el-radio-button>
                <el-radio-button :label="30">最近30天</el-radio-button>
              </el-radio-group>
            </div>
          </div>
          <div v-if="hasTrendData" ref="trendChart" style="width: 100%; height: 400px;" v-loading="loadingTrend"></div>
          <div v-if="!hasTrendData && !loadingTrend" class="empty-tip">
            暂无数据
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getResourceStats,
  getInventoryAlerts,
  getProcurementStatus,
  getRequisitionStatus,
  getResourceDistribution,
  getUsageTrends,
  refreshDashboard
} from '@/api/resource/dashboard'
import * as echarts from 'echarts'
require('echarts/theme/macarons')

export default {
  name: 'ResourceDashboard',
  data() {
    return {
      // 加载状态
      loading: false,
      loadingAlerts: false,
      loadingProcurement: false,
      loadingRequisition: false,
      loadingDistribution: false,
      loadingTrend: false,
      // 资源总览统计
      resourceStats: {},
      // 库存预警列表
      inventoryAlerts: [],
      // 采购状态统计
      procurementStatusData: {},
      procurementChart: null,
      // 征用状态统计
      requisitionStatusData: {},
      requisitionChart: null,
      // 资源状态分布
      resourceDistribution: {},
      distributionChart: null,
      // 资源使用趋势
      usageTrends: {},
      trendChart: null,
      trendDays: 7,

      hasProcurementData: false,
      hasRequisitionData: false,
      hasDistributionData: false,
      hasTrendData: false,
    }
  },
  watch: {
    procurementStatusData: {
      deep: true,
      handler() {
        this.$nextTick(() => {
          this.initProcurementChart()
        })
      }
    },
    requisitionStatusData: {
      deep: true,
      handler() {
        this.$nextTick(() => {
          this.initRequisitionChart()
        })
      }
    },
    resourceDistribution: {
      deep: true,
      handler() {
        this.$nextTick(() => {
          this.initDistributionChart()
        })
      }
    },
    usageTrends: {
      deep: true,
      handler() {
        this.$nextTick(() => {
          this.initTrendChart()
        })
      }
    }
  },
  mounted() {
    this.loadAllData()
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.handleResize)
    this.disposeCharts()
  },
  methods: {
    /** 加载所有数据 */
    loadAllData() {
      this.loadResourceStats()
      this.loadInventoryAlerts()
      this.loadProcurementStatus()
      this.loadRequisitionStatus()
      this.loadResourceDistribution()
      this.loadUsageTrends()
    },
    /** 加载资源总览统计 */
    loadResourceStats() {
      this.loading = true
      getResourceStats().then(response => {
        this.resourceStats = response.data || {}
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 加载库存预警 */
    loadInventoryAlerts() {
      this.loadingAlerts = true
      getInventoryAlerts().then(response => {
        this.inventoryAlerts = (response.data && response.data.list) || []
        this.loadingAlerts = false
      }).catch(() => {
        this.loadingAlerts = false
      })
    },
    /** 加载采购状态统计 */
    loadProcurementStatus() {
      this.loadingProcurement = true
      getProcurementStatus().then(response => {
        this.procurementStatusData = response.data || {}
        this.loadingProcurement = false
        if (this.hasProcurementData) {
          this.$nextTick(() => {
            this.initProcurementChart()
          })
        }
      }).catch(() => {
        this.loadingProcurement = false
      })
    },
    /** 加载征用状态统计 */
    loadRequisitionStatus() {
      this.loadingRequisition = true
      getRequisitionStatus().then(response => {
        this.requisitionStatusData = response.data || {}
        this.loadingRequisition = false
        if (this.hasRequisitionData) {
          this.$nextTick(() => {
            this.initRequisitionChart()
          })
        }
      }).catch(() => {
        this.loadingRequisition = false
      })
    },
    /** 加载资源状态分布 */
    loadResourceDistribution() {
      this.loadingDistribution = true
      getResourceDistribution().then(response => {
        this.resourceDistribution = response.data || {}
        this.loadingDistribution = false
        if (this.hasDistributionData) {
          this.$nextTick(() => {
            this.initDistributionChart()
          })
        }
      }).catch(() => {
        this.loadingDistribution = false
      })
    },
    /** 加载资源使用趋势 */
    loadUsageTrends() {
      this.loadingTrend = true
      getUsageTrends(this.trendDays).then(response => {
        this.usageTrends = response.data || {}
        this.loadingTrend = false
        if (this.hasTrendData) {
          this.$nextTick(() => {
            this.initTrendChart()
          })
        }
      }).catch(() => {
        this.loadingTrend = false
      })
    },
    /** 初始化采购状态饼图 */
    initProcurementChart() {
      if (!this.$refs.procurementChart) {
        return
      }
      if (this.procurementChart) {
        this.procurementChart.dispose()
      }
      this.procurementChart = echarts.init(this.$refs.procurementChart, 'macarons')
      
      const data = []
      const statusMap = {
        draft: { label: '草稿', color: '#909399' },
        submitted: { label: '已提交', color: '#409EFF' },
        approved: { label: '已审核', color: '#67C23A' },
        rejected: { label: '已驳回', color: '#F56C6C' },
        inProgress: { label: '进行中', color: '#E6A23C' },
        received: { label: '已入库', color: '#9C27B0' }
      }
      
      Object.keys(statusMap).forEach(key => {
        const value = this.procurementStatusData[key] || 0
        if (value > 0) {
          data.push({
            name: statusMap[key].label,
            value: value
          })
        }
      })
      
      if (data.length === 0) {
        return
      }
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          bottom: '10%'
        },
        series: [
          {
            name: '采购状态',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c}\n({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            data: data,
            color: data.map(item => {
              const key = Object.keys(statusMap).find(k => statusMap[k].label === item.name)
              return (statusMap[key] && statusMap[key].color) || '#409EFF'
            })
          }
        ]
      }
      
      this.procurementChart.setOption(option)
      
      // 点击事件
      this.procurementChart.off('click')
      this.procurementChart.on('click', (params) => {
        const statusMap = {
          '草稿': 'draft',
          '已提交': 'submitted',
          '已审核': 'approved',
          '已驳回': 'rejected',
          '进行中': 'in_progress',
          '已入库': 'received'
        }
        const status = statusMap[params.name]
        if (status) {
          this.$router.push({
            path: '/resource/procurement',
            query: { status }
          })
        }
      })
    },
    /** 初始化征用状态饼图 */
    initRequisitionChart() {
      if (!this.$refs.requisitionChart) {
        return
      }
      if (this.requisitionChart) {
        this.requisitionChart.dispose()
      }
      this.requisitionChart = echarts.init(this.$refs.requisitionChart, 'macarons')
      
      const data = []
      const statusMap = {
        draft: { label: '草稿', color: '#909399' },
        approved: { label: '已审批', color: '#67C23A' },
        rejected: { label: '已驳回', color: '#F56C6C' },
        active: { label: '进行中', color: '#E6A23C' },
        ended: { label: '已结束', color: '#409EFF' }
      }
      
      Object.keys(statusMap).forEach(key => {
        const value = this.requisitionStatusData[key] || 0
        if (value > 0) {
          data.push({
            name: statusMap[key].label,
            value: value
          })
        }
      })
      
      if (data.length === 0) {
        return
      }
      
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          bottom: '10%'
        },
        series: [
          {
            name: '征用状态',
            type: 'pie',
            radius: ['40%', '70%'],
            center: ['60%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              formatter: '{b}: {c}\n({d}%)'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold'
              }
            },
            data: data,
            color: data.map(item => {
              const key = Object.keys(statusMap).find(k => statusMap[k].label === item.name)
              return (statusMap[key] && statusMap[key].color) || '#409EFF'
            })
          }
        ]
      }
      
      this.requisitionChart.setOption(option)
      
      // 点击事件
      this.requisitionChart.off('click')
      this.requisitionChart.on('click', (params) => {
        const statusMap = {
          '草稿': 'draft',
          '已审批': 'approved',
          '已驳回': 'rejected',
          '进行中': 'active',
          '已结束': 'ended'
        }
        const status = statusMap[params.name]
        if (status) {
          this.$router.push({
            path: '/resource/requisition',
            query: { status }
          })
        }
      })
    },
    /** 初始化资源状态分布柱状图 */
    initDistributionChart() {
      if (!this.$refs.distributionChart) {
        return
      }
      if (this.distributionChart) {
        this.distributionChart.dispose()
      }
      this.distributionChart = echarts.init(this.$refs.distributionChart, 'macarons')
      
      const categories = []
      const availableData = []
      const busyData = []
      const otherData = []
      
      if (this.resourceDistribution.team) {
        categories.push('队伍')
        availableData.push(this.resourceDistribution.team.available || 0)
        busyData.push(this.resourceDistribution.team.busy || 0)
        otherData.push(this.resourceDistribution.team.offline || 0)
      }
      if (this.resourceDistribution.vehicle) {
        categories.push('车辆')
        availableData.push(this.resourceDistribution.vehicle.available || 0)
        busyData.push(this.resourceDistribution.vehicle.busy || 0)
        otherData.push(this.resourceDistribution.vehicle.repair || 0)
      }
      if (this.resourceDistribution.expert) {
        categories.push('专家')
        availableData.push(this.resourceDistribution.expert.active || 0)
        busyData.push(0)
        otherData.push((this.resourceDistribution.expert.inactive || 0) + (this.resourceDistribution.expert.blacklisted || 0))
      }
      if (this.resourceDistribution.equipment) {
        categories.push('装备')
        availableData.push(this.resourceDistribution.equipment.available || 0)
        busyData.push(this.resourceDistribution.equipment.busy || 0)
        otherData.push((this.resourceDistribution.equipment.repair || 0) + (this.resourceDistribution.equipment.scrap || 0))
      }
      
      if (categories.length === 0) {
        return
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            let result = params[0].name + '<br/>'
            params.forEach(param => {
              result += param.seriesName + ': ' + param.value.toFixed(1) + '%<br/>'
            })
            return result
          }
        },
        legend: {
          data: ['可用/活跃', '忙碌', '其他'],
          bottom: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: categories
        },
        yAxis: {
          type: 'value',
          max: 100,
          axisLabel: {
            formatter: '{value}%'
          }
        },
        series: [
          {
            name: '可用/活跃',
            type: 'bar',
            data: availableData,
            itemStyle: {
              color: '#67C23A'
            }
          },
          {
            name: '忙碌',
            type: 'bar',
            data: busyData,
            itemStyle: {
              color: '#E6A23C'
            }
          },
          {
            name: '其他',
            type: 'bar',
            data: otherData,
            itemStyle: {
              color: '#909399'
            }
          }
        ]
      }
      
      this.distributionChart.setOption(option)
    },
    /** 初始化资源使用趋势折线图 */
    initTrendChart() {
      if (!this.$refs.trendChart) {
        return
      }
      if (this.trendChart) {
        this.trendChart.dispose()
      }
      this.trendChart = echarts.init(this.$refs.trendChart, 'macarons')
      
      if (!this.usageTrends.dateRange || this.usageTrends.dateRange.length === 0) {
        return
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['物资消耗', '物资归还', '装备分配', '装备释放'],
          bottom: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.usageTrends.dateRange || []
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '物资消耗',
            type: 'line',
            smooth: true,
            data: this.usageTrends.materialConsume || [],
            itemStyle: {
              color: '#F56C6C'
            },
            lineStyle: {
              color: '#F56C6C',
              width: 2
            }
          },
          {
            name: '物资归还',
            type: 'line',
            smooth: true,
            data: this.usageTrends.materialReturn || [],
            itemStyle: {
              color: '#67C23A'
            },
            lineStyle: {
              color: '#67C23A',
              width: 2
            }
          },
          {
            name: '装备分配',
            type: 'line',
            smooth: true,
            data: this.usageTrends.equipmentAssign || [],
            itemStyle: {
              color: '#409EFF'
            },
            lineStyle: {
              color: '#409EFF',
              width: 2
            }
          },
          {
            name: '装备释放',
            type: 'line',
            smooth: true,
            data: this.usageTrends.equipmentRelease || [],
            itemStyle: {
              color: '#E6A23C'
            },
            lineStyle: {
              color: '#E6A23C',
              width: 2
            }
          }
        ]
      }
      
      this.trendChart.setOption(option)
    },
    /** 处理窗口大小变化 */
    handleResize() {
      this.procurementChart && this.procurementChart.resize()
      this.requisitionChart && this.requisitionChart.resize()
      this.distributionChart && this.distributionChart.resize()
      this.trendChart && this.trendChart.resize()
    },
    /** 销毁所有图表 */
    disposeCharts() {
      this.procurementChart && this.procurementChart.dispose()
      this.requisitionChart && this.requisitionChart.dispose()
      this.distributionChart && this.distributionChart.dispose()
      this.trendChart && this.trendChart.dispose()
    },
    /** 卡片点击事件 */
    handleCardClick(path) {
      if (path) {
        this.$router.push(path)
      }
    },
    /** 预警行点击事件 */
    handleAlertRowClick(row) {
      this.$router.push({
        path: '/resource/material/inventory',
        query: { materialId: row.materialId }
      })
    },
    /** 查看更多预警 */
    handleViewMoreAlerts() {
      this.$router.push('/resource/material/inventory')
    },
    /** 刷新数据 */
    handleRefresh() {
      refreshDashboard().then(() => {
        this.$modal.msgSuccess('缓存刷新成功')
        this.loadAllData()
      }).catch(() => {})
    },
    /** 趋势天数变化 */
    handleTrendDaysChange() {
      this.loadUsageTrends()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.mb20 {
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
  
  .stat-content {
    .stat-title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 10px;
    }
    
    .stat-value {
      font-size: 32px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 10px;
    }
    
    .stat-details {
      display: flex;
      flex-wrap: wrap;
      gap: 5px;
      
      .el-tag {
        margin: 0;
      }
    }
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}

.empty-tip {
  text-align: center;
  color: #909399;
  padding: 40px 0;
  font-size: 14px;
}
</style>

