<template>
  <div class="inventory-alert">

    <div class="content-wrapper">
      <!-- 预警概览 -->
      <div class="alert-overview">
        <el-card shadow="hover" class="alert-card">
          <div class="alert-content">
            <div class="alert-info">
              <div class="alert-count">{{ lowStockAlertCount }}</div>
              <div class="alert-label">低库存预警</div>
            </div>
            <div class="alert-icon low-stock">
              <el-icon-warning />
            </div>
          </div>
        </el-card>
        <el-card shadow="hover" class="alert-card">
          <div class="alert-content">
            <div class="alert-info">
              <div class="alert-count">{{ highStockAlertCount }}</div>
              <div class="alert-label">高库存预警</div>
            </div>
            <div class="alert-icon high-stock">
              <el-icon-warning />
            </div>
          </div>
        </el-card>
        <el-card shadow="hover" class="alert-card">
          <div class="alert-content">
            <div class="alert-info">
              <div class="alert-count">{{ nearExpiryAlertCount }}</div>
              <div class="alert-label">即将过期预警</div>
            </div>
            <div class="alert-icon near-expiry">
              <el-icon-clock />
            </div>
          </div>
        </el-card>
        <el-card shadow="hover" class="alert-card">
          <div class="alert-content">
            <div class="alert-info">
              <div class="alert-count">{{ lowTurnoverAlertCount }}</div>
              <div class="alert-label">低周转率预警</div>
            </div>
            <div class="alert-icon low-turnover">
              <el-icon-data-analysis />
            </div>
          </div>
        </el-card>
        <el-card shadow="hover" class="alert-card">
          <div class="alert-content">
            <div class="alert-info">
              <div class="alert-count">{{ totalAlertCount }}</div>
              <div class="alert-label">总预警数</div>
            </div>
            <div class="alert-icon total">
              <el-icon-bell />
            </div>
          </div>
        </el-card>
      </div>

      <!-- 预警图表 -->
      <div class="alert-charts">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>预警类型分布</span>
            </div>
          </template>
          <div ref="alertTypeChartRef" class="chart-box"></div>
        </el-card>
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>预警处理进度</span>
            </div>
          </template>
          <div ref="alertProgressChartRef" class="chart-box"></div>
        </el-card>
      </div>

      <!-- 库存分析报表 -->
      <div class="analysis-reports">
        <el-tabs v-model="activeReportTab" class="report-tabs" @tab-click="handleTabClick">
          <el-tab-pane label="库存结构分析" name="structure">
            <div class="report-content">
              <div ref="inventoryStructureChartRef" class="chart-box large"></div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="周转率分析" name="turnover">
            <div class="report-content">
              <div ref="turnoverAnalysisChartRef" class="chart-box large"></div>
            </div>
          </el-tab-pane>
          <el-tab-pane label="库存占用资金分析" name="capital">
            <div class="report-content">
              <div ref="capitalOccupancyChartRef" class="chart-box large"></div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 库存优化建议 -->
      <div class="optimization-suggestions">
        <el-card shadow="hover" class="suggestion-card">
          <template #header>
            <div class="card-header">
              <span>库存优化建议</span>
            </div>
          </template>
          <div class="suggestion-content">
            <div v-for="(suggestion, index) in optimizationSuggestions" :key="index" class="suggestion-item">
              <div class="suggestion-text">
                <strong>{{ suggestion.title }}</strong>
                <p>{{ suggestion.content }}</p>
              </div>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 异常库存监控 -->
      <div class="abnormal-inventory">
        <el-card shadow="hover" class="abnormal-card">
          <template #header>
            <div class="card-header">
              <span>异常库存监控</span>
            </div>
          </template>
          <el-table :data="abnormalInventoryList" style="width: 100%" stripe border>
            <el-table-column prop="materialCode" label="物资编码" width="120"></el-table-column>
            <el-table-column prop="materialName" label="物资名称" min-width="150"></el-table-column>
            <el-table-column prop="spec" label="规格型号" min-width="120"></el-table-column>
            <el-table-column prop="abnormalType" label="异常类型" width="120">
              <template #default="scope">
                <el-tag :type="scope.row.abnormalType === 'long_term_overstock' ? 'danger' : 'warning'">
                  {{ getAbnormalTypeLabel(scope.row.abnormalType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="currentQuantity" label="当前库存" width="100"></el-table-column>
            <el-table-column prop="abnormalDays" label="异常天数" width="100"></el-table-column>
            <el-table-column prop="description" label="异常描述" min-width="200"></el-table-column>
          </el-table>
        </el-card>
      </div>

      <!-- 预警列表筛选 -->
      <div class="alert-filter">
        <el-input v-model="searchKeyword" placeholder="搜索物资编码或名称" style="width: 300px; margin-right: 10px;">
          <template #prefix>
            <el-icon-search />
          </template>
        </el-input>
        <el-select v-model="filterAlertType" placeholder="选择预警类型" style="width: 150px; margin-right: 10px;">
          <el-option label="全部" value="" />
          <el-option label="低库存" value="low_stock" />
          <el-option label="高库存" value="high_stock" />
          <el-option label="即将过期" value="near_expiry" />
          <el-option label="低周转率" value="low_turnover" />
        </el-select>
        <el-select v-model="filterAlertStatus" placeholder="选择预警状态" style="width: 150px; margin-right: 10px;">
          <el-option label="全部" value="" />
          <el-option label="未处理" value="pending" />
          <el-option label="已处理" value="processed" />
        </el-select>
        <el-button type="primary" @click="handleSearch">
          <el-icon-search /> 搜索
        </el-button>
        <el-button @click="resetSearch">
          重置
        </el-button>
      </div>

      <!-- 预警列表 -->
      <div class="alert-list">
        <div class="page-header">
          <div class="header-actions">
            <el-button type="primary" @click="openAlertRuleDialog">
              <el-icon-setting /> 预警规则配置
            </el-button>
            <el-button type="success" @click="markAllAsProcessed" :disabled="filteredAlertList.length === 0">
              <el-icon-check /> 批量标记已处理
            </el-button>
          </div>
        </div>
        <el-table :data="paginatedAlertList" style="width: 100%" stripe border
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="alertId" label="预警ID" width="120"></el-table-column>
          <el-table-column prop="materialCode" label="物资编码" width="120"></el-table-column>
          <el-table-column prop="materialName" label="物资名称" min-width="150"></el-table-column>
          <el-table-column prop="spec" label="规格型号" min-width="120"></el-table-column>
          <el-table-column prop="alertType" label="预警类型" width="120">
            <template #default="scope">
              <el-tag
                :type="scope.row.alertType === 'low_stock' ? 'danger' : scope.row.alertType === 'high_stock' ? 'warning' : 'info'">
                {{ getAlertTypeLabel(scope.row.alertType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="currentQuantity" label="当前数量" width="100"></el-table-column>
          <el-table-column prop="threshold" label="预警阈值" width="100"></el-table-column>
          <el-table-column prop="alertTime" label="预警时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.alertTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="scope.row.status === 'pending' ? 'warning' : 'success'">
                {{ scope.row.status === 'pending' ? '未处理' : '已处理' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="warehouseName" label="仓库" width="100"></el-table-column>
          <el-table-column prop="location" label="货架" width="100"></el-table-column>
          <el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleAlertProcess(scope.row)">
                <el-icon-edit /> 处理
              </el-button>
              <el-button v-if="scope.row.status === 'pending'" type="success" size="small"
                @click="markAsProcessed(scope.row)">
                <el-icon-check /> 已处理
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[10, 20, 50, 100]"
            :total="filteredAlertList.length" layout="total, sizes, prev, pager, next, jumper"></el-pagination>
        </div>
      </div>
    </div>

    <!-- 预警规则配置对话框 -->
    <el-dialog title="预警规则配置" v-model="alertRuleDialogVisible" width="600px">
      <el-form :model="alertRuleForm" label-width="120px">
        <el-form-item label="低库存阈值">
          <el-input-number v-model="alertRuleForm.lowStockThreshold" :min="0" :max="1000" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="高库存阈值">
          <el-input-number v-model="alertRuleForm.highStockThreshold" :min="0" :max="10000" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="过期预警天数">
          <el-input-number v-model="alertRuleForm.expiryWarningDays" :min="1" :max="365" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="预警通知方式">
          <el-checkbox-group v-model="alertRuleForm.notificationMethods">
            <el-checkbox label="系统消息">系统消息</el-checkbox>
            <el-checkbox label="邮件">邮件</el-checkbox>
            <el-checkbox label="短信">短信</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="alertRuleDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAlertRule">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预警处理对话框 -->
    <el-dialog title="预警处理" v-model="alertProcessDialogVisible" width="500px">
      <div v-if="selectedAlert" class="alert-process-form">
        <div class="process-info">
          <div class="info-item">
            <label>预警ID：</label>
            <span>{{ selectedAlert.alertId }}</span>
          </div>
          <div class="info-item">
            <label>物资编码：</label>
            <span>{{ selectedAlert.materialCode }}</span>
          </div>
          <div class="info-item">
            <label>物资名称：</label>
            <span>{{ selectedAlert.materialName }}</span>
          </div>
          <div class="info-item">
            <label>预警类型：</label>
            <el-tag
              :type="selectedAlert.alertType === 'low_stock' ? 'danger' : selectedAlert.alertType === 'high_stock' ? 'warning' : 'info'">
              {{ getAlertTypeLabel(selectedAlert.alertType) }}
            </el-tag>
          </div>
          <div class="info-item">
            <label>当前数量：</label>
            <span>{{ selectedAlert.currentQuantity }}</span>
          </div>
          <div class="info-item">
            <label>预警阈值：</label>
            <span>{{ selectedAlert.threshold }}</span>
          </div>
        </div>
        <el-form-item label="处理方式">
          <el-radio-group v-model="alertProcessForm.processType">
            <el-radio label="采购补货">采购补货</el-radio>
            <el-radio label="促销处理">促销处理</el-radio>
            <el-radio label="调整库存">调整库存</el-radio>
            <el-radio label="忽略">忽略</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="处理备注">
          <el-input v-model="alertProcessForm.remark" type="textarea" :rows="4" placeholder="请输入处理备注" />
        </el-form-item>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="alertProcessDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAlertProcess">保存处理</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  Setting as ElIconSetting,
  Check as ElIconCheck,
  Warning as ElIconWarning,
  Clock as ElIconClock,
  Bell as ElIconBell,
  Search as ElIconSearch,
  Edit as ElIconEdit,
  DataAnalysis as ElIconDataAnalysis,
  InfoFilled as ElIconInfo
} from '@element-plus/icons-vue'

// 预警类型
interface Alert {
  alertId: string
  materialCode: string
  materialName: string
  spec: string
  alertType: 'low_stock' | 'high_stock' | 'near_expiry' | 'low_turnover'
  currentQuantity: number
  threshold: number
  alertTime: string
  status: 'pending' | 'processed'
  warehouseName: string
  location: string
  remark: string
}

// 库存优化建议
interface OptimizationSuggestion {
  title: string
  content: string
}

// 异常库存
interface AbnormalInventory {
  materialCode: string
  materialName: string
  spec: string
  abnormalType: 'long_term_overstock' | 'frequent_alert'
  currentQuantity: number
  abnormalDays: number
  description: string
}

// 预警列表数据
const alertList = ref<Alert[]>([
  { alertId: 'A001', materialCode: 'M001', materialName: '智能手机', spec: '128GB', alertType: 'low_stock', currentQuantity: 10, threshold: 20, alertTime: '2025-12-10 09:30:00', status: 'pending', warehouseName: '主仓库', location: 'A1-01', remark: '库存低于安全库存' },
  { alertId: 'A002', materialCode: 'M002', materialName: '笔记本电脑', spec: 'i7/16GB/512GB', alertType: 'low_stock', currentQuantity: 5, threshold: 15, alertTime: '2025-12-09 14:20:00', status: 'pending', warehouseName: '主仓库', location: 'A2-01', remark: '库存低于安全库存' },
  { alertId: 'A003', materialCode: 'M004', materialName: '办公桌椅', spec: '木质', alertType: 'high_stock', currentQuantity: 50, threshold: 30, alertTime: '2025-12-08 11:00:00', status: 'processed', warehouseName: '家具库', location: 'C1-01', remark: '库存过高' },
  { alertId: 'A004', materialCode: 'M005', materialName: '打印纸', spec: 'A4', alertType: 'high_stock', currentQuantity: 1000, threshold: 800, alertTime: '2025-12-07 10:00:00', status: 'pending', warehouseName: '耗材库', location: 'D1-01', remark: '库存过高' },
  { alertId: 'A005', materialCode: 'M006', materialName: '电池', spec: 'AA', alertType: 'near_expiry', currentQuantity: 50, threshold: 30, alertTime: '2025-12-06 16:30:00', status: 'pending', warehouseName: '配件库', location: 'B2-01', remark: '即将过期' },
  { alertId: 'A006', materialCode: 'M007', materialName: '鼠标', spec: '无线', alertType: 'low_stock', currentQuantity: 8, threshold: 25, alertTime: '2025-12-05 09:15:00', status: 'processed', warehouseName: '配件库', location: 'B3-01', remark: '库存低于安全库存' },
  { alertId: 'A007', materialCode: 'M008', materialName: '键盘', spec: '机械', alertType: 'low_turnover', currentQuantity: 100, threshold: 0.5, alertTime: '2025-12-10 10:00:00', status: 'pending', warehouseName: '配件库', location: 'B4-01', remark: '周转率低于0.5' },
  { alertId: 'A008', materialCode: 'M009', materialName: '显示器', spec: '27寸', alertType: 'low_turnover', currentQuantity: 30, threshold: 0.5, alertTime: '2025-12-09 15:00:00', status: 'pending', warehouseName: '主仓库', location: 'A3-01', remark: '周转率低于0.5' }
])

// 库存优化建议数据
const optimizationSuggestions = ref<OptimizationSuggestion[]>([
  {
    title: '采购优化建议',
    content: '对于低库存预警的物资（如智能手机、笔记本电脑），建议根据历史销售数据和当前需求，立即采购20-30件，以满足未来1个月的需求。'
  },
  {
    title: '库存清理建议',
    content: '对于高库存预警的物资（如办公桌椅、打印纸），建议调整采购计划，减少未来3个月的采购量，并考虑促销活动清理库存。'
  },
  {
    title: '周转率提升建议',
    content: '对于低周转率的物资（如键盘、显示器），建议分析销售不畅的原因，考虑调整定价策略或优化产品展示，以提升周转率。'
  },
  {
    title: '近效期处理建议',
    content: '对于即将过期的物资（如电池），建议优先使用或考虑退货，避免过期损失。'
  }
])

// 异常库存数据
const abnormalInventoryList = ref<AbnormalInventory[]>([
  {
    materialCode: 'M008',
    materialName: '键盘',
    spec: '机械',
    abnormalType: 'long_term_overstock',
    currentQuantity: 100,
    abnormalDays: 120,
    description: '连续4个月库存周转低于0.5，建议优化采购或促销处理'
  },
  {
    materialCode: 'M009',
    materialName: '显示器',
    spec: '27寸',
    abnormalType: 'long_term_overstock',
    currentQuantity: 30,
    abnormalDays: 90,
    description: '连续3个月库存周转低于0.5，建议优化采购或促销处理'
  },
  {
    materialCode: 'M001',
    materialName: '智能手机',
    spec: '128GB',
    abnormalType: 'frequent_alert',
    currentQuantity: 10,
    abnormalDays: 15,
    description: '连续2周触发低库存预警，建议调整安全库存阈值'
  }
])

// 搜索和筛选条件
const searchKeyword = ref('')
const filterAlertType = ref('')
const filterAlertStatus = ref('')
const selectedAlerts = ref<string[]>([])

// 分页
const currentPage = ref(1)
const pageSize = ref(20)

// 预警统计
const lowStockAlertCount = computed(() => {
  return alertList.value.filter(alert => alert.alertType === 'low_stock' && alert.status === 'pending').length
})

const highStockAlertCount = computed(() => {
  return alertList.value.filter(alert => alert.alertType === 'high_stock' && alert.status === 'pending').length
})

const nearExpiryAlertCount = computed(() => {
  return alertList.value.filter(alert => alert.alertType === 'near_expiry' && alert.status === 'pending').length
})

const lowTurnoverAlertCount = computed(() => {
  return alertList.value.filter(alert => alert.alertType === 'low_turnover' && alert.status === 'pending').length
})

const totalAlertCount = computed(() => {
  return alertList.value.filter(alert => alert.status === 'pending').length
})

// 筛选后的预警列表
const filteredAlertList = computed(() => {
  return alertList.value.filter(alert => {
    // 搜索关键字筛选
    const keywordMatch = !searchKeyword.value ||
      alert.materialCode.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      alert.materialName.toLowerCase().includes(searchKeyword.value.toLowerCase())

    // 预警类型筛选
    const typeMatch = !filterAlertType.value || alert.alertType === filterAlertType.value

    // 预警状态筛选
    const statusMatch = !filterAlertStatus.value || alert.status === filterAlertStatus.value

    return keywordMatch && typeMatch && statusMatch
  })
})

// 分页处理
const paginatedAlertList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredAlertList.value.slice(start, end)
})

// 预警规则配置
const alertRuleDialogVisible = ref(false)
const alertRuleForm = ref({
  lowStockThreshold: 20,
  highStockThreshold: 100,
  expiryWarningDays: 30,
  notificationMethods: ['系统消息', '邮件']
})

// 预警处理
const alertProcessDialogVisible = ref(false)
const selectedAlert = ref<Alert | null>(null)
const alertProcessForm = ref({
  processType: '采购补货',
  remark: ''
})

// 标签页状态
const activeReportTab = ref('structure')

// 图表引用
const alertTypeChartRef = ref<HTMLElement | null>(null)
const alertProgressChartRef = ref<HTMLElement | null>(null)
const inventoryStructureChartRef = ref<HTMLElement | null>(null)
const turnoverAnalysisChartRef = ref<HTMLElement | null>(null)
const capitalOccupancyChartRef = ref<HTMLElement | null>(null)

let alertTypeChart: echarts.ECharts | null = null
let alertProgressChart: echarts.ECharts | null = null
let inventoryStructureChart: echarts.ECharts | null = null
let turnoverAnalysisChart: echarts.ECharts | null = null
let capitalOccupancyChart: echarts.ECharts | null = null

// 初始化图表
onMounted(() => {
  initCharts()

  // 窗口大小变化时重新调整图表大小
  window.addEventListener('resize', handleResize)
})

// 初始化图表
const initCharts = () => {
  // 预警类型分布图表
  if (alertTypeChartRef.value) {
    alertTypeChart = echarts.init(alertTypeChartRef.value)
    const alertTypeOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: ['低库存', '高库存', '即将过期', '低周转率']
      },
      series: [
        {
          name: '预警类型',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: lowStockAlertCount.value, name: '低库存', itemStyle: { color: '#F56C6C' } },
            { value: highStockAlertCount.value, name: '高库存', itemStyle: { color: '#E6A23C' } },
            { value: nearExpiryAlertCount.value, name: '即将过期', itemStyle: { color: '#409EFF' } },
            { value: lowTurnoverAlertCount.value, name: '低周转率', itemStyle: { color: '#909399' } }
          ]
        }
      ]
    }
    alertTypeChart.setOption(alertTypeOption)
  }

  // 预警处理进度图表
  if (alertProgressChartRef.value) {
    alertProgressChart = echarts.init(alertProgressChartRef.value)
    const processedCount = alertList.value.filter(alert => alert.status === 'processed').length
    const pendingCount = alertList.value.filter(alert => alert.status === 'pending').length

    const alertProgressOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: ['已处理', '未处理']
      },
      series: [
        {
          name: '处理进度',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: processedCount, name: '已处理', itemStyle: { color: '#67C23A' } },
            { value: pendingCount, name: '未处理', itemStyle: { color: '#E6A23C' } }
          ]
        }
      ]
    }
    alertProgressChart.setOption(alertProgressOption)
  }

  // 库存结构分析图表
  if (inventoryStructureChartRef.value) {
    inventoryStructureChart = echarts.init(inventoryStructureChartRef.value)
    const inventoryStructureOption = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      legend: {
        data: ['库存数量', '库存金额']
      },
      xAxis: {
        type: 'category',
        data: ['电子设备', '办公用品', '家具', '耗材', '配件']
      },
      yAxis: [
        {
          type: 'value',
          name: '库存数量',
          axisLabel: {
            formatter: '{value} 件'
          }
        },
        {
          type: 'value',
          name: '库存金额',
          axisLabel: {
            formatter: '{value} 元'
          }
        }
      ],
      series: [
        {
          name: '库存数量',
          type: 'bar',
          data: [150, 800, 50, 1200, 200],
          barMaxWidth: 20
        },
        {
          name: '库存金额',
          type: 'line',
          yAxisIndex: 1,
          data: [150000, 40000, 25000, 60000, 30000],
          barMaxWidth: 20
        }
      ]
    }
    inventoryStructureChart.setOption(inventoryStructureOption)
  }

  // 周转率分析图表
  if (turnoverAnalysisChartRef.value) {
    turnoverAnalysisChart = echarts.init(turnoverAnalysisChartRef.value)
    const turnoverAnalysisOption = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['周转率']
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
      },
      yAxis: {
        type: 'value',
        name: '周转率',
        axisLabel: {
          formatter: '{value}'
        }
      },
      series: [
        {
          name: '周转率',
          type: 'line',
          data: [0.8, 0.9, 1.2, 1.0, 0.7, 0.6, 0.8, 1.1, 1.3, 1.0, 0.7, 0.5]
        }
      ]
    }
    turnoverAnalysisChart.setOption(turnoverAnalysisOption)
  }

  // 库存占用资金分析图表
  if (capitalOccupancyChartRef.value) {
    capitalOccupancyChart = echarts.init(capitalOccupancyChartRef.value)
    const capitalOccupancyOption = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 10,
        data: ['电子设备', '办公用品', '家具', '耗材', '配件']
      },
      series: [
        {
          name: '库存占用资金',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '18',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: [
            { value: 150000, name: '电子设备', itemStyle: { color: '#F56C6C' } },
            { value: 40000, name: '办公用品', itemStyle: { color: '#E6A23C' } },
            { value: 25000, name: '家具', itemStyle: { color: '#409EFF' } },
            { value: 60000, name: '耗材', itemStyle: { color: '#67C23A' } },
            { value: 30000, name: '配件', itemStyle: { color: '#909399' } }
          ]
        }
      ]
    }
    capitalOccupancyChart.setOption(capitalOccupancyOption)
  }
}

// 窗口大小变化时重新调整图表大小
const handleResize = () => {
  alertTypeChart?.resize()
  alertProgressChart?.resize()
  inventoryStructureChart?.resize()
  turnoverAnalysisChart?.resize()
  capitalOccupancyChart?.resize()
}

// 处理选择
const handleSelectionChange = (selection: any[]) => {
  selectedAlerts.value = selection.map(item => item.alertId)
}

// 打开预警规则配置对话框
const openAlertRuleDialog = () => {
  alertRuleDialogVisible.value = true
}

// 保存预警规则
const saveAlertRule = () => {
  // 实际项目中这里会调用API保存预警规则
  ElMessage.success('预警规则保存成功')
  alertRuleDialogVisible.value = false
}

// 打开预警处理对话框
const handleAlertProcess = (alert: Alert) => {
  selectedAlert.value = alert
  alertProcessForm.value = {
    processType: '采购补货',
    remark: ''
  }
  alertProcessDialogVisible.value = true
}

// 保存预警处理
const saveAlertProcess = () => {
  if (!selectedAlert.value) return

  // 实际项目中这里会调用API保存预警处理
  const alertIndex = alertList.value.findIndex(alert => alert.alertId === selectedAlert.value?.alertId)
  if (alertIndex !== -1) {
    alertList.value[alertIndex].status = 'processed'
    alertList.value[alertIndex].remark = alertProcessForm.value.remark
  }

  ElMessage.success('预警处理成功')
  alertProcessDialogVisible.value = false
  selectedAlert.value = null

  // 更新图表
  initCharts()
}

// 标记为已处理
const markAsProcessed = (alert: Alert) => {
  // 实际项目中这里会调用API更新预警状态
  const alertIndex = alertList.value.findIndex(item => item.alertId === alert.alertId)
  if (alertIndex !== -1) {
    alertList.value[alertIndex].status = 'processed'
  }

  ElMessage.success('已标记为已处理')

  // 更新图表
  initCharts()
}

// 批量标记为已处理
const markAllAsProcessed = () => {
  // 实际项目中这里会调用API批量更新预警状态
  alertList.value.forEach(alert => {
    if (selectedAlerts.value.includes(alert.alertId)) {
      alert.status = 'processed'
    }
  })

  ElMessage.success('批量标记已处理成功')
  selectedAlerts.value = []

  // 更新图表
  initCharts()
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
}

// 重置搜索
const resetSearch = () => {
  searchKeyword.value = ''
  filterAlertType.value = ''
  filterAlertStatus.value = ''
  currentPage.value = 1
}

// 获取预警类型标签
const getAlertTypeLabel = (alertType: string) => {
  switch (alertType) {
    case 'low_stock':
      return '低库存'
    case 'high_stock':
      return '高库存'
    case 'near_expiry':
      return '即将过期'
    case 'low_turnover':
      return '低周转率'
    default:
      return alertType
  }
}

// 获取异常类型标签
const getAbnormalTypeLabel = (abnormalType: string) => {
  switch (abnormalType) {
    case 'long_term_overstock':
      return '长期积压'
    case 'frequent_alert':
      return '频繁预警'
    default:
      return abnormalType
  }
}

// 处理标签页切换
const handleTabClick = () => {
  // 延迟执行，确保DOM已更新
  setTimeout(() => {
    // 根据当前激活的标签页，重新渲染对应图表
    switch (activeReportTab.value) {
      case 'structure':
        if (inventoryStructureChart) {
          inventoryStructureChart.resize()
        }
        break
      case 'turnover':
        if (turnoverAnalysisChart) {
          turnoverAnalysisChart.resize()
        }
        break
      case 'capital':
        if (capitalOccupancyChart) {
          capitalOccupancyChart.resize()
        }
        break
      default:
        break
    }
  }, 100)
}

// 格式化日期
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}
</script>

<style scoped>
.inventory-alert {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
}

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

.content-wrapper {
  background-color: #fff;
  border-radius: 4px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.alert-overview {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

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

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

.alert-info {
  flex: 1;
}

.alert-count {
  font-size: 32px;
  font-weight: 600;
  color: #303133;
}

.alert-label {
  font-size: 14px;
  color: #606266;
  margin-top: 4px;
}

.alert-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  color: #fff;
}

.alert-icon.low-stock {
  background-color: #F56C6C;
}

.alert-icon.high-stock {
  background-color: #E6A23C;
}

.alert-icon.near-expiry {
  background-color: #409EFF;
}

.alert-icon.low-turnover {
  background-color: #909399;
}

.alert-icon.total {
  background-color: #67C23A;
}

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

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

.chart-box {
  width: 100%;
  height: 300px;
}

.chart-box.large {
  height: 400px;
}

.alert-filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 10px;
  flex-wrap: wrap;
}

.alert-list {
  margin-bottom: 20px;
}

.pagination {
  text-align: right;
  margin-top: 20px;
}

.alert-process-form {
  padding: 10px 0;
}

.process-info {
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  margin-bottom: 10px;
  align-items: center;
}

.info-item label {
  width: 80px;
  font-weight: 500;
  margin-right: 10px;
}

.info-item span {
  flex: 1;
}

/* 库存分析报表样式 */
.analysis-reports {
  margin-bottom: 20px;
}

.report-tabs {
  margin-bottom: 20px;
}

.report-content {
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

/* 库存优化建议样式 */
.optimization-suggestions {
  margin-bottom: 20px;
}

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

.suggestion-content {
  padding: 10px 0;
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.suggestion-icon {
  color: #409EFF;
  font-size: 20px;
  margin-right: 15px;
  margin-top: 2px;
}

.suggestion-text {
  flex: 1;
}

.suggestion-text strong {
  display: block;
  margin-bottom: 5px;
  color: #303133;
}

.suggestion-text p {
  margin: 0;
  color: #606266;
  line-height: 1.5;
}

/* 异常库存监控样式 */
.abnormal-inventory {
  margin-bottom: 20px;
}

.abnormal-card {
  margin-bottom: 20px;
}
</style>