<template>
  <div>
    <!-- 如果是子路由，显示子路由内容 -->
    <router-view v-slot="{ Component }">
      <div v-if="Component">
        <component :is="Component" />
      </div>
      <div v-else>
        <!-- 搜索和操作栏 -->
        <a-card style="margin-bottom: 16px;">
          <div style="display: flex; flex-wrap: wrap; gap: 16px; align-items: center;">
            <a-input v-model:value="searchKeyword" placeholder="输入物资名称或编号" style="width: 250px;">
              <template #prefix>
                <span class="iconfont icon-sousuo"></span>
              </template>
            </a-input>
            
            <a-select v-model:value="categoryFilter" placeholder="物资类别" style="width: 120px;">
              <a-select-option value="">全部</a-select-option>
              <a-select-option value="feed">饲料</a-select-option>
              <a-select-option value="medicine">药品</a-select-option>
              <a-select-option value="equipment">设备</a-select-option>
              <a-select-option value="other">其他</a-select-option>
            </a-select>
            
            <a-select v-model:value="statusFilter" placeholder="库存状态" style="width: 120px;">
              <a-select-option value="">全部</a-select-option>
              <a-select-option value="normal">正常</a-select-option>
              <a-select-option value="low">低库存</a-select-option>
              <a-select-option value="out">缺货</a-select-option>
            </a-select>
            
            <a-button type="primary" @click="handleSearch" style="margin-left: auto;">
              <span class="iconfont icon-sousuo"></span> 搜索
            </a-button>
            
            <a-button type="default" @click="handleReset">重置</a-button>
            
            <a-button type="dashed" @click="handleImport">
              <span class="iconfont icon-daoru"></span> 导入
            </a-button>
            
            <a-button type="dashed" @click="handleExport">
              <span class="iconfont icon-daochu"></span> 导出
            </a-button>
            
            <a-button type="primary" danger @click="handleAddMaterial">
              <span class="iconfont icon-tianjia"></span> 新增物资
            </a-button>
          </div>
    </a-card>
    
    <!-- 数据统计卡片 -->
    <a-row gutter={24} style="margin-bottom: 16px;">
      <a-col :span="6">
        <a-statistic title="物资总类" :value="totalCategories" suffix="种" />
      </a-col>
      <a-col :span="6">
        <a-statistic title="库存总量" :value="totalQuantity" suffix="单位" />
      </a-col>
      <a-col :span="6">
        <a-statistic title="低库存物资" :value="lowStockCount" suffix="种" :valueStyle="{ color: '#faad14' }" />
      </a-col>
      <a-col :span="6">
        <a-statistic title="缺货物资" :value="outOfStockCount" suffix="种" :valueStyle="{ color: '#cf1322' }" />
      </a-col>
    </a-row>
    
    <!-- 库存预警图表 -->
    <a-card title="库存预警分析" style="margin-bottom: 16px;">
      <div style="height: 300px;" ref="stockChartRef"></div>
    </a-card>
    
    <!-- 物资列表 -->
    <a-card>
      <a-table
        :columns="columns"
        :data-source="materialsData"
        :pagination="pagination"
        row-key="id"
        :row-selection="{ selectedRowKeys, onChange: onSelectChange }"
       :scroll="{ x: 'max-content' }"
      >
        <!-- 状态列 -->
        <template #bodyCell:status="{ record }">
          <a-tag :color="getStatusColor(record.status)">{{ getStatusText(record.status) }}</a-tag>
        </template>
        
        <!-- 库存数量列 -->
        <template #bodyCell:stockQuantity="{ record }">
          <span :class="record.status !== 'normal' ? 'text-danger font-weight-bold' : ''">
            {{ record.stockQuantity }}{{ record.unit }}
          </span>
        </template>
        
        <!-- 操作列 -->
        <template #bodyCell:action="{ record }">
          <div style="display: flex; gap: 8px;">
            <a-button size="small" @click="handleView(record)">查看</a-button>
            <a-button size="small" type="primary" @click="handleEdit(record)">编辑</a-button>
            <a-button size="small" danger @click="handleDelete(record.id)">删除</a-button>
            <a-popconfirm title="确定要入库吗？" @confirm="() => handleStockIn(record.id)">
              <a-button size="small" type="link">入库</a-button>
            </a-popconfirm>
            <a-popconfirm title="确定要出库吗？" @confirm="() => handleStockOut(record.id)">
              <a-button size="small" type="link">出库</a-button>
            </a-popconfirm>
          </div>
        </template>
      </a-table>
    </a-card>
    
    <!-- 新增/编辑物资模态框 -->
    <a-modal
      v-model:open="isAddEditModalOpen"
      title="新增/编辑物资"
      :footer="null"
      width={700}
    >
      <a-form
        :model="currentMaterial"
        layout="vertical"
        style="max-width: 500px; margin: 0 auto;"
      >
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="物资编号" name="code" :rules="[{ required: true, message: '请输入物资编号' }]">
              <a-input v-model:value="currentMaterial.code" placeholder="请输入物资编号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="物资名称" name="name" :rules="[{ required: true, message: '请输入物资名称' }]">
              <a-input v-model:value="currentMaterial.name" placeholder="请输入物资名称" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="物资类别" name="category" :rules="[{ required: true, message: '请选择物资类别' }]">
              <a-select v-model:value="currentMaterial.category" placeholder="请选择物资类别">
                <a-select-option value="feed">饲料</a-select-option>
                <a-select-option value="medicine">药品</a-select-option>
                <a-select-option value="equipment">设备</a-select-option>
                <a-select-option value="other">其他</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="单位" name="unit" :rules="[{ required: true, message: '请输入单位' }]">
              <a-input v-model:value="currentMaterial.unit" placeholder="请输入单位" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-row gutter={24}>
          <a-col :span="12">
            <a-form-item label="库存数量" name="stockQuantity" :rules="[{ required: true, message: '请输入库存数量' }]">
              <a-input-number v-model:value="currentMaterial.stockQuantity" :min="0" placeholder="请输入库存数量" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="预警数量" name="warningQuantity" :rules="[{ required: true, message: '请输入预警数量' }]">
              <a-input-number v-model:value="currentMaterial.warningQuantity" :min="0" placeholder="请输入预警数量" />
            </a-form-item>
          </a-col>
        </a-row>
        
        <a-form-item label="供应商" name="supplier">
          <a-input v-model:value="currentMaterial.supplier" placeholder="请输入供应商" />
        </a-form-item>
        
        <a-form-item label="备注信息" name="remark">
          <a-input.TextArea v-model:value="currentMaterial.remark" placeholder="请输入备注信息" :rows="3" />
        </a-form-item>
        
        <div style="display: flex; justify-content: flex-end; gap: 16px;">
          <a-button @click="isAddEditModalOpen = false">取消</a-button>
          <a-button type="primary" @click="handleSave">保存</a-button>
        </div>
      </a-form>
    </a-modal>
    
    <!-- 查看物资详情模态框 -->
    <a-modal
      v-model:open="isViewModalOpen"
      title="物资详情"
      :footer="null"
      width={700}
    >
      <div v-if="viewMaterial" class="material-detail">
        <div class="detail-row">
          <div class="detail-label">物资编号：</div>
          <div class="detail-value">{{ viewMaterial.code }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">物资名称：</div>
          <div class="detail-value">{{ viewMaterial.name }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">物资类别：</div>
          <div class="detail-value">{{ getCategoryText(viewMaterial.category) }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">单位：</div>
          <div class="detail-value">{{ viewMaterial.unit }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">库存数量：</div>
          <div class="detail-value" :class="viewMaterial.status !== 'normal' ? 'text-danger font-weight-bold' : ''">
            {{ viewMaterial.stockQuantity }}{{ viewMaterial.unit }}
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-label">预警数量：</div>
          <div class="detail-value">{{ viewMaterial.warningQuantity }}{{ viewMaterial.unit }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">库存状态：</div>
          <div class="detail-value">
            <a-tag :color="getStatusColor(viewMaterial.status)">{{ getStatusText(viewMaterial.status) }}</a-tag>
          </div>
        </div>
        <div class="detail-row">
          <div class="detail-label">供应商：</div>
          <div class="detail-value">{{ viewMaterial.supplier || '无' }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">最后更新时间：</div>
          <div class="detail-value">{{ viewMaterial.updateTime }}</div>
        </div>
        <div class="detail-row">
          <div class="detail-label">备注信息：</div>
          <div class="detail-value">{{ viewMaterial.remark || '无' }}</div>
        </div>
      </div>
      <div style="text-align: center; margin-top: 24px;">
        <a-button @click="isViewModalOpen = false">关闭</a-button>
      </div>
    </a-modal>
    
    <!-- 入库/出库模态框 -->
    <a-modal
      v-model:open="isStockModalOpen"
      :title="stockModalTitle"
      :footer="null"
      width={500}
    >
      <a-form
        :model="stockForm"
        layout="vertical"
        style="max-width: 400px; margin: 0 auto;"
      >
        <a-form-item label="物资名称" name="materialName" :rules="[{ required: true }]">
          <a-input v-model:value="stockForm.materialName" disabled />
        </a-form-item>
        
        <a-form-item label="当前库存" name="currentStock" :rules="[{ required: true }]">
          <a-input v-model:value="stockForm.currentStock" disabled />
        </a-form-item>
        
        <a-form-item label="数量" name="quantity" :rules="[{ required: true, message: '请输入数量' }]">
          <a-input-number v-model:value="stockForm.quantity" :min="1" placeholder="请输入数量" />
        </a-form-item>
        
        <a-form-item label="操作人" name="operator" :rules="[{ required: true, message: '请输入操作人' }]">
          <a-input v-model:value="stockForm.operator" placeholder="请输入操作人" />
        </a-form-item>
        
        <a-form-item label="备注" name="remark">
          <a-input.TextArea v-model:value="stockForm.remark" placeholder="请输入备注" :rows="2" />
        </a-form-item>
        
        <div style="display: flex; justify-content: flex-end; gap: 16px;">
          <a-button @click="isStockModalOpen = false">取消</a-button>
          <a-button type="primary" @click="handleStockSubmit">确定</a-button>
        </div>
      </a-form>
    </a-modal>
  </div>
  </router-view>
</div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import api from '@/utils/api'

// 搜索条件
const searchKeyword = ref('')
const categoryFilter = ref('')
const statusFilter = ref('')

// 统计数据
const totalCategories = ref(86)
const totalQuantity = ref(12560)
const lowStockCount = ref(12)
const outOfStockCount = ref(3)

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`,
  onChange: (page) => {
    pagination.current = page
    fetchMaterials()
  },
  onShowSizeChange: (current, pageSize) => {
    pagination.current = 1
    pagination.pageSize = pageSize
    fetchMaterials()
  }
})

// 选中的行
const selectedRowKeys = ref([])
const onSelectChange = (newSelectedRowKeys) => {
  selectedRowKeys.value = newSelectedRowKeys
}

// 图表引用
const stockChartRef = ref(null)

// 模态框状态
const isAddEditModalOpen = ref(false)
const isViewModalOpen = ref(false)
const isStockModalOpen = ref(false)
const stockModalTitle = ref('入库')
const currentStockOperation = ref('in') // 'in' 或 'out'
const currentStockMaterialId = ref('')

// 当前编辑的物资
const currentMaterial = reactive({
  id: '',
  code: '',
  name: '',
  category: '',
  unit: '',
  stockQuantity: 0,
  warningQuantity: 0,
  status: 'normal',
  supplier: '',
  remark: '',
  updateTime: ''
})

// 查看的物资
const viewMaterial = ref(null)

// 入库/出库表单
const stockForm = reactive({
  materialName: '',
  currentStock: '',
  quantity: 1,
  operator: '',
  remark: ''
})

// 物资列表数据
const materialsData = ref([])

// 获取物资列表
// const fetchMaterials = async () => {
//   try {
//     const params = {
//       keyword: searchKeyword.value,
//       category: categoryFilter.value,
//       status: statusFilter.value,
//       page: pagination.current,
//       pageSize: pagination.pageSize
//     }
//     const response = await api.warehouse.getList(params)
//     // 根据后端实际返回的数据结构进行调整
//     materialsData.value = response.data || []
//     pagination.total = response.total || 0
//   } catch (error) {
//     console.error('获取物资列表失败:', error)
//     // 如果获取失败，提供一些模拟数据以便页面可以正常显示
//     materialsData.value = [
//       {
//         id: '1',
//         code: 'M001',
//         name: '玉米饲料',
//         category: 'feed',
//         unit: '吨',
//         stockQuantity: 150,
//         warningQuantity: 50,
//         status: 'normal',
//         supplier: '希望饲料厂',
//         updateTime: '2024-04-07 10:15:00'
//       },
//       {
//         id: '2',
//         code: 'M002',
//         name: '牛瘟疫苗',
//         category: 'medicine',
//         unit: '盒',
//         stockQuantity: 20,
//         warningQuantity: 10,
//         status: 'low',
//         supplier: '生物制药公司',
//         updateTime: '2024-04-05 14:30:00'
//       },
//       {
//         id: '3',
//         code: 'M003',
//         name: '兽用注射器',
//         category: 'equipment',
//         unit: '个',
//         stockQuantity: 0,
//         warningQuantity: 50,
//         status: 'out',
//         supplier: '医疗器械公司',
//         updateTime: '2024-04-01 09:45:00'
//       }
//     ]
//     pagination.total = materialsData.value.length
//   }
// }

// 表格列定义
const columns = [
  {
    title: '物资编号',
    dataIndex: 'code',
    key: 'code',
    width: 120
  },
  {
    title: '物资名称',
    dataIndex: 'name',
    key: 'name',
    ellipsis: true
  },
  {
    title: '物资类别',
    dataIndex: 'category',
    key: 'category',
    width: 100,
    customRender: ({ text }) => getCategoryText(text)
  },
  {
    title: '单位',
    dataIndex: 'unit',
    key: 'unit',
    width: 80
  },
  {
    title: '库存数量',
    dataIndex: 'stockQuantity',
    key: 'stockQuantity',
    width: 100
  },
  {
    title: '预警数量',
    dataIndex: 'warningQuantity',
    key: 'warningQuantity',
    width: 100,
    customRender: ({ text, record }) => `${text}${record.unit}`
  },
  {
    title: '库存状态',
    dataIndex: 'status',
    key: 'status',
    width: 100
  },
  {
    title: '供应商',
    dataIndex: 'supplier',
    key: 'supplier',
    width: 120
  },
  {
    title: '最后更新',
    dataIndex: 'updateTime',
    key: 'updateTime',
    width: 160
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case 'normal': return 'green'
    case 'low': return 'orange'
    case 'out': return 'red'
    default: return 'default'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'normal': return '正常'
    case 'low': return '低库存'
    case 'out': return '缺货'
    default: return status
  }
}

// 获取类别文本
const getCategoryText = (category) => {
  switch (category) {
    case 'feed': return '饲料'
    case 'medicine': return '药品'
    case 'equipment': return '设备'
    case 'other': return '其他'
    default: return category
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.current = 1
  fetchMaterials()
}

// 重置处理
const handleReset = () => {
  searchKeyword.value = ''
  categoryFilter.value = ''
  statusFilter.value = ''
  selectedRowKeys.value = []
  pagination.current = 1
  fetchMaterials()
}

// 导入处理
const handleImport = () => {
  console.log('导入物资数据')
  // 这里应该有实际的导入逻辑
}

// 导出处理
const handleExport = () => {
  console.log('导出物资数据')
  // 这里应该有实际的导出逻辑
}

// 新增物资
const handleAddMaterial = () => {
  // 重置当前物资数据
  Object.assign(currentMaterial, {
    id: '',
    code: '',
    name: '',
    category: '',
    unit: '',
    stockQuantity: 0,
    warningQuantity: 0,
    status: 'normal',
    supplier: '',
    remark: '',
    updateTime: ''
  })
  isAddEditModalOpen.value = true
}

// 编辑物资
const handleEdit = (record) => {
  // 复制记录数据到当前物资
  Object.assign(currentMaterial, JSON.parse(JSON.stringify(record)))
  isAddEditModalOpen.value = true
}

// 查看物资
const handleView = async (record) => {
  try {
    const response = await api.warehouse.getDetail(record.id)
    viewMaterial.value = response.data
    isViewModalOpen.value = true
  } catch (error) {
    console.error('获取物资详情失败:', error)
    alert('获取物资详情失败，请重试')
  }
}

// 删除物资
const handleDelete = async (id) => {
  try {
    if (confirm('确定要删除这条物资记录吗？')) {
      await api.warehouse.delete(id)
      alert('删除成功')
      fetchMaterials() // 重新获取物资列表
    }
  } catch (error) {
    console.error('删除物资失败:', error)
    alert('删除失败，请重试')
  }
}

// 保存物资
const handleSave = async () => {
  try {
    // 复制物资对象，避免修改原对象
    const materialData = { ...currentMaterial }
    
    if (materialData.id) {
      // 更新现有物资
      await api.warehouse.update(materialData.id, materialData)
    } else {
      // 创建新物资
      await api.warehouse.create(materialData)
    }
    
    isAddEditModalOpen.value = false
    alert('保存成功')
    fetchMaterials() // 重新获取物资列表
  } catch (error) {
    console.error('保存物资失败:', error)
    alert('保存失败，请重试')
  }
}

// 入库
const handleStockIn = async (id) => {
  try {
    const response = await api.warehouse.getDetail(id)
    const material = response.data
    if (material) {
      currentStockOperation.value = 'in'
      currentStockMaterialId.value = id
      stockModalTitle.value = '入库'
      Object.assign(stockForm, {
        materialName: material.name,
        currentStock: `${material.stockQuantity}${material.unit}`,
        quantity: 1,
        operator: '',
        remark: ''
      })
      isStockModalOpen.value = true
    }
  } catch (error) {
    console.error('获取物资信息失败:', error)
    alert('获取物资信息失败，请重试')
  }
}

// 出库
const handleStockOut = async (id) => {
  try {
    const response = await api.warehouse.getDetail(id)
    const material = response.data
    if (material) {
      currentStockOperation.value = 'out'
      currentStockMaterialId.value = id
      stockModalTitle.value = '出库'
      Object.assign(stockForm, {
        materialName: material.name,
        currentStock: `${material.stockQuantity}${material.unit}`,
        quantity: 1,
        operator: '',
        remark: ''
      })
      isStockModalOpen.value = true
    }
  } catch (error) {
    console.error('获取物资信息失败:', error)
    alert('获取物资信息失败，请重试')
  }
}

// 提交入库/出库
const handleStockSubmit = async () => {
  try {
    const stockData = {
      materialId: currentStockMaterialId.value,
      quantity: stockForm.quantity,
      operator: stockForm.operator,
      remark: stockForm.remark
    }
    
    if (currentStockOperation.value === 'in') {
      // 入库操作
      await api.warehouse.stockIn(stockData)
    } else {
      // 出库操作
      await api.warehouse.stockOut(stockData)
    }
    
    isStockModalOpen.value = false
    alert(`${currentStockOperation.value === 'in' ? '入库' : '出库'}操作成功`)
    fetchMaterials() // 重新获取物资列表
    fetchWarehouseStats() // 更新统计数据和图表
  } catch (error) {
    console.error(`${currentStockOperation.value === 'in' ? '入库' : '出库'}操作失败:`, error)
    alert(`${currentStockOperation.value === 'in' ? '入库' : '出库'}操作失败，请重试`)
  }
}

// 获取仓库统计信息
const fetchWarehouseStats = async () => {
  try {
    const response = await api.warehouse.getStats()
    // 确保我们使用正确的响应结构
    totalCategories.value = response.data?.totalCategories || response.totalCategories || totalCategories.value
    totalQuantity.value = response.data?.totalQuantity || response.totalQuantity || totalQuantity.value
    lowStockCount.value = response.data?.lowStockCount || response.lowStockCount || lowStockCount.value
    outOfStockCount.value = response.data?.outOfStockCount || response.outOfStockCount || outOfStockCount.value
    
    // 更新图表数据
    if (stockChartRef.value) {
      const chart = echarts.getInstanceByDom(stockChartRef.value)
      if (chart) {
        chart.setOption({
          series: [{
            data: [
              { value: totalCategories.value - lowStockCount.value - outOfStockCount.value, name: '正常库存', itemStyle: { color: '#52c41a' } },
              { value: lowStockCount.value, name: '低库存', itemStyle: { color: '#faad14' } },
              { value: outOfStockCount.value, name: '缺货', itemStyle: { color: '#f5222d' } }
            ]
          }]
        })
      }
    }
  } catch (error) {
    console.error('获取仓库统计信息失败:', error)
    // 如果获取失败，使用硬编码的统计数据
    totalCategories.value = 86
    totalQuantity.value = 12560
    lowStockCount.value = 12
    outOfStockCount.value = 3
  }
}

// 初始化库存预警图表
const initStockChart = () => {
  if (!stockChartRef.value) return
  
  const chart = echarts.init(stockChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'item'
    },
    legend: {
      top: 'bottom'
    },
    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: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: totalCategories.value - lowStockCount.value - outOfStockCount.value, name: '正常库存', itemStyle: { color: '#52c41a' } },
          { value: lowStockCount.value, name: '低库存', itemStyle: { color: '#faad14' } },
          { value: outOfStockCount.value, name: '缺货', itemStyle: { color: '#f5222d' } }
        ]
      }
    ]
  }
  
  chart.setOption(option)
  
  // 保存图表实例引用以便后续更新
  stockChartRef.value.__chartInstance = chart
  
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 组件挂载时初始化数据和图表
onMounted(async () => {
  await Promise.all([
    fetchMaterials(),
    fetchWarehouseStats()
  ])
  
  setTimeout(() => {
    initStockChart()
  }, 100)
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  if (stockChartRef.value && stockChartRef.value.__chartInstance) {
    const chart = stockChartRef.value.__chartInstance
    chart.dispose()
  }
})
</script>

<style scoped>
  .material-detail {
    padding: 16px;
  }
  
  .detail-row {
    display: flex;
    margin-bottom: 16px;
    align-items: flex-start;
  }
  
  .detail-label {
    width: 120px;
    font-weight: bold;
    color: #666;
  }
  
  .detail-value {
    flex: 1;
    color: #333;
  }
  
  .text-danger {
    color: #f5222d;
  }
  
  .font-weight-bold {
    font-weight: bold;
  }
</style>