<template>
  <div class="equipment-center-container">
    <!-- 搜索表单 -->
    <a-card class="search-card" :bordered="false">
      <a-form layout="inline" :model="searchForm" @submit="handleSearch">
        <a-form-item label="设备名称">
          <a-input
            v-model:value="searchForm.equipmentName"
            placeholder="请输入设备名称"
            allow-clear
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item label="设备类型">
          <a-select
            v-model:value="searchForm.equipmentType"
            :options="equipmentTypeOptions"
            placeholder="请选择设备类型"
            allow-clear
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item label="设备状态">
          <a-select
            v-model:value="searchForm.equipmentStatus"
            :options="equipmentStatusOptions"
            placeholder="请选择设备状态"
            allow-clear
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item label="位置状态">
          <a-select
            v-model:value="searchForm.locationStatus"
            :options="locationStatusOptions"
            placeholder="请选择位置状态"
            allow-clear
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item label="健康状态">
          <a-select
            v-model:value="searchForm.healthStatus"
            :options="healthStatusOptions"
            placeholder="请选择健康状态"
            allow-clear
            style="width: 150px"
          />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" html-type="submit" :loading="loading">
            <template #icon>
              <IconSearch />
            </template>
            搜索
          </a-button>
          <a-button style="margin-left: 8px" @click="handleReset">
            <template #icon>
              <IconRefresh />
            </template>
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 操作按钮 -->
    <a-card class="table-card" :bordered="false">
      <template #title>
        <div class="card-title">
          <span>设备中心</span>
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <IconPlus />
            </template>
            新增设备
          </a-button>
        </div>
      </template>

      <!-- 数据表格 -->
      <a-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="pagination"
        row-key="equipmentId"
        @change="handleTableChange"
      >
        <template #equipmentType="{ record }">
          <a-tag :color="getEquipmentTypeColor(record.equipmentType)">
            {{ getEquipmentTypeText(record.equipmentType) }}
          </a-tag>
        </template>
        <template #equipmentStatus="{ record }">
          <a-space>
            <div
              :class="getStatusDotClass(record.equipmentStatus)"
              class="status-dot"
            />
            <a-tag :color="getEquipmentStatusColor(record.equipmentStatus)">
              {{ getEquipmentStatusText(record.equipmentStatus) }}
            </a-tag>
          </a-space>
        </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 #useStatus="{ record }">
          <a-tag :color="record.useStatus === '1' ? 'blue' : 'green'">
            {{ record.useStatus === '1' ? '使用中' : '空闲' }}
          </a-tag>
        </template>
        <template #purchasePrice="{ record }">
          <span v-if="record.purchasePrice">
            ¥{{ formatPrice(record.purchasePrice) }}
          </span>
          <span v-else>-</span>
        </template>
        <template #currentNetValue="{ record }">
          <span v-if="record.currentNetValue">
            ¥{{ formatPrice(record.currentNetValue) }}
          </span>
          <span v-else>-</span>
        </template>
        <template #createTime="{ record }">
          {{ formatDateTime(record.createTime) }}
        </template>
        <template #action="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleView(record)">
              查看
            </a-button>
            <a-button type="text" size="small" @click="handleDetail(record)">
              详情
            </a-button>
            <a-button type="text" size="small" @click="handleEdit(record)">
              编辑
            </a-button>
            <a-button
              v-if="record.useStatus === '0'"
              type="text"
              size="small"
              @click="handleAssign(record)"
            >
              分配
            </a-button>
            <a-button
              v-if="record.useStatus === '1'"
              type="text"
              size="small"
              @click="handleReturn(record)"
            >
              归还
            </a-button>
            <a-button
              type="text"
              size="small"
              danger
              @click="handleDelete(record)"
            >
              删除
            </a-button>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <!-- 新增/编辑弹窗 -->
    <DeviceModal
      v-model:visible="modalVisible"
      :equipment-data="currentEquipment"
      :mode="modalMode"
      @success="handleModalSuccess"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from 'vue'
import { Modal } from '@arco-design/web-vue'
import { IconPlus, IconRefresh, IconSearch } from '@arco-design/web-vue/es/icon'
import message from '@arco-design/web-vue/es/message'
import DeviceModal from './components/DeviceModal.vue'
import router from '@/router'
import {
  assignEquipment,
  deleteEquipment,
  pageEquipment,
  returnEquipment,
} from '@/apis/equipment'
import type { EquipmentPageQuery, EquipmentResp } from '@/types/equipment.d'

defineOptions({ name: 'EquipmentCenter' })

// 搜索表单
const searchForm = reactive<EquipmentPageQuery>({
  equipmentName: '',
  equipmentType: '',
  equipmentStatus: '',
  locationStatus: '',
  healthStatus: '',
})

// 表格数据
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 currentEquipment = ref<EquipmentResp | null>(null)
const modalMode = ref<'add' | 'edit' | 'view'>('add')

// 表格列配置
const columns = [
  {
    title: '资产编号',
    dataIndex: 'assetCode',
    key: 'assetCode',
    width: 120,
  },
  {
    title: '设备名称',
    dataIndex: 'equipmentName',
    key: 'equipmentName',
    width: 150,
  },
  {
    title: '设备类型',
    dataIndex: 'equipmentType',
    key: 'equipmentType',
    slotName: 'equipmentType',
    width: 120,
  },
  {
    title: '设备型号',
    dataIndex: 'equipmentModel',
    key: 'equipmentModel',
    width: 120,
  },
  {
    title: '序列号',
    dataIndex: 'equipmentSn',
    key: 'equipmentSn',
    width: 150,
  },
  {
    title: '品牌',
    dataIndex: 'brand',
    key: 'brand',
    width: 100,
  },
  {
    title: '设备状态',
    dataIndex: 'equipmentStatus',
    key: 'equipmentStatus',
    slotName: 'equipmentStatus',
    width: 120,
  },
  {
    title: '使用状态',
    dataIndex: 'useStatus',
    key: 'useStatus',
    slotName: 'useStatus',
    width: 100,
  },
  {
    title: '位置状态',
    dataIndex: 'locationStatus',
    key: 'locationStatus',
    slotName: 'locationStatus',
    width: 120,
  },
  {
    title: '物理位置',
    dataIndex: 'physicalLocation',
    key: 'physicalLocation',
    width: 150,
  },
  {
    title: '健康状态',
    dataIndex: 'healthStatus',
    key: 'healthStatus',
    slotName: 'healthStatus',
    width: 100,
  },
  {
    title: '负责人',
    dataIndex: 'responsiblePerson',
    key: 'responsiblePerson',
    width: 100,
  },
  {
    title: '当前使用人',
    dataIndex: 'name',
    key: 'name',
    width: 100,
  },
  {
    title: '所属项目',
    dataIndex: 'projectName',
    key: 'projectName',
    width: 150,
  },
  {
    title: '采购价格',
    dataIndex: 'purchasePrice',
    key: 'purchasePrice',
    width: 120,
    slotName: 'purchasePrice',
  },
  {
    title: '当前净值',
    dataIndex: 'currentNetValue',
    key: 'currentNetValue',
    width: 120,
    slotName: 'currentNetValue',
  },
  {
    title: '维护人员',
    dataIndex: 'maintenancePerson',
    key: 'maintenancePerson',
    width: 100,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
    width: 160,
    slotName: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
    slotName: 'action',
    width: 280,
    fixed: 'right',
  },
]

// 下拉选项
const equipmentTypeOptions = [
  { label: '检测设备', value: '1' },
  { label: '安全设备', value: '2' },
  { label: '车辆', value: '3' },
]

const equipmentStatusOptions = [
  { label: '正常', value: 'normal' },
  { label: '维修中', value: 'maintenance' },
  { label: '报废', value: 'scrapped' },
]

const locationStatusOptions = [
  { label: '库存中', value: 'in_stock' },
  { label: '已分配', value: 'allocated' },
  { label: '维修中', value: 'repair' },
  { label: '待报废', value: 'scrap' },
  { label: '已报废', value: 'scrapped' },
  { label: '外借中', value: 'borrowed' },
  { label: '丢失', value: 'lost' },
]

const healthStatusOptions = [
  { label: '优秀', value: 'excellent' },
  { label: '良好', value: 'good' },
  { label: '一般', value: 'normal' },
  { label: '较差', value: 'poor' },
  { label: '差', value: 'bad' },
]

// 获取设备类型文本
const getEquipmentTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    1: '检测设备',
    2: '安全设备',
    3: '车辆',
  }
  return typeMap[type] || type
}

// 获取设备类型颜色
const getEquipmentTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    1: 'blue',
    2: 'green',
    3: 'orange',
  }
  return colorMap[type] || 'default'
}

// 获取设备状态文本
const getEquipmentStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    normal: '正常',
    maintenance: '维修中',
    scrapped: '报废',
  }
  return statusMap[status] || status
}

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

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

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

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

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

// 获取状态点样式
const getStatusDotClass = (status: string) => {
  const classMap: Record<string, string> = {
    normal: 'normal-dot',
    maintenance: 'maintenance-dot',
    scrapped: 'scrapped-dot',
  }
  return classMap[status] || 'normal-dot'
}

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

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return '-'
  try {
    const date = new Date(dateTime)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
    })
  // eslint-disable-next-line unused-imports/no-unused-vars
  } catch (error) {
    return dateTime
  }
}

// 数据转换函数
const transformBackendData = (data: any[]) => {
  console.log('转换前的数据:', data)
  return data.map((item) => {
    console.log('处理单个项目:', item)
    return {
      equipmentId: item.equipmentId || item.id,
      assetCode: item.assetCode,
      equipmentName: item.equipmentName || item.name,
      equipmentType: item.equipmentType || item.type,
      equipmentTypeLabel: item.equipmentTypeLabel,
      equipmentModel: item.equipmentModel || item.model,
      equipmentSn: item.equipmentSn || item.sn,
      brand: item.brand,
      specification: item.specification,
      equipmentStatus: item.equipmentStatus || item.status,
      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 ? new Date(item.createTime).toLocaleString() : '',
      updateTime: item.updateTime ? new Date(item.updateTime).toLocaleString() : '',
    }
  })
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      pageSize: pagination.pageSize,
      page: pagination.current,
      ...searchForm, // 添加搜索条件
    }
    const res = await pageEquipment(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 = () => {
  pagination.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    equipmentName: '',
    equipmentType: '',
    equipmentStatus: '',
    locationStatus: '',
    healthStatus: '',
  })
  pagination.current = 1
  loadData()
}

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

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

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

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

// 详情
const handleDetail = (record: EquipmentResp) => {
  // 跳转到设备详情页面，并传递 equipmentId
  router.push({ name: 'DeviceDetail', params: { id: record.equipmentId } })
}

// 分配
const handleAssign = async (record: EquipmentResp) => {
  Modal.confirm({
    title: '确认分配',
    content: `确定要分配设备"${record.equipmentName}"吗？`,
    onOk: async () => {
      try {
        await assignEquipment(record.equipmentId, 'current-user-id')
        message.success('分配成功')
        loadData()
      } catch (error: any) {
        console.error('分配失败:', error)
        message.error(error?.message || '分配失败')
      }
    },
  })
}

// 归还
const handleReturn = async (record: EquipmentResp) => {
  Modal.confirm({
    title: '确认归还',
    content: `确定要归还设备"${record.equipmentName}"吗？`,
    onOk: async () => {
      try {
        await returnEquipment(record.equipmentId)
        message.success('归还成功')
        loadData()
      } catch (error: any) {
        console.error('归还失败:', error)
        message.error(error?.message || '归还失败')
      }
    },
  })
}

// 删除
const handleDelete = async (record: EquipmentResp) => {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除设备"${record.equipmentName}"吗？此操作不可恢复！`,
    onOk: async () => {
      try {
        await deleteEquipment(record.equipmentId)
        message.success('删除成功')
        loadData()
      } catch (error: any) {
        console.error('删除失败:', error)
        message.error(error?.message || '删除失败')
      }
    },
  })
}

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

// 监听表格数据变化
watch(tableData, (_newData) => {
  // 数据变化监听
}, { deep: true })

// 初始化
onMounted(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.equipment-center-container {
  padding: 16px;
  background: #f5f5f5;
  min-height: 100vh;

  .search-card {
    margin-bottom: 16px;
  }

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

  .status-dot {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    display: inline-block;
  }

  .normal-dot {
    background-color: #52c41a;
  }

  .maintenance-dot {
    background-color: #faad14;
  }

  .scrapped-dot {
    background-color: #ff4d4f;
  }
}
</style>
