<template>
  <div class="equipment-procurement-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <div class="page-title">
            <IconDesktop style="font-size: 24px; margin-right: 12px; color: var(--color-primary);" />
            <h1>设备采购管理</h1>
          </div>
          <div class="page-description">
            管理企业设备采购流程，包括采购申请、订单管理、供应商管理等
          </div>
        </div>
        <div class="header-right">
          <a-space>
            <ProcurementSearch
              :loading="loading"
              @search="handleSearch"
              @reset="handleReset"
            />
            <a-button type="primary" @click="handleAdd" size="large">
              <template #icon>
                <IconPlus />
              </template>
              新增采购
            </a-button>
          </a-space>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-container">
      <a-row :gutter="16">
        <a-col :span="6">
          <a-card class="stat-card" :bordered="false">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                <IconDesktop />
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ pagination.total }}</div>
                <div class="stat-label">采购总数</div>
              </div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card" :bordered="false">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
                <IconClockCircle />
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ getPendingCount() }}</div>
                <div class="stat-label">待处理</div>
              </div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card" :bordered="false">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
                <IconCheckCircle />
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ getCompletedCount() }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card" :bordered="false">
            <div class="stat-content">
              <div class="stat-icon" style="background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);">
                <IconApps />
              </div>
              <div class="stat-info">
                <div class="stat-number">¥{{ getTotalAmount() }}</div>
                <div class="stat-label">采购总额</div>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 数据表格 -->
    <a-card class="table-card" :bordered="false">
      <template #title>
        <div class="card-title">
          <span>采购记录</span>
          <div class="table-actions">
            <a-space>
              <a-button type="text" @click="refreshData">
                <template #icon>
                  <IconRefresh />
                </template>
                刷新
              </a-button>
              <a-button type="text" @click="handleExport">
                <template #icon>
                  <IconDownload />
                </template>
                导出
              </a-button>
            </a-space>
          </div>
        </div>
      </template>

      <a-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        row-key="equipmentId"
        @change="handleTableChange"
      >
        <!-- 设备状态 -->
        <template #equipmentStatus="{ record }">
          <a-tag :color="getEquipmentStatusColor(record.equipmentStatus)">
            {{ getEquipmentStatusText(record.equipmentStatus) }}
          </a-tag>
        </template>

        <!-- 位置状态 -->
        <template #locationStatus="{ record }">
          <a-tag :color="getLocationStatusColor(record.locationStatus)">
            {{ getLocationStatusText(record.locationStatus) }}
          </a-tag>
        </template>

        <!-- 健康状态 -->
        <template #healthStatus="{ record }">
          <a-tag :color="getHealthStatusColor(record.healthStatus)">
            {{ getHealthStatusText(record.healthStatus) }}
          </a-tag>
        </template>

        <!-- 采购价格 -->
        <template #purchasePrice="{ record }">
          <span v-if="record.purchasePrice" class="price-text">
            ¥{{ formatPrice(record.purchasePrice) }}
          </span>
          <span v-else class="no-data">-</span>
        </template>

        <!-- 当前净值 -->
        <template #currentNetValue="{ record }">
          <span v-if="record.currentNetValue" class="price-text">
            ¥{{ formatPrice(record.currentNetValue) }}
          </span>
          <span v-else class="no-data">-</span>
        </template>

        <!-- 创建时间 -->
        <template #createTime="{ record }">
          <span v-if="record.createTime" class="time-text">
            {{ formatDateTime(record.createTime) }}
          </span>
          <span v-else class="no-data">-</span>
        </template>

        <!-- 操作 -->
        <template #action="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleView(record)">
              查看
            </a-button>
            <a-button type="text" size="small" @click="handleEdit(record)">
              编辑
            </a-button>
            <!-- 申请采购按钮 -->
            <a-button 
              v-if="canApplyProcurement(record)"
              type="primary" 
              size="small" 
              @click="handleApplyProcurement(record)"
            >
              申请采购
            </a-button>
            <!-- 显示审批状态 -->
            <a-tag v-if="record.approvalStatus" :color="getApprovalStatusColor(record.approvalStatus)">
              {{ getApprovalStatusText(record.approvalStatus) }}
            </a-tag>
            <a-popconfirm
              content="确定要删除这条采购记录吗？"
              @ok="handleDelete(record)"
            >
              <a-button type="text" size="small" status="danger">
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑弹窗 -->
    <ProcurementModal
      v-model:visible="modalVisible"
      :procurement-data="currentProcurement"
      :mode="modalMode"
      @success="handleModalSuccess"
    />

    <!-- 采购申请弹窗 -->
    <ProcurementApplicationModal
      v-model:visible="applicationModalVisible"
      :equipment-data="currentApplicationData"
      @success="handleApplicationSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { Modal } from '@arco-design/web-vue'
import {
  IconCheckCircle,
  IconClockCircle,
  IconDownload,
  IconPlus, 
  IconRefresh,
  IconDesktop,
  IconApps
} from '@arco-design/web-vue/es/icon'
import message from '@arco-design/web-vue/es/message'
import ProcurementModal from './components/ProcurementModal.vue'
import ProcurementSearch from './components/ProcurementSearch.vue'
import ProcurementApplicationModal from './components/ProcurementApplicationModal.vue'
import { equipmentProcurementApi } from '@/apis/equipment/procurement'
import { equipmentApprovalApi } from '@/apis/equipment/approval'
import type { EquipmentListReq, EquipmentResp } from '@/apis/equipment/type'

defineOptions({ name: 'EquipmentProcurement' })

// 当前搜索参数
const currentSearchParams = ref<EquipmentListReq>({
  minPrice: undefined,
  maxPrice: undefined
})

// 表格数据
const tableData = ref<EquipmentResp[]>([])
const loading = ref(false)

// 分页配置
const pagination = reactive<any>({
  current: 1,
  pageSize: 10,
  total: 0,
  showPageSize: true,
  showJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`,
})

// 弹窗控制
const modalVisible = ref(false)
const currentProcurement = ref<EquipmentResp | null>(null)
const modalMode = ref<'add' | 'edit' | 'view'>('add')

// 采购申请弹窗控制
const applicationModalVisible = ref(false)
const currentApplicationData = ref<EquipmentResp | null>(null)

// 表格选择
const selectedRowKeys = ref<string[]>([])
const rowSelection = reactive({
  type: 'checkbox' as const,
  showCheckedAll: true,
  selectedRowKeys,
  onChange: (keys: string[]) => {
    selectedRowKeys.value = keys
  },
})

// 表格列配置
const columns = [
  {
    title: '资产编号',
    dataIndex: 'assetCode',
    key: 'assetCode',
    width: 120,
  },
  {
    title: '设备名称',
    dataIndex: 'equipmentName',
    key: 'equipmentName',
    width: 150,
  },
  {
    title: '设备类型',
    dataIndex: 'equipmentType',
    key: 'equipmentType',
    width: 120,
  },
  {
    title: '设备型号',
    dataIndex: 'equipmentModel',
    key: 'equipmentModel',
    width: 120,
  },
  {
    title: '品牌',
    dataIndex: 'brand',
    key: 'brand',
    width: 100,
  },
  {
    title: '供应商',
    dataIndex: 'supplierName',
    key: 'supplierName',
    width: 150,
  },
  {
    title: '采购订单',
    dataIndex: 'purchaseOrder',
    key: 'purchaseOrder',
    width: 120,
  },
  {
    title: '采购价格',
    dataIndex: 'purchasePrice',
    key: 'purchasePrice',
    slotName: 'purchasePrice',
    width: 120,
  },
  {
    title: '当前净值',
    dataIndex: 'currentNetValue',
    key: 'currentNetValue',
    slotName: 'currentNetValue',
    width: 120,
  },
  {
    title: '设备状态',
    dataIndex: 'equipmentStatus',
    key: 'equipmentStatus',
    slotName: 'equipmentStatus',
    width: 120,
  },
  {
    title: '位置状态',
    dataIndex: 'locationStatus',
    key: 'locationStatus',
    slotName: 'locationStatus',
    width: 120,
  },
  {
    title: '健康状态',
    dataIndex: 'healthStatus',
    key: 'healthStatus',
    slotName: 'healthStatus',
    width: 100,
  },
  {
    title: '负责人',
    dataIndex: 'responsiblePerson',
    key: 'responsiblePerson',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    slotName: 'createTime',
    width: 160,
  },
  {
    title: '操作',
    key: 'action',
    slotName: 'action',
    width: 200,
    fixed: 'right',
  },
]

// 获取设备状态颜色
const getEquipmentStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    normal: 'green',
    repair: 'orange',
    maintain: 'blue',
    scrap: 'red',
  }
  return colorMap[status] || 'blue'
}

// 获取设备状态文本
const getEquipmentStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    normal: '正常',
    repair: '维修中',
    maintain: '保养中',
    scrap: '报废',
  }
  return textMap[status] || '未知'
}

// 获取位置状态颜色
const getLocationStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    not_in_stock: 'gray',
    in_stock: 'blue',
    allocated: 'green',
    repair: 'orange',
    scrap: 'red',
    scrapped: 'red',
    borrowed: 'purple',
    lost: 'gray',
  }
  return colorMap[status] || 'blue'
}

// 获取位置状态文本
const getLocationStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    not_in_stock: '未入库',
    in_stock: '库存中',
    allocated: '已分配',
    repair: '维修中',
    scrap: '待报废',
    scrapped: '已报废',
    borrowed: '外借中',
    lost: '丢失',
  }
  return textMap[status] || '未知'
}

// 获取健康状态颜色
const getHealthStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    excellent: 'green',
    good: 'blue',
    normal: 'orange',
    poor: 'red',
    critical: 'red',
  }
  return colorMap[status] || 'blue'
}

// 获取健康状态文本
const getHealthStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    excellent: '优秀',
    good: '良好',
    normal: '一般',
    poor: '较差',
    critical: '危险',
  }
  return textMap[status] || '未知'
}

// 格式化价格
const formatPrice = (price: number) => {
  return price.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  })
}

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

// 转换后端数据
const transformBackendData = (data: any[]): EquipmentResp[] => {
  return data.map((item: any) => ({
    equipmentId: item.equipmentId || item.id,
    assetCode: item.assetCode,
    equipmentName: item.equipmentName,
    equipmentType: item.equipmentType,
    equipmentTypeLabel: item.equipmentTypeLabel,
    equipmentModel: item.equipmentModel,
    equipmentSn: item.equipmentSn,
    brand: item.brand,
    specification: item.specification,
    equipmentStatus: item.equipmentStatus,
    equipmentStatusLabel: item.equipmentStatusLabel,
    useStatus: item.useStatus,
    locationStatus: item.locationStatus,
    locationStatusLabel: item.locationStatusLabel,
    physicalLocation: item.physicalLocation,
    responsiblePerson: item.responsiblePerson,
    healthStatus: item.healthStatus,
    healthStatusLabel: item.healthStatusLabel,
    purchaseTime: item.purchaseTime,
    inStockTime: item.inStockTime,
    activationTime: item.activationTime,
    expectedScrapTime: item.expectedScrapTime,
    actualScrapTime: item.actualScrapTime,
    statusChangeTime: item.statusChangeTime,
    purchaseOrder: item.purchaseOrder,
    supplierName: item.supplierName,
    purchasePrice: item.purchasePrice,
    currentNetValue: item.currentNetValue,
    depreciationMethod: item.depreciationMethod,
    depreciationYears: item.depreciationYears,
    salvageValue: item.salvageValue,
    warrantyExpireDate: item.warrantyExpireDate,
    lastMaintenanceDate: item.lastMaintenanceDate,
    nextMaintenanceDate: item.nextMaintenanceDate,
    maintenancePerson: item.maintenancePerson,
    inventoryBarcode: item.inventoryBarcode,
    assetRemark: item.assetRemark,
    projectId: item.projectId,
    projectName: item.projectName,
    userId: item.userId,
    name: item.name,
    createTime: item.createTime,
    updateTime: item.updateTime,
    accountNumber: item.accountNumber,
    quantity: item.quantity,
    unitPrice: item.unitPrice,
    totalPrice: item.totalPrice,
    inventoryBasis: item.inventoryBasis,
    dynamicRecord: item.dynamicRecord,
  }))
}

// 加载数据
const loadData = async (searchParams?: EquipmentListReq) => {
  console.log('📊 loadData - 开始加载数据')
  console.log('📊 loadData - 接收到的搜索参数:', searchParams)

  loading.value = true
  try {
    const params: EquipmentListReq = {
      pageSize: pagination.pageSize,
      page: pagination.current,
      minPrice: undefined,
      maxPrice: undefined,
      ...(searchParams || {}),
    }

    console.log('📊 loadData - 构建的完整请求参数:', params)

    const res = await equipmentProcurementApi.page(params)

    console.log('API响应:', res)

    if (res.success || res.status === 200 || res.code === 200) {
      let dataList: any[] = []

      if (Array.isArray(res.data)) {
        dataList = res.data
      } else if (res.data && Array.isArray((res.data as any).records)) {
        dataList = (res.data as any).records
      } else if (res.data && Array.isArray((res.data as any).list)) {
        dataList = (res.data as any).list
      } else if (res.data && Array.isArray((res.data as any).rows)) {
        dataList = (res.data as any).rows
      }

      console.log('处理后的数据列表:', dataList)

      if (dataList.length > 0) {
        const transformedData = transformBackendData(dataList)
        console.log('转换后的数据:', transformedData)
        tableData.value = transformedData
      } else {
        tableData.value = []
      }

      pagination.total = (res.data as any)?.total || (res as any).total || dataList.length || 0
      console.log('总数:', pagination.total)
    } else {
      message.error(res.msg || '加载数据失败')
    }
  } catch (error: any) {
    console.error('加载数据失败:', error)
    message.error(error?.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = (searchParams: EquipmentListReq) => {
  console.log('🔍 主组件 - 接收到的搜索参数:', searchParams)
  pagination.current = 1
  currentSearchParams.value = { ...searchParams }
  loadData(searchParams)
}

// 重置
const handleReset = () => {
  console.log('🔄 主组件 - 重置操作')
  pagination.current = 1
  currentSearchParams.value = {
    minPrice: undefined,
    maxPrice: undefined
  }
  loadData()
}

// 表格变化
const handleTableChange = (pag: any) => {
  pagination.current = pag.current || 1
  pagination.pageSize = pag.pageSize || 10
  loadData(currentSearchParams.value)
}

// 新增
const handleAdd = () => {
  modalMode.value = 'add'
  currentProcurement.value = null
  modalVisible.value = true
}

// 查看
const handleView = (record: EquipmentResp) => {
  modalMode.value = 'view'
  currentProcurement.value = { ...record }
  modalVisible.value = true
}

// 编辑
const handleEdit = (record: EquipmentResp) => {
  modalMode.value = 'edit'
  currentProcurement.value = { ...record }
  modalVisible.value = true
}

// 申请采购
const handleApplyProcurement = (record: EquipmentResp) => {
  currentApplicationData.value = { ...record }
  applicationModalVisible.value = true
}

// 删除
const handleDelete = async (record: EquipmentResp) => {
  try {
    await equipmentProcurementApi.delete(record.equipmentId)
    message.success('删除成功')
    loadData(currentSearchParams.value)
  } catch (error: any) {
    console.error('删除失败:', error)
    message.error(error?.message || '删除失败')
  }
}

// 弹窗成功回调
const handleModalSuccess = () => {
  modalVisible.value = false
  loadData(currentSearchParams.value)
}

// 采购申请成功回调
const handleApplicationSuccess = () => {
  applicationModalVisible.value = false
  loadData(currentSearchParams.value)
}

// 刷新数据
const refreshData = () => {
  loadData(currentSearchParams.value)
}

// 导出数据
const handleExport = async () => {
  try {
    const response = await equipmentProcurementApi.export(currentSearchParams.value)
    const blob = response.data || response
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `设备采购记录_${new Date().toISOString().split('T')[0]}.xlsx`
    link.click()
    window.URL.revokeObjectURL(url)
    message.success('导出成功')
  } catch (error: any) {
    console.error('导出失败:', error)
    message.error(error?.message || '导出失败')
  }
}

// 统计函数
const getPendingCount = () => {
  return tableData.value.filter(item => 
    item.equipmentStatus === 'pending' || 
    item.locationStatus === 'pending'
  ).length
}

const getCompletedCount = () => {
  return tableData.value.filter(item => 
    item.equipmentStatus === 'completed' || 
    item.locationStatus === 'completed'
  ).length
}

const getTotalAmount = () => {
  const total = tableData.value.reduce((sum, item) => {
    return sum + (item.purchasePrice || 0)
  }, 0)
  return formatPrice(total)
}

// 检查是否可以申请采购
const canApplyProcurement = (record: EquipmentResp) => {
  // 检查是否有审批状态，如果没有或者状态为待申请，则可以申请
  return !record.approvalStatus || record.approvalStatus === 'PENDING_APPLICATION'
}

// 获取审批状态颜色
const getApprovalStatusColor = (status: string) => {
  const colorMap: Record<string, string> = {
    'PENDING_APPLICATION': 'blue',
    'PENDING': 'orange',
    'APPROVED': 'green',
    'REJECTED': 'red',
    'WITHDRAWN': 'gray'
  }
  return colorMap[status] || 'blue'
}

// 获取审批状态文本
const getApprovalStatusText = (status: string) => {
  const textMap: Record<string, string> = {
    'PENDING_APPLICATION': '待申请',
    'PENDING': '待审批',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝',
    'WITHDRAWN': '已撤回'
  }
  return textMap[status] || '未知'
}

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

<style scoped lang="scss">
.equipment-procurement-container {
  .page-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    padding: 24px;
    margin-bottom: 24px;
    
    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-left {
        .page-title {
          display: flex;
          align-items: center;
          margin-bottom: 8px;
          
          h1 {
            margin: 0;
            color: white;
            font-size: 28px;
            font-weight: 600;
            background: linear-gradient(135deg, #ffffff 0%, #f0f0f0 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
          }
        }
        
        .page-description {
          color: rgba(255, 255, 255, 0.8);
          font-size: 14px;
        }
      }
      
      .header-right {
        .arco-btn {
          border-radius: 8px;
          font-weight: 500;
        }
      }
    }
  }

  .stats-container {
    margin-bottom: 24px;
    
    .stat-card {
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      
      &:hover {
        transform: translateY(-4px);
        box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
      }
      
      .stat-content {
        display: flex;
        align-items: center;
        
        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 16px;
          
          .arco-icon {
            font-size: 24px;
            color: white;
          }
        }
        
        .stat-info {
          flex: 1;
          
          .stat-number {
            font-size: 24px;
            font-weight: 600;
            color: var(--color-text-1);
            margin-bottom: 4px;
          }
          
          .stat-label {
            font-size: 14px;
            color: var(--color-text-3);
          }
        }
      }
    }
  }

  .table-card {
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    
    .card-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      span {
        font-size: 18px;
        font-weight: 600;
        color: var(--color-text-1);
      }
      
      .table-actions {
        .arco-btn {
          border-radius: 6px;
        }
      }
    }
    
    .arco-table {
      .arco-table-th {
        background-color: var(--color-fill-2);
        font-weight: 600;
      }
      
      .arco-table-tr:hover {
        background-color: var(--color-fill-1);
      }
    }
  }

  .price-text {
    color: #f56c6c;
    font-weight: 500;
  }

  .time-text {
    color: var(--color-text-2);
    font-size: 12px;
  }

  .no-data {
    color: var(--color-text-4);
    font-style: italic;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .equipment-procurement-container {
    .page-header {
      .header-content {
        flex-direction: column;
        align-items: flex-start;
        
        .header-right {
          margin-top: 16px;
          width: 100%;
          
          .arco-space {
            width: 100%;
            justify-content: space-between;
          }
        }
      }
    }
    
    .stats-container {
      .arco-col {
        margin-bottom: 16px;
      }
    }
  }
} 
</style> 