<template>
  <div class="equipment-inventory">
    <a-card title="设备盘库管理" :bordered="false">
      <template #extra>
        <a-button type="primary" @click="handleBatchInventory">
          <template #icon>
            <IconPlus />
          </template>
          批量盘库
        </a-button>
      </template>

      <!-- 搜索区域 -->
      <div class="search-container">
        <a-form layout="inline" :model="searchForm" class="search-form">
          <a-form-item label="设备名称">
            <a-input 
              v-model="searchForm.equipmentName" 
              placeholder="请输入设备名称" 
              allow-clear
              style="width: 200px"
              @input="debouncedSearch"
            />
          </a-form-item>
          
          <a-form-item label="资产编号">
            <a-input 
              v-model="searchForm.assetCode" 
              placeholder="请输入资产编号" 
              allow-clear
              style="width: 200px"
              @input="debouncedSearch"
            />
          </a-form-item>
          
          <a-form-item label="设备类型">
            <a-select 
              v-model="searchForm.equipmentType" 
              placeholder="请选择类型" 
              allow-clear
              style="width: 150px"
              @change="debouncedSearch"
            >
              <a-option value="">全部</a-option>
              <a-option value="COMPUTER">计算机设备</a-option>
              <a-option value="NETWORK">网络设备</a-option>
              <a-option value="STORAGE">存储设备</a-option>
              <a-option value="SECURITY">安防设备</a-option>
              <a-option value="OTHER">其他设备</a-option>
            </a-select>
          </a-form-item>
          
          <a-form-item>
            <a-space>
              <a-button type="primary" @click="search">
                <template #icon><IconSearch /></template>
                搜索
              </a-button>
              <a-button @click="reset">
                <template #icon><IconRefresh /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </div>

      <a-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        @page-change="handlePageChange"
        @page-size-change="handlePageSizeChange"
      >
        <template #toolbar-left>
          <span class="search-result-info">
            共找到 <strong>{{ pagination.total }}</strong> 条记录
          </span>
        </template>
        
        <template #equipmentStatus="{ record }">
          <a-tag :color="getStatusColor(record.equipmentStatus)">
            {{ getStatusText(record.equipmentStatus) }}
          </a-tag>
        </template>

        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleView(record)">
              查看详情
            </a-button>
            <a-button type="text" size="small" @click="handleInventory(record)">
              执行盘库
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { Message } from '@arco-design/web-vue'
import { IconSearch, IconRefresh, IconPlus } from '@arco-design/web-vue/es/icon'
import { pageEquipmentInventory } from '@/apis/equipment'
import type { EquipmentResp } from '@/types/equipment.d'

// 防抖函数
const debounce = (func: Function, delay: number) => {
  let timeoutId: NodeJS.Timeout
  return (...args: any[]) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func.apply(null, args), delay)
  }
}

defineOptions({ name: 'EquipmentInventory' })

// 表格列定义
const columns = [
  { title: '设备名称', dataIndex: 'equipmentName', key: 'equipmentName', width: 180 },
  { title: '资产编号', dataIndex: 'assetCode', key: 'assetCode', width: 150 },
  { title: '设备类型', dataIndex: 'equipmentType', key: 'equipmentType', width: 120 },
  { title: '品牌', dataIndex: 'brand', key: 'brand', width: 100 },
  { title: '型号', dataIndex: 'equipmentModel', key: 'equipmentModel', width: 120 },
  { title: '设备状态', dataIndex: 'equipmentStatus', key: 'equipmentStatus', slotName: 'equipmentStatus', width: 100 },
  { title: '负责人', dataIndex: 'responsiblePerson', key: 'responsiblePerson', width: 100 },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime', width: 180 },
  { title: '操作', key: 'operations', slotName: 'operations', width: 200 }
]

// 搜索表单
const searchForm = reactive({
  equipmentName: '',
  assetCode: '',
  equipmentType: ''
})

// 表格数据
const tableData = ref<EquipmentResp[]>([])
const loading = ref(false)
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true,
  showJumper: true,
  showPageSize: true
})

// 表格选择
const selectedRowKeys = ref<string[]>([])
const rowSelection = computed(() => ({
  selectedRowKeys: selectedRowKeys.value,
  onChange: (keys: string[]) => {
    selectedRowKeys.value = keys
  }
}))

// 获取状态颜色
const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    'IDLE': 'blue',
    'IN_USE': 'green',
    'MAINTENANCE': 'orange',
    'REPAIR': 'red',
    'SCRAPPED': 'gray'
  }
  return colors[status] || 'blue'
}

// 获取状态文本
const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    'IDLE': '空闲中',
    'IN_USE': '使用中',
    'MAINTENANCE': '保养中',
    'REPAIR': '维修中',
    'SCRAPPED': '已报废'
  }
  return texts[status] || '未知'
}

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    const response = await pageEquipmentInventory({
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
      equipmentName: searchForm.equipmentName || undefined,
      assetCode: searchForm.assetCode || undefined,
      equipmentType: searchForm.equipmentType || undefined
    })
    
    if (response.status === 200) {
      // 检查响应数据结构
      if (response.data && Array.isArray(response.data)) {
        // 如果直接返回数组，说明没有分页信息
        tableData.value = response.data
        pagination.total = response.data.length
      } else if (response.data && typeof response.data === 'object' && 'records' in response.data) {
        // 如果有分页信息
        const pageData = response.data as any
        tableData.value = pageData.records || []
        pagination.total = pageData.total || pageData.records?.length || 0
        pagination.current = pageData.current || 1
      } else {
        tableData.value = []
        pagination.total = 0
      }
    } else {
      Message.error('获取数据失败')
    }
  } catch (error) {
    console.error('获取设备盘库列表失败:', error)
    Message.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 防抖搜索函数
const debouncedSearch = debounce(() => {
  pagination.current = 1
  getTableData()
}, 300)

// 搜索
const search = () => {
  pagination.current = 1
  getTableData()
}

// 重置
const reset = () => {
  Object.assign(searchForm, {
    equipmentName: '',
    assetCode: '',
    equipmentType: ''
  })
  pagination.current = 1
  getTableData()
}

// 查看详情
const handleView = (record: EquipmentResp) => {
  console.log('查看设备详情:', record)
}

// 执行盘库
const handleInventory = (record: EquipmentResp) => {
  console.log('执行设备盘库:', record)
}

// 批量盘库
const handleBatchInventory = () => {
  if (selectedRowKeys.value.length === 0) {
    Message.warning('请先选择要盘库的设备')
    return
  }
  console.log('批量盘库设备:', selectedRowKeys.value)
}

// 分页事件
const handlePageChange = (page: number) => {
  pagination.current = page
  getTableData()
}

const handlePageSizeChange = (pageSize: number) => {
  pagination.pageSize = pageSize
  pagination.current = 1
  getTableData()
}

onMounted(() => {
  getTableData()
})
</script>

<style scoped lang="scss">
.equipment-inventory {
  .arco-card {
    margin-bottom: 16px;
  }
}

.search-container {
  padding: 16px;
  background: var(--color-bg-2);
  border-radius: 6px;
  margin-bottom: 16px;
  
  .search-form {
    .arco-form-item {
      margin-bottom: 0;
      margin-right: 16px;
      
      .arco-form-item-label {
        font-weight: 500;
        color: var(--color-text-1);
        margin-right: 8px;
      }
    }
    
    .arco-input,
    .arco-select {
      border-radius: 4px;
    }
    
    .arco-btn {
      border-radius: 4px;
    }
  }
}

.search-result-info {
  color: var(--color-text-2);
  font-size: 14px;
  
  strong {
    color: var(--color-text-1);
    font-weight: 600;
  }
}
</style>
