<template>
  <div class="asset-create">
    <el-page-header @back="$router.back()" title="返回" content="资产入库" />

    <el-card class="form-card" style="margin-top: 20px">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <h3>基本信息</h3>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="资产名称" prop="assetName">
                <el-input v-model="formData.assetName" placeholder="请输入资产名称" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="设备类型" prop="deviceTypeId">
                <el-select
                  v-model="formData.deviceTypeId"
                  placeholder="请选择设备类型"
                  style="width: 100%"
                  @change="handleDeviceTypeChange"
                >
                  <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="formData.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="formData.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="formData.serialNumber" placeholder="请输入序列号(SN)" />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierId">
                <el-select v-model="formData.supplierId" placeholder="请选择供应商" style="width: 100%">
                  <el-option
                    v-for="supplier in suppliers"
                    :key="supplier.id"
                    :label="supplier.supplierName"
                    :value="supplier.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="采购日期" prop="purchaseDate">
                <el-date-picker
                  v-model="formData.purchaseDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="采购价格" prop="purchasePrice">
                <el-input-number
                  v-model="formData.purchasePrice"
                  :precision="2"
                  :min="0"
                  placeholder="请输入采购价格"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="保修期" prop="warrantyPeriod">
                <el-input-number
                  v-model="formData.warrantyPeriod"
                  :min="0"
                  placeholder="月"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>

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

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

        <!-- 备注 -->
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="4"
            placeholder="请输入备注信息"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-space>
            <el-button @click="$router.back()">取消</el-button>
            <el-button type="primary" plain @click="handleSaveAndContinue">
              保存并继续
            </el-button>
            <el-button type="primary" :loading="loading" @click="handleSave">
              保存
            </el-button>
          </el-space>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { createAsset, getDeviceTypes, getOrganizationTree } from '@/api'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'

const router = useRouter()

const formRef = ref<FormInstance>()
const loading = ref(false)

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

const formData = reactive({
  assetName: '',
  deviceTypeId: null,
  brandId: null,
  model: '',
  serialNumber: '',
  supplierId: null,
  purchaseDate: '',
  purchasePrice: null,
  warrantyPeriod: null,
  organizationId: null,
  location: '',
  remark: ''
})

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

// 获取设备类型
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 handleDeviceTypeChange = (deviceTypeId: number) => {
  // 可以在这里加载动态字段
}

// 保存
const handleSave = async () => {
  if (!formRef.value) return

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

    await createAsset(formData)

    ElMessage.success('创建成功')
    router.push('/assets/list')
  } catch (error) {
    ElMessage.error('创建失败')
  } finally {
    loading.value = false
  }
}

// 保存并继续
const handleSaveAndContinue = async () => {
  if (!formRef.value) return

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

    await createAsset(formData)

    ElMessage.success('创建成功')

    // 重置表单
    Object.assign(formData, {
      assetName: '',
      model: '',
      serialNumber: '',
      purchaseDate: '',
      purchasePrice: null,
      warrantyPeriod: null,
      location: '',
      remark: ''
    })
  } catch (error) {
    ElMessage.error('创建失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchDeviceTypes()
  fetchOrganizations()
})
</script>

<style scoped lang="scss">
.asset-create {
  .form-card {
    max-width: 1000px;
  }

  .form-section {
    margin-bottom: 30px;

    h3 {
      font-size: 16px;
      color: $text-primary;
      font-weight: 600;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid $border-base;
    }
  }
}
</style>
