<template>
  <a-modal v-model:visible="dialogVisible" title="分配U位" :width="600" :on-before-ok="handleBeforeOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formData" :rules="rules" layout="vertical">
      <a-form-item field="start_unit" label="起始U位" required>
        <a-input-number v-model="formData.start_unit" :min="1" :max="rackHeight" placeholder="请输入起始U位" style="width: 100%" />
      </a-form-item>

      <a-form-item field="occupied_units" label="占用U位数量" required>
        <a-input-number v-model="formData.occupied_units" :min="1" :max="rackHeight" placeholder="请输入占用U位数量" style="width: 100%" />
      </a-form-item>

      <a-form-item field="asset_id" label="选择设备">
        <a-select
          v-model="formData.asset_id"
          placeholder="请选择设备"
          :loading="assetListLoading"
          allow-search
          :filter-option="false"
          @search="handleAssetSearch"
          @change="handleAssetChange"
        >
          <a-option v-for="asset in assetList" :key="asset.id" :value="asset.id">{{ asset.asset_name }} ({{ asset.asset_code }})</a-option>
        </a-select>
      </a-form-item>

      <a-form-item field="asset_type" label="设备类型">
        <a-input v-model="formData.asset_type" placeholder="设备类型（选择设备后自动填入）" disabled />
      </a-form-item>

      <a-form-item field="asset_type_code" label="分类标识">
        <a-input v-model="formData.asset_type_code" placeholder="分类标识（选择设备后自动填入）" disabled />
      </a-form-item>

      <a-form-item field="power_consumption" label="功耗 (W)">
        <a-input-number v-model="formData.power_consumption" :min="0" placeholder="请输入功耗" style="width: 100%" />
      </a-form-item>

      <a-form-item field="description" label="描述">
        <a-textarea v-model="formData.description" placeholder="请输入描述信息" :auto-size="{ minRows: 3, maxRows: 5 }" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export default defineComponent({
  name: 'AllocateUnitDialog',
})
</script>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import { fetchAssetAll } from '@/api/ops/asset'

interface Asset {
  id: number
  asset_code: string
  asset_name: string
  asset_type_name: string
  asset_type_code: string
  category_id?: number
  power_consumption?: number
}

interface Props {
  visible: boolean
  rackId: number
  rackHeight: number
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
})

const formRef = ref()
const assetListLoading = ref(false)
let assetSearchTimer: number | undefined
const formData = reactive({
  start_unit: 1,
  occupied_units: 1,
  asset_id: undefined as number | undefined,
  asset_code: '',
  asset_name: '',
  asset_type: '', // 展示 category.name
  asset_type_code: '', // 提交 category.code
  power_consumption: undefined as number | undefined,
  description: '',
})

const assetList = ref<Asset[]>([])

const rules = {
  start_unit: [{ required: true, message: '请输入起始U位' }],
  occupied_units: [{ required: true, message: '请输入占用U位数量' }],
  asset_id: [{ required: true, message: '请选择设备' }],
}

const syncAssetFields = (value: number | string | undefined) => {
  if (value === undefined || value === null || value === '') return
  const asset = assetList.value.find((a) => String(a.id) === String(value))
  if (asset) {
    formData.asset_id = asset.id
    formData.asset_code = asset.asset_code
    formData.asset_name = asset.asset_name
    formData.asset_type = asset.asset_type_name
    formData.asset_type_code = asset.asset_type_code
    formData.power_consumption = asset.power_consumption
  }
}

const handleAssetChange = (value: number | string) => {
  syncAssetFields(value)
}

const loadAssetList = async (keyword?: string) => {
  assetListLoading.value = true
  try {
    const res: any = await fetchAssetAll({ keyword: keyword || undefined })
    if (res.code === 0) {
      const rowsCandidate = res?.data?.data ?? res?.details?.data ?? res?.data ?? res?.details ?? []
      const rows = Array.isArray(rowsCandidate) ? rowsCandidate : []
      assetList.value = rows.map((item: any) => ({
        id: item.id,
        asset_code: item.asset_code || '',
        asset_name: item.asset_name || '',
        asset_type_name: item?.category?.name || item?.category_name || item?.asset_type_name || '',
        asset_type_code: item?.category?.code ?? item?.category_code ?? item?.asset_type ?? '',
        category_id: item?.category_id,
        power_consumption: item.power_consumption,
      }))
    } else {
      Message.error(res.message || '获取设备列表失败')
      assetList.value = []
    }
  } catch (error) {
    console.error('获取设备列表失败:', error)
    Message.error('获取设备列表失败')
    assetList.value = []
  } finally {
    assetListLoading.value = false
  }
}

const handleAssetSearch = (keyword: string) => {
  if (assetSearchTimer) {
    window.clearTimeout(assetSearchTimer)
  }
  assetSearchTimer = window.setTimeout(() => {
    loadAssetList(keyword?.trim() || undefined)
  }, 300)
}

const handleBeforeOk = async () => {
  try {
    await formRef.value?.validate()
  } catch (error) {
    console.error('分配失败:', error)
    return false
  }

  // 防止 change 事件未触发时字段未回写
  syncAssetFields(formData.asset_id)

  const { allocateUnit } = await import('@/api/ops/unit')
  const params = {
    rack_id: props.rackId,
    start_unit: formData.start_unit,
    occupied_units: formData.occupied_units,
    asset_id: formData.asset_id,
    asset_code: formData.asset_code,
    asset_name: formData.asset_name || `未命名设备-${formData.start_unit}`,
    // 后端字段 asset_type 使用分类标识（category.code）
    asset_type: formData.asset_type_code,
    power_consumption: formData.power_consumption,
    description: formData.description,
  }

  const res = await allocateUnit(params)
  if (res.code === 0) {
    Message.success('分配成功')
    emit('success')
    return true
  } else {
    Message.error(res.message || '分配失败')
    return false
  }
}

const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  formData.start_unit = 1
  formData.occupied_units = 1
  formData.asset_id = undefined
  formData.asset_code = ''
  formData.asset_name = ''
  formData.asset_type = ''
  formData.asset_type_code = ''
  formData.power_consumption = undefined
  formData.description = ''
  formRef.value?.resetFields()
}

watch(
  () => props.visible,
  (val) => {
    if (val) {
      loadAssetList()
    } else {
      resetForm()
    }
  }
)

watch(
  () => formData.asset_id,
  (value) => {
    syncAssetFields(value)
  }
)
</script>
