<template>
  <div class="reports-view">
    <div class="view-header">
      <div class="header-actions">
        <el-button type="primary" @click="exportReport">
          <el-icon><Download /></el-icon>
          导出报表
        </el-button>
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>
    
    <div class="view-content">
      <!-- 过滤条件 -->
      <el-card shadow="hover" class="filter-card">
        <el-form :model="filterForm" :inline="true" label-width="100px">
          <el-form-item label="报表类型">
            <el-select v-model="filterForm.reportType" placeholder="请选择报表类型" clearable filterable style="width: 120px;">
              <el-option label="出入库汇总" value="summary"></el-option>
              <el-option label="周转率分析" value="turnover"></el-option>
              <el-option label="效率分析" value="efficiency"></el-option>
              <el-option label="异常统计" value="exception"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="时间范围">
            <el-date-picker
              v-model="filterForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              class="date-picker"
            ></el-date-picker>
          </el-form-item>
          
          <el-form-item label="物资类别">
            <el-select v-model="filterForm.materialCategory" placeholder="请选择物资类别" clearable filterable style="width: 150px;">
              <el-option label="钢材" value="steel"></el-option>
              <el-option label="铝材" value="aluminum"></el-option>
              <el-option label="五金配件" value="hardware"></el-option>
              <el-option label="电子元件" value="electronics"></el-option>
              <el-option label="其他" value="other"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="操作类型">
            <el-select v-model="filterForm.operationType" placeholder="请选择操作类型" clearable filterable style="width: 150px;">
              <el-option label="入库" value="inbound"></el-option>
              <el-option label="出库" value="outbound"></el-option>
              <el-option label="全部" value="all"></el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="searchReport">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
      
      <!-- 报表内容 -->
      <div class="report-content">
        <!-- 统计卡片 -->
        <div class="stats-cards">
          <el-card shadow="hover" class="stat-card">
            <el-statistic title="总出入库量" :value="statistics.totalQuantity" suffix="件"></el-statistic>
          </el-card>
          <el-card shadow="hover" class="stat-card">
            <el-statistic title="入库量" :value="statistics.inboundQuantity" suffix="件" :value-style="{ color: '#67C23A' }"></el-statistic>
          </el-card>
          <el-card shadow="hover" class="stat-card">
            <el-statistic title="出库量" :value="statistics.outboundQuantity" suffix="件" :value-style="{ color: '#F56C6C' }"></el-statistic>
          </el-card>
          <el-card shadow="hover" class="stat-card">
            <el-statistic title="周转率" :value="statistics.turnoverRate" suffix="%" :value-style="{ color: '#E6A23C' }"></el-statistic>
          </el-card>
          <el-card shadow="hover" class="stat-card">
            <el-statistic title="平均库存" :value="statistics.averageInventory" suffix="件" :value-style="{ color: '#409EFF' }"></el-statistic>
          </el-card>
          <el-card shadow="hover" class="stat-card">
            <el-statistic title="库存周转天数" :value="statistics.turnoverDays" suffix="天" :value-style="{ color: '#909399' }"></el-statistic>
          </el-card>
          <el-card shadow="hover" class="stat-card">
            <el-statistic title="作业效率" :value="statistics.operationEfficiency" suffix="件/小时" :value-style="{ color: '#67C23A' }"></el-statistic>
          </el-card>
          <el-card shadow="hover" class="stat-card">
            <el-statistic title="异常率" :value="statistics.exceptionRate" suffix="%" :value-style="{ color: '#F56C6C' }"></el-statistic>
          </el-card>
        </div>
        
        <!-- 图表区域 -->
        <div class="charts-section">
          <!-- 趋势图 -->
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="card-header">
                <span>出入库趋势分析</span>
                <el-select v-model="trendChartType" placeholder="选择图表类型" class="chart-type-select">
                  <el-option label="折线图" value="line"></el-option>
                  <el-option label="柱状图" value="bar"></el-option>
                </el-select>
              </div>
            </template>
            <div ref="trendChartRef" class="chart-container"></div>
          </el-card>
          
          <!-- 饼图 -->
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="card-header">
                <span>物资类别分布</span>
              </div>
            </template>
            <div ref="distributionChartRef" class="chart-container"></div>
          </el-card>
          
          <!-- 周转率分析图 -->
          <el-card shadow="hover" class="chart-card full-width">
            <template #header>
              <div class="card-header">
                <span>周转率与效率分析</span>
              </div>
            </template>
            <div ref="turnoverChartRef" class="chart-container"></div>
          </el-card>
        </div>
        
        <!-- 详细报表数据 -->
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>{{ getReportTitle(filterForm.reportType) }} - 详细数据</span>
              <el-button size="small" @click="expandAllRows">
                <el-icon><Expand /></el-icon>
                展开全部
              </el-button>
            </div>
          </template>
          
          <el-table :data="reportData" style="width: 100%" v-loading="loading">
            <el-table-column prop="date" label="日期" width="150"></el-table-column>
            <el-table-column prop="materialCategory" label="物资类别" width="120">
              <template #default="scope">
                <el-tag :type="getMaterialCategoryType(scope.row.materialCategory)">
                  {{ getMaterialCategoryName(scope.row.materialCategory) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="inboundQuantity" label="入库量" width="120" align="right"></el-table-column>
            <el-table-column prop="outboundQuantity" label="出库量" width="120" align="right"></el-table-column>
            <el-table-column prop="totalQuantity" label="总数量" width="120" align="right"></el-table-column>
            <el-table-column prop="turnoverRate" label="周转率(%)" width="150" align="right">
              <template #default="scope">
                <el-progress :percentage="scope.row.turnoverRate" :color="scope.row.turnoverRate > 50 ? '#67C23A' : '#E6A23C'" :stroke-width="8" size="small"></el-progress>
              </template>
            </el-table-column>
            <el-table-column prop="efficiency" label="效率(件/小时)" width="150" align="right"></el-table-column>
            <el-table-column prop="exceptionCount" label="异常次数" width="120" align="right">
              <template #default="scope">
                <el-tag :type="scope.row.exceptionCount > 0 ? 'danger' : 'success'">
                  {{ scope.row.exceptionCount }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="200"></el-table-column>
          </el-table>
          
          <div class="table-pagination">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pagination.currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pagination.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="reportData.length"
            ></el-pagination>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { Download, Refresh, Search, Expand } from '@element-plus/icons-vue'
import { ElMessage as elMessage } from 'element-plus'
import * as echarts from 'echarts'

// 过滤条件
const filterForm = reactive({
  reportType: 'summary',
  dateRange: null,
  materialCategory: '',
  operationType: ''
})

// 加载状态
const loading = ref(false)

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
})

// 图表引用
const trendChartRef = ref<HTMLElement | null>(null)
const distributionChartRef = ref<HTMLElement | null>(null)
const turnoverChartRef = ref<HTMLElement | null>(null)

// 图表实例
let trendChart: echarts.ECharts | null = null
let distributionChart: echarts.ECharts | null = null
let turnoverChart: echarts.ECharts | null = null

// 图表类型
const trendChartType = ref('line')

// 统计数据
const statistics = reactive({
  totalQuantity: 2568,
  inboundQuantity: 1324,
  outboundQuantity: 1244,
  turnoverRate: 48.5,
  averageInventory: 5200,
  turnoverDays: 18.5,
  operationEfficiency: 35.8,
  exceptionRate: 1.2
})

// 报表数据
const reportData = ref([
  {
    date: '2024-12-01',
    materialCategory: 'steel',
    inboundQuantity: 56,
    outboundQuantity: 48,
    totalQuantity: 104,
    turnoverRate: 46.2,
    efficiency: 24.5,
    exceptionCount: 2,
    remark: '正常'
  },
  {
    date: '2024-12-02',
    materialCategory: 'aluminum',
    inboundQuantity: 34,
    outboundQuantity: 42,
    totalQuantity: 76,
    turnoverRate: 55.3,
    efficiency: 28.3,
    exceptionCount: 0,
    remark: '正常'
  },
  {
    date: '2024-12-03',
    materialCategory: 'hardware',
    inboundQuantity: 89,
    outboundQuantity: 76,
    totalQuantity: 165,
    turnoverRate: 46.1,
    efficiency: 26.8,
    exceptionCount: 1,
    remark: '少量异常'
  },
  {
    date: '2024-12-04',
    materialCategory: 'electronics',
    inboundQuantity: 123,
    outboundQuantity: 118,
    totalQuantity: 241,
    turnoverRate: 48.9,
    efficiency: 31.2,
    exceptionCount: 3,
    remark: '部分物资质量问题'
  },
  {
    date: '2024-12-05',
    materialCategory: 'other',
    inboundQuantity: 45,
    outboundQuantity: 51,
    totalQuantity: 96,
    turnoverRate: 53.1,
    efficiency: 22.7,
    exceptionCount: 0,
    remark: '正常'
  },
  {
    date: '2024-12-06',
    materialCategory: 'steel',
    inboundQuantity: 78,
    outboundQuantity: 82,
    totalQuantity: 160,
    turnoverRate: 51.2,
    efficiency: 25.9,
    exceptionCount: 1,
    remark: '正常'
  },
  {
    date: '2024-12-07',
    materialCategory: 'aluminum',
    inboundQuantity: 67,
    outboundQuantity: 59,
    totalQuantity: 126,
    turnoverRate: 46.8,
    efficiency: 23.4,
    exceptionCount: 0,
    remark: '正常'
  },
  {
    date: '2024-12-08',
    materialCategory: 'hardware',
    inboundQuantity: 102,
    outboundQuantity: 95,
    totalQuantity: 197,
    turnoverRate: 48.2,
    efficiency: 27.6,
    exceptionCount: 2,
    remark: '标签问题'
  },
  {
    date: '2024-12-09',
    materialCategory: 'electronics',
    inboundQuantity: 145,
    outboundQuantity: 138,
    totalQuantity: 283,
    turnoverRate: 48.8,
    efficiency: 32.1,
    exceptionCount: 1,
    remark: '正常'
  },
  {
    date: '2024-12-10',
    materialCategory: 'other',
    inboundQuantity: 56,
    outboundQuantity: 62,
    totalQuantity: 118,
    turnoverRate: 52.5,
    efficiency: 24.3,
    exceptionCount: 0,
    remark: '正常'
  }
])

// 导出报表
const exportReport = () => {
  elMessage.success('报表导出成功')
}

// 刷新数据
const refreshData = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    elMessage.success('数据刷新成功')
    initCharts()
  }, 1000)
}

// 查询报表
const searchReport = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    elMessage.success('报表查询成功')
    initCharts()
  }, 1000)
}

// 重置过滤条件
const resetFilter = () => {
  Object.assign(filterForm, {
    reportType: 'summary',
    dateRange: null,
    materialCategory: '',
    operationType: ''
  })
  searchReport()
}

// 展开全部行
const expandAllRows = () => {
  elMessage.info('已展开全部行')
}

// 获取报表标题
const getReportTitle = (reportType: string) => {
  const titleMap: Record<string, string> = {
    'summary': '出入库汇总报表',
    'turnover': '周转率分析报表',
    'efficiency': '效率分析报表',
    'exception': '异常统计报表'
  }
  return titleMap[reportType] || '报表'
}

// 获取物资类别名称
const getMaterialCategoryName = (category: string) => {
  const categoryMap: Record<string, string> = {
    'steel': '钢材',
    'aluminum': '铝材',
    'hardware': '五金配件',
    'electronics': '电子元件',
    'other': '其他'
  }
  return categoryMap[category] || category
}

// 获取物资类别类型
const getMaterialCategoryType = (category: string) => {
  const typeMap: Record<string, string> = {
    'steel': 'success',
    'aluminum': 'info',
    'hardware': 'warning',
    'electronics': 'primary',
    'other': 'danger'
  }
  return typeMap[category] || 'info'
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
}

const handleCurrentChange = (current: number) => {
  pagination.currentPage = current
}

// 初始化图表
const initCharts = () => {
  // 销毁原有图表
  if (trendChart) {
    trendChart.dispose()
  }
  if (distributionChart) {
    distributionChart.dispose()
  }
  if (turnoverChart) {
    turnoverChart.dispose()
  }
  
  // 初始化趋势图
  if (trendChartRef.value) {
    trendChart = echarts.init(trendChartRef.value)
    const trendOption = {
      title: {
        text: '出入库趋势分析',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        },
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['入库量', '出库量'],
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: reportData.value.map(item => item.date)
      },
      yAxis: {
        type: 'value'
      },
      series: [
        {
          name: '入库量',
          type: trendChartType.value,
          data: reportData.value.map(item => item.inboundQuantity),
          itemStyle: {
            color: '#67C23A'
          }
        },
        {
          name: '出库量',
          type: trendChartType.value,
          data: reportData.value.map(item => item.outboundQuantity),
          itemStyle: {
            color: '#F56C6C'
          }
        }
      ]
    }
    trendChart.setOption(trendOption)
  }
  
  // 初始化分布饼图
  if (distributionChartRef.value) {
    distributionChart = echarts.init(distributionChartRef.value)
    
    // 统计物资类别分布
    const categoryStats = {
      steel: 0,
      aluminum: 0,
      hardware: 0,
      electronics: 0,
      other: 0
    }
    
    reportData.value.forEach(item => {
      categoryStats[item.materialCategory as keyof typeof categoryStats] += item.totalQuantity
    })
    
    const distributionOption = {
      title: {
        text: '物资类别分布',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        },
        left: 'center'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left'
      },
      series: [
        {
          name: '物资类别',
          type: 'pie',
          radius: '50%',
          data: [
            { value: categoryStats.steel, name: '钢材' },
            { value: categoryStats.aluminum, name: '铝材' },
            { value: categoryStats.hardware, name: '五金配件' },
            { value: categoryStats.electronics, name: '电子元件' },
            { value: categoryStats.other, name: '其他' }
          ],
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          },
          itemStyle: {
            borderRadius: 5,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            formatter: '{b}: {c} ({d}%)'
          }
        }
      ]
    }
    distributionChart.setOption(distributionOption)
  }
  
  // 初始化周转率分析图
  if (turnoverChartRef.value) {
    turnoverChart = echarts.init(turnoverChartRef.value)
    
    const turnoverOption = {
      title: {
        text: '周转率与效率分析',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        },
        left: 'center'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['周转率', '作业效率', '异常率'],
        top: 30
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      toolbox: {
        feature: {
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        data: reportData.value.map(item => item.date)
      },
      yAxis: [
        {
          type: 'value',
          name: '周转率(%)',
          position: 'left',
          axisLabel: {
            formatter: '{value}%'
          }
        },
        {
          type: 'value',
          name: '作业效率(件/小时)',
          position: 'right'
        }
      ],
      series: [
        {
          name: '周转率',
          type: 'line',
          data: reportData.value.map(item => item.turnoverRate),
          itemStyle: {
            color: '#E6A23C'
          },
          yAxisIndex: 0
        },
        {
          name: '作业效率',
          type: 'line',
          data: reportData.value.map(item => item.efficiency),
          itemStyle: {
            color: '#67C23A'
          },
          yAxisIndex: 1
        },
        {
          name: '异常率',
          type: 'line',
          data: reportData.value.map(item => item.exceptionCount),
          itemStyle: {
            color: '#F56C6C'
          },
          yAxisIndex: 0
        }
      ]
    }
    turnoverChart.setOption(turnoverOption)
  }
}

// 监听图表类型变化
watch(trendChartType, () => {
  if (trendChart) {
    initCharts()
  }
})

// 窗口大小变化时重新调整图表大小
window.addEventListener('resize', () => {
  if (trendChart) {
    trendChart.resize()
  }
  if (distributionChart) {
    distributionChart.resize()
  }
  if (turnoverChart) {
    turnoverChart.resize()
  }
})

// 组件挂载时初始化图表
onMounted(() => {
  setTimeout(() => {
    initCharts()
  }, 100)
})
</script>

<style scoped>
  .reports-view{
    padding: 20px;
  }
.view-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.view-header h3 {
  margin: 0;
  font-size: 18px;
  color: var(--text-color);
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-card {
  margin-bottom: 20px;
}

.date-picker {
  width: 300px;
}

.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 200px;
}

.charts-section {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.chart-card {
  flex: 1;
  min-width: 400px;
}

.chart-card.full-width {
  flex: 0 0 100%;
  min-width: 100%;
}

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

.chart-type-select {
  width: 120px;
}

.chart-container {
  height: 350px;
}

.data-card {
  margin-bottom: 20px;
}

.table-pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
</style>