<template>
  <a-modal
    :visible="visible"
    :title="isEdit ? '编辑设备' : '新增设备'"
    width="900px"
    @ok="handleOk"
    @cancel="handleCancel"
    @update:visible="handleVisibleChange"
    :confirm-loading="submitting"
  >
    <a-form :model="form" layout="vertical" ref="formRef">
      <a-tabs v-model:active-key="activeTab">
        <!-- 基本信息 -->
        <a-tab-pane key="basic" title="基本信息">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item
                label="资产名称"
                field="asset_name"
                :rules="[{ required: true, message: '请输入资产名称' }]"
              >
                <a-input
                  v-model="form.asset_name"
                  placeholder="请输入资产名称"
                  :max-length="200"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item
                label="资产编号"
                field="asset_code"
                :rules="[{ required: true, message: '请输入资产编号' }]"
              >
                <a-input
                  v-model="form.asset_code"
                  placeholder="请输入资产编号"
                  :max-length="100"
                  :disabled="isEdit"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <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="12">
              <a-form-item label="规格型号" field="model">
                <a-input
                  v-model="form.model"
                  placeholder="请输入规格型号"
                  :max-length="200"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="生产厂商" field="manufacturer">
                <a-input
                  v-model="form.manufacturer"
                  placeholder="请输入生产厂商"
                  :max-length="200"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="序列号" field="serial_number">
                <a-input
                  v-model="form.serial_number"
                  placeholder="请输入序列号"
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <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="12">
              <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="12">
              <a-form-item label="供应商" field="supplier_id">
                <a-select
                  v-model="form.supplier_id"
                  placeholder="请选择供应商"
                  allow-clear
                  allow-search
                  :loading="supplierLoading"
                >
                  <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="12">
              <a-form-item label="质保期" field="warranty_period">
                <a-input
                  v-model="form.warranty_period"
                  placeholder="请输入质保期（如：36个月）"
                  :max-length="50"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <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="12">
              <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-tab-pane>

        <!-- 使用信息 -->
        <a-tab-pane key="usage" title="使用信息">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="使用部门" field="department">
                <a-input
                  v-model="form.department"
                  placeholder="请输入使用部门"
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="使用人" field="user">
                <a-input
                  v-model="form.user"
                  placeholder="请输入使用人"
                  :max-length="50"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-tab-pane>

        <!-- 位置信息 -->
        <a-tab-pane key="location" title="位置信息">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="所属数据中心" field="datacenter_id">
                <a-select
                  v-model="form.datacenter_id"
                  placeholder="请选择数据中心"
                  allow-clear
                  allow-search
                  :loading="datacenterLoading"
                  @change="handleDatacenterChange"
                >
                  <a-option
                    v-for="item in datacenterOptions"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  />
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <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"
                  @change="handleFloorChange"
                >
                  <a-option
                    v-for="item in floorOptions"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  />
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <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"
                >
                  <a-option
                    v-for="item in rackOptions"
                    :key="item.id"
                    :value="item.id"
                    :label="item.name"
                  />
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <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="6">
              <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-tab-pane>

        <!-- 其他信息 -->
        <a-tab-pane key="other" title="其他信息">
          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="二维码标签" field="qr_code">
                <a-input
                  v-model="form.qr_code"
                  placeholder="请输入二维码标签"
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="RFID标签" field="rfid_tag">
                <a-input
                  v-model="form.rfid_tag"
                  placeholder="请输入RFID标签"
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-row :gutter="16">
            <a-col :span="12">
              <a-form-item label="资产标签号" field="asset_tag">
                <a-input
                  v-model="form.asset_tag"
                  placeholder="请输入资产标签号"
                  :max-length="100"
                />
              </a-form-item>
            </a-col>
            <a-col :span="12">
              <a-form-item label="技术规格" field="specifications">
                <a-input
                  v-model="form.specifications"
                  placeholder="请输入技术规格"
                  :max-length="500"
                />
              </a-form-item>
            </a-col>
          </a-row>

          <a-form-item label="资产描述" field="description">
            <a-textarea
              v-model="form.description"
              placeholder="请输入资产描述"
              :auto-size="{ minRows: 3, maxRows: 6 }"
              :max-length="1000"
            />
          </a-form-item>

          <a-form-item label="备注" field="remarks">
            <a-textarea
              v-model="form.remarks"
              placeholder="请输入备注"
              :auto-size="{ minRows: 3, maxRows: 6 }"
              :max-length="500"
            />
          </a-form-item>
        </a-tab-pane>
      </a-tabs>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, watch, computed, onMounted } from 'vue'
import { Message } from '@arco-design/web-vue'
import {
  createAsset,
  updateAsset,
  fetchCategoryOptions,
  fetchSupplierOptions,
  fetchDatacenterOptions,
  fetchFloorOptions,
  fetchRackOptions,
  assetStatusOptions,
  AssetForm,
} from '@/api/ops/asset'

interface Device {
  id?: number
  asset_name?: string
  asset_code?: string
  category_id?: number
  model?: string
  manufacturer?: string
  serial_number?: string
  purchase_date?: string
  original_value?: number
  supplier_id?: number
  warranty_period?: string
  warranty_expiry?: string
  department?: string
  user?: string
  status?: string
  location?: string
  datacenter_id?: number
  floor_id?: number
  rack_id?: number
  unit_start?: number
  unit_end?: number
  qr_code?: string
  rfid_tag?: string
  asset_tag?: string
  specifications?: string
  description?: string
  remarks?: string
}

interface Props {
  visible: boolean
  device: Device | null
}

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

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

const formRef = ref()
const submitting = ref(false)
const activeTab = ref('basic')

// 下拉选项
const categoryOptions = ref<any[]>([])
const supplierOptions = ref<any[]>([])
const datacenterOptions = ref<any[]>([])
const floorOptions = ref<any[]>([])
const rackOptions = ref<any[]>([])

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

// 是否为编辑模式
const isEdit = computed(() => !!props.device?.id)

// 表单数据
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 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
  }

  // 加载供应商
  supplierLoading.value = true
  try {
    const res = await fetchSupplierOptions()
    if (res.code === 0) {
      supplierOptions.value = res.details || []
    }
  } catch (error) {
    console.error('加载供应商失败:', error)
  } finally {
    supplierLoading.value = false
  }

  // 加载数据中心
  datacenterLoading.value = true
  try {
    const res = await fetchDatacenterOptions()
    if (res.code === 0) {
      datacenterOptions.value = res.details?.data || res.details || []
    }
  } catch (error) {
    console.error('加载数据中心失败:', error)
  } finally {
    datacenterLoading.value = false
  }
}

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

  if (value) {
    floorLoading.value = true
    try {
      const res = await fetchFloorOptions(value)
      if (res.code === 0) {
        floorOptions.value = res.details || []
      }
    } catch (error) {
      console.error('加载楼层失败:', error)
    } finally {
      floorLoading.value = false
    }
  }
}

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

  if (value) {
    rackLoading.value = true
    try {
      const res = await fetchRackOptions({
        datacenter_id: form.value.datacenter_id,
        floor_id: value,
      })
      if (res.code === 0) {
        rackOptions.value = res.details?.data || res.details || []
      }
    } catch (error) {
      console.error('加载机柜失败:', error)
    } finally {
      rackLoading.value = false
    }
  }
}

// 监听 device 变化，初始化表单
watch(
  () => props.device,
  async (newVal) => {
    if (newVal) {
      form.value = { ...newVal } as AssetForm
      
      // 如果有数据中心，加载楼层
      if (newVal.datacenter_id) {
        try {
          const res = await fetchFloorOptions(newVal.datacenter_id)
          if (res.code === 0) {
            floorOptions.value = res.details || []
          }
        } catch (error) {
          console.error('加载楼层失败:', error)
        }
      }
      
      // 如果有楼层，加载机柜
      if (newVal.floor_id) {
        try {
          const res = await fetchRackOptions({
            datacenter_id: newVal.datacenter_id,
            floor_id: newVal.floor_id,
          })
          if (res.code === 0) {
            rackOptions.value = res.details?.data || res.details || []
          }
        } catch (error) {
          console.error('加载机柜失败:', error)
        }
      }
    } else {
      // 重置表单
      form.value = {
        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: '',
      }
      floorOptions.value = []
      rackOptions.value = []
    }
    activeTab.value = 'basic'
  },
  { immediate: true }
)

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

    submitting.value = true

    const data = { ...form.value }

    let res
    if (isEdit.value) {
      res = await updateAsset({ ...data, id: props.device?.id })
    } else {
      res = await createAsset(data)
    }

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

// 取消
const handleCancel = () => {
  emit('update:visible', false)
}

// 处理对话框可见性变化
const handleVisibleChange = (visible: boolean) => {
  emit('update:visible', visible)
}

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

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

<style scoped lang="less">
:deep(.arco-tabs-content) {
  padding-top: 16px;
}
</style>