<template>
  <div class="device-form-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <a-button type="text" @click="handleBack">
          <template #icon><icon-left /></template>
          返回列表
        </a-button>
        <a-divider direction="vertical" />
        <h2 class="page-title">{{ pageTitle }}</h2>
      </div>
      <div class="header-right">
        <a-space>
          <a-button @click="handleBack">取消</a-button>
          <a-button type="primary" :loading="submitting" @click="handleSubmit">
            {{ isEdit ? '保存' : '创建' }}
          </a-button>
        </a-space>
      </div>
    </div>

    <!-- 表单内容 -->
    <div class="page-content">
      <a-spin :loading="loading" style="width: 100%">
        <a-form ref="formRef" :model="form" :rules="rules" layout="vertical">
          <!-- 基本信息 -->
          <a-card class="info-card" title="基本信息">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="资产名称" field="asset_name" required>
                  <a-input
                    v-model="form.asset_name"
                    placeholder="请输入资产名称"
                    :max-length="200"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="资产编号" field="asset_code" required>
                  <a-input
                    v-model="form.asset_code"
                    placeholder="请输入资产编号"
                    :max-length="100"
                    :disabled="isEdit"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="资产分类" field="category_id">
                  <a-select
                    v-model="form.category_id"
                    placeholder="请选择资产分类"
                    allow-clear
                    allow-search
                    :loading="categoryLoading"
                  >
                    <a-option
                      v-for="item in categoryOptions"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    />
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="规格型号" field="model">
                  <a-input
                    v-model="form.model"
                    placeholder="请输入规格型号"
                    :max-length="200"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="生产厂商" field="manufacturer">
                  <a-input
                    v-model="form.manufacturer"
                    placeholder="请输入生产厂商"
                    :max-length="200"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="序列号" field="serial_number">
                  <a-input
                    v-model="form.serial_number"
                    placeholder="请输入序列号"
                    :max-length="100"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="采购日期" field="purchase_date">
                  <a-date-picker
                    v-model="form.purchase_date"
                    placeholder="请选择采购日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="原值（元）" field="original_value">
                  <a-input-number
                    v-model="form.original_value"
                    placeholder="请输入原值"
                    :min="0"
                    :precision="2"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="供应商" field="supplier_id">
                  <a-select
                    v-model="form.supplier_id"
                    placeholder="请选择供应商"
                    allow-clear
                    allow-search
                    :loading="supplierLoading"
                    :filter-option="false"
                    @search="handleSupplierSearch"
                    @dropdown-visible-change="handleSupplierDropdownChange"
                  >
                    <a-option
                      v-for="item in supplierOptions"
                      :key="item.id"
                      :value="item.id"
                      :label="item.name"
                    />
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="质保期" field="warranty_period">
                  <a-input
                    v-model="form.warranty_period"
                    placeholder="请输入质保期（如：36个月）"
                    :max-length="50"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="质保到期日期" field="warranty_expiry">
                  <a-date-picker
                    v-model="form.warranty_expiry"
                    placeholder="请选择质保到期日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="资产状态" field="status">
                  <a-select v-model="form.status" placeholder="请选择资产状态">
                    <a-option
                      v-for="item in assetStatusOptions"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>

          <!-- 使用信息 -->
          <a-card class="info-card" title="使用信息">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="使用部门" field="department">
                  <a-input
                    v-model="form.department"
                    placeholder="请输入使用部门"
                    :max-length="100"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="使用人" field="user">
                  <a-input
                    v-model="form.user"
                    placeholder="请输入使用人"
                    :max-length="50"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>

          <!-- 位置信息 -->
          <a-card class="info-card" title="位置信息">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="所属数据中心" field="datacenter_id">
                  <a-select
                    v-model="form.datacenter_id"
                    placeholder="请选择数据中心"
                    allow-clear
                    allow-search
                    :loading="datacenterLoading"
                    :filter-option="false"
                    @search="handleDatacenterSearch"
                    @change="handleDatacenterChange"
                  >
                    <a-option
                      v-for="item in datacenterOptions"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="所属楼层" field="floor_id">
                  <a-select
                    v-model="form.floor_id"
                    placeholder="请选择楼层"
                    allow-clear
                    allow-search
                    :loading="floorLoading"
                    :disabled="!form.datacenter_id"
                    :filter-option="false"
                    @search="handleFloorSearch"
                    @change="handleFloorChange"
                  >
                    <a-option
                      v-for="item in floorOptions"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                    />
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="所属机柜" field="rack_id">
                  <a-select
                    v-model="form.rack_id"
                    placeholder="请选择机柜"
                    allow-clear
                    allow-search
                    :loading="rackLoading"
                    :disabled="!form.floor_id"
                    :filter-option="false"
                    @search="handleRackSearch"
                  >
                    <a-option
                      v-for="item in rackOptions"
                      :key="item.id"
                      :value="item.id"
                    >
                      {{ item.name }} ({{ item.code }})
                    </a-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-form-item label="起始U位" field="unit_start">
                  <a-input-number
                    v-model="form.unit_start"
                    placeholder="起始U位"
                    :min="1"
                    :max="48"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="3">
                <a-form-item label="结束U位" field="unit_end">
                  <a-input-number
                    v-model="form.unit_end"
                    placeholder="结束U位"
                    :min="1"
                    :max="48"
                    style="width: 100%"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>

          <!-- 其他信息 -->
          <a-card class="info-card" title="其他信息">
            <a-row :gutter="16">
              <a-col :span="6">
                <a-form-item label="二维码标签" field="qr_code">
                  <a-input
                    v-model="form.qr_code"
                    placeholder="请输入二维码标签"
                    :max-length="100"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="RFID标签" field="rfid_tag">
                  <a-input
                    v-model="form.rfid_tag"
                    placeholder="请输入RFID标签"
                    :max-length="100"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="资产标签号" field="asset_tag">
                  <a-input
                    v-model="form.asset_tag"
                    placeholder="请输入资产标签号"
                    :max-length="100"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="技术规格" field="specifications">
                  <a-input
                    v-model="form.specifications"
                    placeholder="请输入技术规格"
                    :max-length="500"
                    allow-clear
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="资产描述" field="description">
                  <a-textarea
                    v-model="form.description"
                    placeholder="请输入资产描述"
                    :auto-size="{ minRows: 3, maxRows: 6 }"
                    :max-length="1000"
                    show-word-limit
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="备注" field="remarks">
                  <a-textarea
                    v-model="form.remarks"
                    placeholder="请输入备注"
                    :auto-size="{ minRows: 3, maxRows: 6 }"
                    :max-length="500"
                    show-word-limit
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-card>
        </a-form>
      </a-spin>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import type { FormInstance } from '@arco-design/web-vue/es/form'
import {
  createAsset,
  updateAsset,
  fetchAssetDetail,
  fetchCategoryOptions,
  assetStatusOptions,
  AssetForm,
} from '@/api/ops/asset'
import { fetchAllSuppliers } from '@/api/ops/supplier'
import { fetchDatacenterList, fetchRackListByFloor } from '@/api/ops/rack'
import { fetchFloorListByDatacenter } from '@/api/ops/floor'

const router = useRouter()
const route = useRoute()

// 页面状态
const isEdit = ref(false)
const deviceId = ref<number | null>(null)
const pageTitle = ref('新增设备')
const loading = ref(false)
const submitting = ref(false)
const formRef = ref<FormInstance>()

// 下拉选项
const categoryOptions = ref<any[]>([])
const supplierOptions = ref<any[]>([])
const datacenterOptions = ref<{ label: string; value: number }[]>([])
const floorOptions = ref<{ label: string; value: number }[]>([])
const rackOptions = ref<any[]>([])

// 加载状态
const categoryLoading = ref(false)
const supplierLoading = ref(false)
const datacenterLoading = ref(false)
const floorLoading = ref(false)
const rackLoading = ref(false)

// 搜索防抖定时器
let datacenterSearchTimer: number | undefined
let floorSearchTimer: number | undefined
let rackSearchTimer: number | undefined

// 表单数据
const form = ref<AssetForm>({
  asset_name: '',
  asset_code: '',
  category_id: undefined,
  model: '',
  manufacturer: '',
  serial_number: '',
  purchase_date: '',
  original_value: undefined,
  supplier_id: undefined,
  warranty_period: '',
  warranty_expiry: '',
  department: '',
  user: '',
  status: 'in_use',
  location: '',
  datacenter_id: undefined,
  floor_id: undefined,
  rack_id: undefined,
  unit_start: undefined,
  unit_end: undefined,
  qr_code: '',
  rfid_tag: '',
  asset_tag: '',
  specifications: '',
  description: '',
  remarks: '',
})

// 表单验证规则
const rules = {
  asset_name: [{ required: true, message: '请输入资产名称' }],
  asset_code: [{ required: true, message: '请输入资产编号' }],
}

// 提取列表数据的辅助函数
const extractList = (res: any): any[] => {
  const candidate =
    res?.data?.data ?? res?.details?.data ?? res?.data ?? res?.details ?? []
  return Array.isArray(candidate) ? candidate : []
}

// 加载下拉选项
const loadOptions = async () => {
  // 加载资产分类
  categoryLoading.value = true
  try {
    const res = await fetchCategoryOptions()
    if (res.code === 0) {
      categoryOptions.value = res.details || []
    }
  } catch (error) {
    console.error('加载资产分类失败:', error)
  } finally {
    categoryLoading.value = false
  }

  // 加载全部数据中心（默认列出全部，支持模糊搜索）
  await fetchDatacenters()
}

// 加载供应商选项（默认20条，搜索时全部）
const loadSupplierOptions = async (keyword?: string) => {
  supplierLoading.value = true
  try {
    const res = await fetchAllSuppliers(keyword, 'active', keyword ? undefined : 20)
    if (res.code === 0) {
      supplierOptions.value = res.details?.data || res.details || []
    }
  } catch (error) {
    console.error('加载供应商失败:', error)
  } finally {
    supplierLoading.value = false
  }
}

// 供应商搜索
const handleSupplierSearch = (keyword: string) => {
  loadSupplierOptions(keyword)
}

// 供应商下拉框展开时加载
const handleSupplierDropdownChange = (visible: boolean) => {
  if (visible && supplierOptions.value.length === 0) {
    loadSupplierOptions()
  }
}

// 加载数据中心列表
const fetchDatacenters = async (keyword?: string) => {
  datacenterLoading.value = true
  try {
    const res: any = await fetchDatacenterList({ keyword })
    const rows = extractList(res)
    datacenterOptions.value = rows.map((d: any) => ({
      label: d.name || d.code || String(d.id),
      value: d.id,
    }))
  } catch (error) {
    console.error('获取数据中心列表失败:', error)
    datacenterOptions.value = []
  } finally {
    datacenterLoading.value = false
  }
}

// 数据中心搜索（带防抖）
const handleDatacenterSearch = (keyword: string) => {
  if (datacenterSearchTimer) {
    window.clearTimeout(datacenterSearchTimer)
  }
  datacenterSearchTimer = window.setTimeout(() => {
    fetchDatacenters(keyword?.trim() || undefined)
  }, 300)
}

// 加载楼层列表
const fetchFloors = async (keyword?: string) => {
  if (!form.value.datacenter_id) {
    floorOptions.value = []
    return
  }
  floorLoading.value = true
  try {
    const res: any = await fetchFloorListByDatacenter(form.value.datacenter_id, {
      name: keyword || undefined,
    })
    const rows = extractList(res)
    floorOptions.value = rows.map((floor: any) => ({
      label: floor.name || floor.code || String(floor.id),
      value: floor.id,
    }))
  } catch (error) {
    console.error('获取楼层列表失败:', error)
    floorOptions.value = []
  } finally {
    floorLoading.value = false
  }
}

// 楼层搜索（带防抖）
const handleFloorSearch = (keyword: string) => {
  if (!form.value.datacenter_id) return
  if (floorSearchTimer) {
    window.clearTimeout(floorSearchTimer)
  }
  floorSearchTimer = window.setTimeout(() => {
    fetchFloors(keyword?.trim() || undefined)
  }, 300)
}

// 加载机柜列表
const fetchRacks = async (keyword?: string) => {
  if (!form.value.floor_id) {
    rackOptions.value = []
    return
  }
  rackLoading.value = true
  try {
    const res: any = await fetchRackListByFloor(form.value.floor_id, { name: keyword })
    rackOptions.value = extractList(res)
  } catch (error) {
    console.error('获取机柜列表失败:', error)
    rackOptions.value = []
  } finally {
    rackLoading.value = false
  }
}

// 机柜搜索（带防抖）
const handleRackSearch = (keyword: string) => {
  if (!form.value.floor_id) return
  if (rackSearchTimer) {
    window.clearTimeout(rackSearchTimer)
  }
  rackSearchTimer = window.setTimeout(() => {
    fetchRacks(keyword?.trim() || undefined)
  }, 300)
}

// 数据中心变化时加载楼层
const handleDatacenterChange = async (value: number | undefined) => {
  form.value.floor_id = undefined
  form.value.rack_id = undefined
  floorOptions.value = []
  rackOptions.value = []

  if (value) {
    await fetchFloors()
  }
}

// 楼层变化时加载机柜
const handleFloorChange = async (value: number | undefined) => {
  form.value.rack_id = undefined
  rackOptions.value = []

  if (value) {
    await fetchRacks()
  }
}

// 初始化页面
const initPage = async () => {
  await loadOptions()

  const id = route.query.id
  if (id) {
    isEdit.value = true
    deviceId.value = Number(id)
    pageTitle.value = '编辑设备'
    await loadDeviceDetail()
  }
}

// 加载设备详情
const loadDeviceDetail = async () => {
  if (!deviceId.value) return

  loading.value = true
  try {
    const res = await fetchAssetDetail(deviceId.value)
    if (res.code === 0) {
      form.value = { ...res.details } as AssetForm

      // 如果有供应商，加载供应商选项
      if (res.details.supplier_id) {
        try {
          const supplierRes = await fetchAllSuppliers()
          if (supplierRes.code === 0) {
            supplierOptions.value = supplierRes.details?.data || supplierRes.details || []
          }
        } catch (error) {
          console.error('加载供应商失败:', error)
        }
      }

      // 如果有数据中心，加载楼层
      if (res.details.datacenter_id) {
        try {
          const floorRes: any = await fetchFloorListByDatacenter(res.details.datacenter_id)
          const rows = extractList(floorRes)
          floorOptions.value = rows.map((floor: any) => ({
            label: floor.name || floor.code || String(floor.id),
            value: floor.id,
          }))
        } catch (error) {
          console.error('加载楼层失败:', error)
        }
      }

      // 如果有楼层，加载机柜
      if (res.details.floor_id) {
        try {
          const rackRes: any = await fetchRackListByFloor(res.details.floor_id)
          rackOptions.value = extractList(rackRes)
        } catch (error) {
          console.error('加载机柜失败:', error)
        }
      }
    } else {
      Message.error(res.message || '获取详情失败')
      router.push('/ops/assets/device')
    }
  } catch (error) {
    console.error('获取设备详情失败:', error)
    Message.error('获取详情失败')
    router.push('/ops/assets/device')
  } finally {
    loading.value = false
  }
}

// 返回上一级
const handleBack = () => {
  router.push('/assets/device')
}

// 提交表单
const handleSubmit = async () => {
  try {
    const valid = await formRef.value?.validate()
    if (valid) {
      return
    }

    submitting.value = true

    const data = { ...form.value }

    let res
    if (isEdit.value && deviceId.value) {
      res = await updateAsset({ ...data, id: deviceId.value })
    } else {
      res = await createAsset(data)
    }

    if (res.code === 0) {
      Message.success(isEdit.value ? '更新成功' : '创建成功')
      handleBack()
    } else {
      Message.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('提交表单失败:', error)
    Message.error('操作失败')
  } finally {
    submitting.value = false
  }
}

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

<script lang="ts">
export default {
  name: 'DeviceForm',
}
</script>

<style scoped lang="less">
.device-form-page {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--color-fill-2);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background-color: var(--color-bg-2);
  border-bottom: 1px solid var(--color-border);
  flex-shrink: 0;

  .header-left {
    display: flex;
    align-items: center;

    .page-title {
      margin: 0;
      font-size: 18px;
      font-weight: 500;
    }
  }
}

.page-content {
  flex: 1;
  padding: 20px;
  overflow: auto;
}

.info-card {
  margin-bottom: 16px;

  &:last-child {
    margin-bottom: 0;
  }
}

// 表单项样式优化
:deep(.arco-form-item) {
  margin-bottom: 16px;
}

:deep(.arco-card) {
  .arco-card-header {
    border-bottom: 1px solid var(--color-border);
  }
}
</style>