<template>
  <div class="statistics-dashboard">
    <el-page-header @back="$router.back()" title="返回" content="统计报表" />

    <!-- 筛选条件 -->
    <el-card style="margin-top: 20px">
      <div class="filter-section">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateChange"
        />
        <el-button type="primary" :icon="Refresh" @click="refreshData">
          刷新数据
        </el-button>
        <el-button :icon="Download" @click="exportReport">
          导出报表
        </el-button>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon total">
              <el-icon :size="32"><Box /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overview.totalAssets || 0 }}</div>
              <div class="stat-label">资产总数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon success">
              <el-icon :size="32"><CircleCheck /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overview.assetsInUse || 0 }}</div>
              <div class="stat-label">在用资产</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon warning">
              <el-icon :size="32"><CircleClose /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overview.assetsMaintenance || 0 }}</div>
              <div class="stat-label">维修中</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-content">
            <div class="stat-icon danger">
              <el-icon :size="32"><Delete /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ overview.assetsScrapped || 0 }}</div>
              <div class="stat-label">待报废</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 图表区域 -->
    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 资产状态分布 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>资产状态分布</span>
          </template>
          <v-chart
            :option="statusPieOption"
            :style="{ height: '350px' }"
            autoresize
          />
        </el-card>
      </el-col>

      <!-- 资产类型分布 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>资产类型分布</span>
          </template>
          <v-chart
            :option="typeBarOption"
            :style="{ height: '350px' }"
            autoresize
          />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 资产价值趋势 -->
      <el-col :span="24">
        <el-card>
          <template #header>
            <span>资产价值趋势</span>
          </template>
          <v-chart
            :option="valueTrendOption"
            :style="{ height: '400px' }"
            autoresize
          />
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" style="margin-top: 20px">
      <!-- 机构分布 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>机构资产分布</span>
          </template>
          <v-chart
            :option="orgDistributionOption"
            :style="{ height: '400px' }"
            autoresize
          />
        </el-card>
      </el-col>

      <!-- 维修统计 -->
      <el-col :span="12">
        <el-card>
          <template #header>
            <span>维修统计</span>
          </template>
          <v-chart
            :option="maintenanceOption"
            :style="{ height: '400px' }"
            autoresize
          />
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Download, Box, CircleCheck, CircleClose, Delete } from '@element-plus/icons-vue'
import { getStatisticsOverview, getStatisticsTrend } from '@/api'
import VChart from 'vue-echarts'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { PieChart, BarChart, LineChart, TreeChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'

// 注册ECharts组件
use([
  CanvasRenderer,
  PieChart,
  BarChart,
  LineChart,
  TreeChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const dateRange = ref<string[]>([])
const overview = reactive({
  totalAssets: 0,
  assetsInUse: 0,
  assetsInStock: 0,
  assetsMaintenance: 0,
  assetsScrapped: 0,
  totalValue: 0
})

// 资产状态分布饼图配置
const statusPieOption = ref({
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '资产状态',
      type: 'pie',
      radius: ['40%', '70%'],
      avoidLabelOverlap: false,
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: 16,
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: [
        { value: 735, name: '在用', itemStyle: { color: '#409EFF' } },
        { value: 580, name: '在库', itemStyle: { color: '#67C23A' } },
        { value: 484, name: '维修中', itemStyle: { color: '#E6A23C' } },
        { value: 300, name: '待报废', itemStyle: { color: '#F56C6C' } }
      ]
    }
  ]
})

// 资产类型分布柱状图配置
const typeBarOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['计算机', '打印机', '复印机', '扫描仪', '投影仪', '服务器']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '数量',
      type: 'bar',
      barWidth: '60%',
      data: [326, 208, 156, 98, 76, 45],
      itemStyle: {
        color: '#409EFF'
      }
    }
  ]
})

// 资产价值趋势折线图配置
const valueTrendOption = ref({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: ['资产数量', '资产价值']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['1月', '2月', '3月', '4月', '5月', '6月']
  },
  yAxis: [
    {
      type: 'value',
      name: '数量',
      position: 'left'
    },
    {
      type: 'value',
      name: '价值(万元)',
      position: 'right'
    }
  ],
  series: [
    {
      name: '资产数量',
      type: 'line',
      data: [120, 132, 101, 134, 90, 230],
      smooth: true,
      itemStyle: {
        color: '#409EFF'
      }
    },
    {
      name: '资产价值',
      type: 'line',
      yAxisIndex: 1,
      data: [220, 182, 191, 234, 290, 330],
      smooth: true,
      itemStyle: {
        color: '#67C23A'
      }
    }
  ]
})

// 机构分布图配置
const orgDistributionOption = ref({
  tooltip: {
    trigger: 'item',
    triggerOn: 'mousemove'
  },
  series: [
    {
      type: 'tree',
      data: [
        {
          name: '广东省',
          children: [
            {
              name: '广州市',
              value: 300,
              children: [
                { name: '天河网点', value: 150 },
                { name: '越秀网点', value: 100 },
                { name: '海珠网点', value: 50 }
              ]
            },
            {
              name: '深圳市',
              value: 250,
              children: [
                { name: '福田网点', value: 120 },
                { name: '南山网点', value: 80 },
                { name: '罗湖网点', value: 50 }
              ]
            }
          ]
        }
      ],
      top: '10%',
      left: '10%',
      bottom: '10%',
      right: '20%',
      symbolSize: 7,
      label: {
        position: 'left',
        verticalAlign: 'middle',
        align: 'right',
        fontSize: 12
      },
      leaves: {
        label: {
          position: 'right',
          verticalAlign: 'middle',
          align: 'left'
        }
      },
      emphasis: {
        focus: 'descendant'
      },
      expandAndCollapse: true,
      animationDuration: 550,
      animationDurationUpdate: 750
    }
  ]
})

// 维修统计图配置
const maintenanceOption = ref({
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  legend: {
    data: ['硬件故障', '软件故障', '其他']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    data: ['1月', '2月', '3月', '4月', '5月', '6月']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '硬件故障',
      type: 'bar',
      stack: 'total',
      data: [320, 302, 301, 334, 390, 330],
      itemStyle: {
        color: '#F56C6C'
      }
    },
    {
      name: '软件故障',
      type: 'bar',
      stack: 'total',
      data: [120, 132, 101, 134, 90, 230],
      itemStyle: {
        color: '#409EFF'
      }
    },
    {
      name: '其他',
      type: 'bar',
      stack: 'total',
      data: [220, 182, 191, 234, 290, 330],
      itemStyle: {
        color: '#E6A23C'
      }
    }
  ]
})

// 获取统计数据
const fetchOverview = async () => {
  try {
    const data = await getStatisticsOverview()
    Object.assign(overview, data)
  } catch (error) {
    console.error('获取统计数据失败', error)
  }
}

// 获取趋势数据
const fetchTrend = async () => {
  try {
    const data = await getStatisticsTrend({ period: 'month' })
    // TODO: 更新图表数据
  } catch (error) {
    console.error('获取趋势数据失败', error)
  }
}

// 日期范围变化
const handleDateChange = () => {
  refreshData()
}

// 刷新数据
const refreshData = () => {
  fetchOverview()
  fetchTrend()
  ElMessage.success('数据已刷新')
}

// 导出报表
const exportReport = () => {
  ElMessage.info('导出功能开发中')
}

// 初始化
onMounted(() => {
  fetchOverview()
  fetchTrend()
})
</script>

<style scoped lang="scss">
.statistics-dashboard {
  .filter-section {
    display: flex;
    gap: 12px;
    align-items: center;
  }

  .stat-card {
    .stat-content {
      display: flex;
      align-items: center;
      gap: 20px;

      .stat-icon {
        width: 60px;
        height: 60px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;

        &.total {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: #fff;
        }

        &.success {
          background: linear-gradient(135deg, #67C23A 0%, #85ce61 100%);
          color: #fff;
        }

        &.warning {
          background: linear-gradient(135deg, #E6A23C 0%, #f0c78a 100%);
          color: #fff;
        }

        &.danger {
          background: linear-gradient(135deg, #F56C6C 0%, #f89898 100%);
          color: #fff;
        }
      }

      .stat-info {
        flex: 1;

        .stat-value {
          font-size: 32px;
          font-weight: bold;
          color: #303133;
          line-height: 1.2;
        }

        .stat-label {
          font-size: 14px;
          color: #909399;
          margin-top: 8px;
        }
      }
    }
  }
}
</style>
