<template>
  <el-dialog
    v-model="dialogVisible"
    title="编辑资产"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      v-if="assetForm"
      ref="formRef"
      :model="assetForm"
      :rules="formRules"
      label-width="120px"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="资产名称" prop="assetName">
            <el-input v-model="assetForm.assetName" placeholder="请输入资产名称" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="设备类型" prop="deviceTypeId">
            <el-select
              v-model="assetForm.deviceTypeId"
              placeholder="请选择设备类型"
              style="width: 100%"
            >
              <el-option
                v-for="type in deviceTypes"
                :key="type.id"
                :label="type.typeName"
                :value="type.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="品牌" prop="brandId">
            <el-select v-model="assetForm.brandId" placeholder="请选择品牌" style="width: 100%">
              <el-option
                v-for="brand in brands"
                :key="brand.id"
                :label="brand.brandName"
                :value="brand.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="规格型号" prop="model">
            <el-input v-model="assetForm.model" placeholder="请输入规格型号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="序列号" prop="serialNumber">
            <el-input v-model="assetForm.serialNumber" placeholder="请输入序列号(SN)" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="所属网点" prop="organizationId">
            <el-tree-select
              v-model="assetForm.organizationId"
              :data="organizationTree"
              placeholder="请选择网点"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="存放位置" prop="location">
        <el-input v-model="assetForm.location" placeholder="请输入存放位置" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        保存
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, reactive, watch } from 'vue'
import { getAssetById, updateAsset, getDeviceTypes, getOrganizationTree } from '@/api'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

interface Props {
  modelValue: boolean
  assetId: number | null
}

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

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

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

const formRef = ref<FormInstance>()
const loading = ref(false)
const assetForm = ref<any>(null)

const deviceTypes = ref<any[]>([])
const brands = ref<any[]>([])
const organizationTree = ref<any[]>([])

const formRules: FormRules = {
  assetName: [{ required: true, message: '请输入资产名称', trigger: 'blur' }],
  deviceTypeId: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  organizationId: [{ required: true, message: '请选择网点', trigger: 'change' }]
}

// 获取资产详情
const fetchAsset = async () => {
  if (!props.assetId) return

  loading.value = true
  try {
    const data = await getAssetById(props.assetId)
    assetForm.value = {
      assetName: data.assetName,
      deviceTypeId: data.deviceTypeId,
      brandId: data.brandId,
      model: data.model,
      serialNumber: data.serialNumber,
      organizationId: data.organizationId,
      location: data.location
    }
  } catch (error) {
    ElMessage.error('获取资产详情失败')
  } finally {
    loading.value = false
  }
}

// 获取设备类型
const fetchDeviceTypes = async () => {
  try {
    deviceTypes.value = await getDeviceTypes({ status: 'active' })
  } catch (error) {
    console.error('获取设备类型失败', error)
  }
}

// 获取网点树
const fetchOrganizations = async () => {
  try {
    organizationTree.value = await getOrganizationTree()
  } catch (error) {
    console.error('获取网点失败', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    await updateAsset(props.assetId!, assetForm.value)

    ElMessage.success('更新成功')
    emit('success')
    handleClose()
  } catch (error) {
    ElMessage.error('更新失败')
  } finally {
    loading.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  emit('update:modelValue', false)
}

// 监听对话框打开
watch(() => props.modelValue, async (val) => {
  if (val) {
    await Promise.all([
      fetchAsset(),
      fetchDeviceTypes(),
      fetchOrganizations()
    ])
  } else {
    assetForm.value = null
    formRef.value?.resetFields()
  }
})
</script>

<style scoped lang="scss">
// 样式继承自全局
</style>
