<script setup lang="ts">
import { IotYfClassifyApi } from '@/api/pms/yfclass'
import { IotDeviceApi } from '@/api/pms/device'
import * as DeptApi from '@/api/system/dept'
import { defaultProps, handleTree } from '@/utils/tree'
import { DeviceAttrModelApi, type DeviceAttrModelData } from '@/api/pms/deviceattrmodel'
import { IotProductClassifyApi } from '@/api/pms/productclassify'
import { useTagsViewStore } from '@/store/modules/tagsView'
import { Form } from '@/components/Form'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import BrandList from './components/select-list/brand-list.vue'
import CustomerList from './components/select-list/customer-list.vue'
import ModelList from './components/select-list/model-list.vue'
import type { DictDataVO } from '@/api/system/dict/dict.data'
import type { IotModelVO } from '@/api/pms/model'
import type { SupplierVO } from '@/api/supplier/base'
import { useRefreshStore } from '@/store/modules/pms/refreshStore.js'

type DynamicFieldType = 'text' | 'textarea' | 'date' | 'double' | 'int'

interface DynamicField extends Omit<DeviceAttrModelData, 'code' | 'name' | 'type'> {
  code: string
  name: string
  type: DynamicFieldType
}

const { t } = useI18n()
const route = useRoute()
const { currentRoute, push } = useRouter()
const { delView } = useTagsViewStore()
const refreshStore = useRefreshStore()
const message = useMessage()

const deptId = computed(() => {
  return route.query.deptId ? Number(route.query.deptId) : undefined
})

const deviceId = computed(() => {
  const id = route.params.id ?? route.query.id
  return id ? Number(id) : undefined
})

const formType = computed<'create' | 'update'>(() => {
  const queryType = route.query.type as string | undefined
  if (queryType === 'create' || queryType === 'update') {
    return queryType
  }
  return deviceId.value ? 'update' : 'create'
})

const pageTitle = computed(() => {
  return formType.value === 'update' ? '编辑设备' : '新增设备'
})

interface Form {
  id?: number
  yfClass?: string[] | string
  yfDeviceCode?: string
  deviceCode?: string
  deviceName?: string
  deptId?: number
  assetClass?: number
  deviceStatus?: string
  assetProperty?: string
  brand?: number
  brandName?: string
  carNo?: string
  deviceNo?: string
  model?: string
  useProject?: string
  assetOwnership?: string
  address?: string
  picUrl?: string
  remark?: string
  manufacturerName?: string
  manDate?: number | string
  supplierName?: string
  expires?: number | string
  enableDate?: number | string
  nameplate?: string
  manufacturerId?: number
  supplierId?: number
  plPrice?: number | string
  plDate?: number | string
  plYear?: number | string
  plStartDate?: number | string
  plMonthed?: number | string
  plAmounted?: number | string
  remainAmount?: number | string
  monthAmount?: number | string
  totalMonth?: number | string
  currency?: string
  templateJson?: string
  [key: string]: any
}

const form = ref<Form>({
  deptId: deptId.value,
  assetProperty: 'zy'
})
const formRef = ref()
const isYfClassRequired = computed(() => form.value.assetProperty !== 'zl')
type SectionKey = 'base' | 'manufacture' | 'finance' | 'other'

const sectionExpanded = reactive<Record<SectionKey, boolean>>({
  base: true,
  manufacture: false,
  finance: false,
  other: false
})

const toggleSection = (section: SectionKey) => {
  sectionExpanded[section] = !sectionExpanded[section]
}

const expandAllSections = () => {
  Object.keys(sectionExpanded).forEach((key) => {
    sectionExpanded[key as SectionKey] = true
  })
}

const collapseAllSections = () => {
  Object.keys(sectionExpanded).forEach((key) => {
    sectionExpanded[key as SectionKey] = false
  })
}

const formRules = reactive({
  yfClass: [
    {
      validator: (_rule, value, callback) => {
        if (!isYfClassRequired.value || (Array.isArray(value) && value.length > 0)) {
          callback()
          return
        }
        callback(new Error('编码分类不能为空'))
      },
      trigger: 'change'
    }
  ],
  deviceName: [{ required: true, message: '设备名称不能为空', trigger: 'blur' }],
  deviceStatus: [{ required: true, message: '设备状态不能为空', trigger: 'change' }],
  manufacturerName: [{ required: true, message: '制造商不能为空', trigger: 'change' }],
  manDate: [{ required: true, message: '生产日期不能为空', trigger: 'change' }],
  brandName: [{ required: true, message: '品牌不能为空', trigger: 'change' }],
  assetProperty: [{ required: true, message: '资产性质不能为空', trigger: 'change' }],
  deptId: [{ required: true, message: '所在部门不能为空', trigger: 'change' }],
  deviceCode: [{ required: true, message: '历史编码不能为空', trigger: 'blur' }],
  assetClass: [{ required: true, message: '设备类别不能为空', trigger: 'change' }]
})

interface EncodingTypeOption {
  label: string
  value: string
  children?: EncodingTypeOption[]
}

const encodingTypeOptions = ref<EncodingTypeOption[]>([])

const getEncodingTypeOptions = async () => {
  const res = await IotYfClassifyApi.getChildrenList()
  encodingTypeOptions.value = res || []
}

const changeEncodingType = async (val: Form['yfClass']) => {
  if (!val || val.length === 0) return
  const prefix = (val as string[]).join('')
  const last = await IotDeviceApi.getMaxCode(prefix)
  form.value.yfDeviceCode = prefix + last
}

const deptLoading = ref(false)
const deptOptions = ref<any[]>([])

async function loadDept() {
  deptLoading.value = true
  try {
    function sortTreeBySort(treeNodes: Tree[]) {
      if (!treeNodes || !Array.isArray(treeNodes)) return treeNodes
      const sortedNodes = [...treeNodes].sort((a, b) => {
        const sortA = a.sort != null ? a.sort : 999999
        const sortB = b.sort != null ? b.sort : 999999
        return sortA - sortB
      })

      sortedNodes.forEach((node) => {
        if (node.children && Array.isArray(node.children)) {
          node.children = sortTreeBySort(node.children)
        }
      })
      return sortedNodes
    }

    const depts = await DeptApi.getSimpleDeptList()
    deptOptions.value = sortTreeBySort(handleTree(depts))
  } catch (error) {
  } finally {
    deptLoading.value = false
  }
}

const productClassifyOptions = ref<any[]>([])
const dynamicFields = ref<DynamicField[]>([])

const getProductClassifyOptions = async () => {
  const res = await IotProductClassifyApi.getSimpleProductClassifyList()
  productClassifyOptions.value = handleTree(res || [])
}

const isDynamicFieldType = (type: string): type is DynamicFieldType => {
  return ['text', 'textarea', 'date', 'double', 'int'].includes(type)
}

const clearDynamicFieldValues = () => {
  dynamicFields.value.forEach((field) => {
    delete form.value[field.code]
  })
}

const getDynamicFields = async (assetClass?: number) => {
  clearDynamicFieldValues()
  dynamicFields.value = []
  if (!assetClass) return

  const data = await DeviceAttrModelApi.getDeviceAttrModelListByDeviceCategoryId(assetClass)
  dynamicFields.value = (data || []).filter(
    (field): field is DynamicField =>
      Boolean(field.code) && Boolean(field.name) && isDynamicFieldType(field.type)
  )
}

const changeAssetClass = async (assetClass?: number) => {
  await getDynamicFields(assetClass)
}

watch(
  () => form.value.assetProperty,
  () => {
    nextTick(() => {
      formRef.value?.clearValidate('yfClass')
      if (isYfClassRequired.value) {
        formRef.value?.validateField('yfClass')
      }
    })
  }
)

const brandRef = ref()

const clearBrand = () => {
  form.value.brand = undefined
  form.value.brandName = undefined
  form.value.model = undefined
}

const chooseBrand = (row: DictDataVO) => {
  form.value.brand = row.id
  form.value.brandName = row.label
  form.value.model = undefined
}

const selectBrand = () => {
  brandRef.value?.open()
}

const modelRef = ref()

const chooseModel = (row: IotModelVO) => {
  form.value.model = row.name
}

const selectModel = () => {
  if (!form.value.brand) {
    ElMessage.warning('请先选择品牌')
    return
  }
  modelRef.value?.open()
}

const manufacturerRef = ref()
const supplierRef = ref()

const chooseManufacturer = (row: SupplierVO) => {
  form.value.manufacturerId = row.id
  form.value.manufacturerName = row.name
}

const chooseSupplier = (row: SupplierVO) => {
  form.value.supplierId = row.id
  form.value.supplierName = row.name
}

const clearManufacturer = () => {
  form.value.manufacturerId = undefined
  form.value.manufacturerName = undefined
}

const clearSupplier = () => {
  form.value.supplierId = undefined
  form.value.supplierName = undefined
}

const selectManufacturer = () => {
  manufacturerRef.value?.open('选择制造商')
}

const selectSupplier = () => {
  supplierRef.value?.open('选择供应商')
}

const parseTemplateFields = (templateJson?: string) => {
  if (!templateJson) return []
  try {
    const fields = JSON.parse(templateJson)
    return Array.isArray(fields) ? fields : []
  } catch {
    return []
  }
}

const loadDeviceDetail = async () => {
  if (!deviceId.value) return
  const device = await IotDeviceApi.getIotDevice(deviceId.value)
  const templateFields = parseTemplateFields(device.templateJson)

  form.value = {
    ...form.value,
    ...device,
    yfClass: device.yfClass ? device.yfClass.split(',') : undefined,
    manufacturerName: device.zzName ?? device.manufacturerName,
    supplierName: device.supplierName
  }

  await getDynamicFields(device.assetClass)
  templateFields.forEach((field) => {
    if (field?.code) {
      form.value[field.code] = field.value
    }
  })
}

const syncTemplateJson = () => {
  form.value.templateJson = JSON.stringify(
    dynamicFields.value.map((field) => ({
      ...field,
      value: form.value[field.code]
    }))
  )
}

const submitLoading = ref(false)

const handleSave = async () => {
  submitLoading.value = true
  try {
    await formRef.value?.validate()
    syncTemplateJson()
    form.value.yfClass = (form.value.yfClass as string[]).join(',')

    const data: any = form.value

    console.log('sssssssssssssssssssss', formType.value)

    if (formType.value === 'create') {
      await IotDeviceApi.createIotDevice(data)
      message.success(t('common.createSuccess'))
    } else {
      await IotDeviceApi.updateIotDevice(data)
      message.success(t('common.updateSuccess'))
    }

    const sourcePage = route.query.source as string

    if (sourcePage) {
      refreshStore.triggerRefresh(sourcePage)
    }
    handleCancel()
  } finally {
    submitLoading.value = false
  }
}

const handleCancel = () => {
  delView(unref(currentRoute))
  push({ name: 'IotDevicePms', params: {} })
}

onMounted(() => {
  loadDept()
  getEncodingTypeOptions()
  getProductClassifyOptions()
  loadDeviceDetail()
})
</script>

<template>
  <div class="iot-device-form-page">
    <div class="page-header">
      <div class="page-header__main">
        <div class="page-header__icon">
          <Icon icon="ep:monitor" :size="22" />
        </div>
        <div class="page-header__content">
          <div class="page-title">
            <span>{{ pageTitle }}</span>
          </div>
          <div class="page-subtitle">设备台账信息维护</div>
        </div>
      </div>
    </div>

    <main class="form-content">
      <el-form
        ref="formRef"
        class="device-form"
        :model="form"
        :rules="formRules"
        label-position="top"
        size="default">
        <section class="info-card">
          <div class="info-card__header">
            <div class="info-card__title">
              <span class="info-card__marker"></span>
              <span>基本信息</span>
            </div>
            <el-button link type="primary" class="info-card__toggle" @click="toggleSection('base')">
              <Icon :icon="sectionExpanded.base ? 'ep:arrow-up' : 'ep:arrow-down'" class="mr-4px" />
              {{ sectionExpanded.base ? '收起' : '展开' }}
            </el-button>
          </div>

          <div v-show="sectionExpanded.base" class="info-card__body">
            <div class="form-grid">
              <el-form-item
                :label="t('iotDevice.yfClass')"
                prop="yfClass"
                :required="isYfClassRequired">
                <el-cascader
                  :disabled="formType === 'update' && Boolean(form.yfDeviceCode)"
                  v-model="form.yfClass"
                  placeholder="请输入编码分类"
                  clearable
                  filterable
                  :options="encodingTypeOptions"
                  :props="{ expandTrigger: 'hover' }"
                  @change="changeEncodingType" />
              </el-form-item>
              <el-form-item :label="t('iotDevice.yfCode')" prop="yfDeviceCode">
                <el-input placeholder="系统生成" disabled v-model="form.yfDeviceCode" />
              </el-form-item>
              <el-form-item :label="t('iotDevice.code')" prop="deviceCode">
                <el-input
                  :disabled="formType === 'update'"
                  v-model="form.deviceCode"
                  placeholder="请输入历史编码" />
              </el-form-item>
              <el-form-item :label="t('iotDevice.name')" prop="deviceName">
                <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
              </el-form-item>
              <el-form-item :label="t('iotDevice.dept')" prop="deptId">
                <el-tree-select
                  :disabled="formType === 'update'"
                  v-model="form.deptId"
                  :data="deptOptions"
                  :props="defaultProps"
                  check-strictly
                  node-key="id"
                  filterable
                  clearable
                  placeholder="请选择所在部门" />
              </el-form-item>
              <el-form-item :label="t('deviceForm.category')" prop="assetClass">
                <el-tree-select
                  :disabled="formType === 'update'"
                  v-model="form.assetClass"
                  :data="productClassifyOptions"
                  :props="defaultProps"
                  check-strictly
                  node-key="id"
                  clearable
                  filterable
                  placeholder="请选择设备类别"
                  @change="changeAssetClass" />
              </el-form-item>
              <el-form-item :label="t('iotDevice.status')" prop="deviceStatus">
                <el-select
                  v-model="form.deviceStatus"
                  placeholder="请选择设备状态"
                  :disabled="formType === 'update'"
                  clearable>
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.PMS_DEVICE_STATUS)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item :label="t('iotDevice.assets')" prop="assetProperty">
                <el-select v-model="form.assetProperty" placeholder="请选择资产性质" clearable>
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.PMS_ASSET_PROPERTY)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item :label="t('iotDevice.brand')" prop="brandName">
                <el-input v-model="form.brandName" readonly placeholder="请选择品牌">
                  <template #suffix>
                    <Icon
                      v-if="form.brandName"
                      icon="ep:circle-close"
                      class="form-input-clear"
                      @mousedown.prevent
                      @click.stop="clearBrand" />
                  </template>
                  <template #append>
                    <el-button @click="selectBrand">选择</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item label="车牌号" prop="carNo">
                <el-input clearable v-model="form.carNo" placeholder="请输入车牌号" />
              </el-form-item>
              <el-form-item label="设备号" prop="deviceNo">
                <el-input clearable v-model="form.deviceNo" placeholder="请输入设备号" />
              </el-form-item>
              <el-form-item :label="t('deviceForm.model')" prop="model">
                <el-input clearable v-model="form.model" placeholder="请输入或选择规格型号">
                  <template #append>
                    <el-button @click="selectModel">选择</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item :label="t('deviceForm.useProject')" prop="useProject">
                <el-input clearable v-model="form.useProject" placeholder="请输入使用项目" />
              </el-form-item>
              <el-form-item label="资产归属" prop="assetOwnership">
                <el-input clearable v-model="form.assetOwnership" placeholder="请输入资产归属" />
              </el-form-item>
              <el-form-item label="所在地点" prop="address">
                <el-input clearable v-model="form.address" placeholder="请输入所在地点" />
              </el-form-item>
              <el-form-item :label="t('deviceForm.picture')" prop="picUrl" class="image-field">
                <UploadImg v-model="form.picUrl" height="94px" width="100%" class="size-full" />
              </el-form-item>
              <el-form-item label="备注" prop="remark" class="remark-field">
                <el-input
                  clearable
                  v-model="form.remark"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入备注信息" />
              </el-form-item>
            </div>
          </div>
        </section>

        <section class="info-card">
          <div class="info-card__header">
            <div class="info-card__title">
              <span class="info-card__marker"></span>
              <span>制造信息</span>
            </div>
            <el-button
              link
              type="primary"
              class="info-card__toggle"
              @click="toggleSection('manufacture')">
              <Icon
                :icon="sectionExpanded.manufacture ? 'ep:arrow-up' : 'ep:arrow-down'"
                class="mr-4px" />
              {{ sectionExpanded.manufacture ? '收起' : '展开' }}
            </el-button>
          </div>

          <div v-show="sectionExpanded.manufacture" class="info-card__body">
            <div class="form-grid">
              <el-form-item :label="t('deviceForm.mfg')" prop="manufacturerName">
                <el-input
                  readonly
                  v-model="form.manufacturerName"
                  :placeholder="t('deviceForm.mfgHolder')">
                  <template #suffix>
                    <Icon
                      v-if="form.manufacturerName"
                      icon="ep:circle-close"
                      class="form-input-clear"
                      @mousedown.prevent
                      @click.stop="clearManufacturer" />
                  </template>
                  <template #append>
                    <el-button @click="selectManufacturer">选择</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item :label="t('deviceForm.pd')" prop="manDate">
                <el-date-picker
                  v-model="form.manDate"
                  type="date"
                  value-format="x"
                  :placeholder="t('deviceForm.pdHolder')" />
              </el-form-item>
              <el-form-item :label="t('deviceForm.supplier')" prop="supplierName">
                <el-input
                  readonly
                  v-model="form.supplierName"
                  :placeholder="t('deviceForm.suppHolder')">
                  <template #suffix>
                    <Icon
                      v-if="form.supplierName"
                      icon="ep:circle-close"
                      class="form-input-clear"
                      @mousedown.prevent
                      @click.stop="clearSupplier" />
                  </template>
                  <template #append>
                    <el-button @click="selectSupplier">选择</el-button>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item :label="t('deviceForm.warranty')" prop="expires">
                <el-date-picker
                  v-model="form.expires"
                  type="date"
                  value-format="x"
                  :placeholder="t('deviceForm.warrHolder')" />
              </el-form-item>
              <el-form-item :label="t('deviceForm.ni')" prop="nameplate" class="nameplate-field">
                <el-input
                  clearable
                  v-model="form.nameplate"
                  type="textarea"
                  :rows="5"
                  :placeholder="t('deviceForm.niHolder')" />
              </el-form-item>
              <el-form-item :label="t('deviceForm.enable')" prop="enableDate">
                <el-date-picker
                  v-model="form.enableDate"
                  type="date"
                  value-format="x"
                  :placeholder="t('deviceForm.enableHolder')" />
              </el-form-item>
            </div>
          </div>
        </section>

        <section class="info-card">
          <div class="info-card__header">
            <div class="info-card__title">
              <span class="info-card__marker"></span>
              <span>财务信息</span>
            </div>
            <el-button
              link
              type="primary"
              class="info-card__toggle"
              @click="toggleSection('finance')">
              <Icon
                :icon="sectionExpanded.finance ? 'ep:arrow-up' : 'ep:arrow-down'"
                class="mr-4px" />
              {{ sectionExpanded.finance ? '收起' : '展开' }}
            </el-button>
          </div>

          <div v-show="sectionExpanded.finance" class="info-card__body">
            <div class="form-grid">
              <el-form-item
                :label="form.assetProperty === 'zy' ? '采购价格' : '租赁价格'"
                prop="plPrice">
                <el-input-number
                  clearable
                  :controls="false"
                  :precision="2"
                  :min="0"
                  align="left"
                  class="w-full!"
                  v-model="form.plPrice"
                  :placeholder="
                    form.assetProperty === 'zy' ? '请输入采购价格' : '请输入租赁价格'
                  " />
              </el-form-item>
              <el-form-item
                :label="form.assetProperty === 'zy' ? '采购日期' : '租赁日期'"
                prop="plDate">
                <el-date-picker
                  v-model="form.plDate"
                  type="date"
                  value-format="x"
                  :placeholder="
                    form.assetProperty === 'zy' ? '请选择采购日期' : '请选择租赁日期'
                  " />
              </el-form-item>
              <el-form-item
                :label="form.assetProperty === 'zy' ? '折旧年限' : '租赁年限'"
                prop="plYear">
                <el-input-number
                  clearable
                  :controls="false"
                  :precision="0"
                  :min="0"
                  align="left"
                  class="w-full!"
                  v-model="form.plYear"
                  :placeholder="
                    form.assetProperty === 'zy' ? '请输入折旧年限' : '请输入租赁年限'
                  " />
              </el-form-item>
              <el-form-item
                :label="form.assetProperty === 'zy' ? '折旧开始日期' : '租赁开始日期'"
                prop="plStartDate">
                <el-date-picker
                  v-model="form.plStartDate"
                  type="date"
                  value-format="x"
                  :placeholder="
                    form.assetProperty === 'zy' ? '请选择折旧开始日期' : '请选择租赁开始日期'
                  " />
              </el-form-item>
              <el-form-item
                :label="form.assetProperty === 'zy' ? '已提折旧月数' : '已租赁月数'"
                prop="plMonthed">
                <el-input
                  clearable
                  :controls="false"
                  :precision="0"
                  :min="0"
                  align="left"
                  class="w-full!"
                  v-model="form.plMonthed"
                  :placeholder="
                    form.assetProperty === 'zy' ? '请输入已提折旧月数' : '请输入已租赁月数'
                  " />
              </el-form-item>
              <el-form-item
                :label="form.assetProperty === 'zy' ? '已提折旧金额' : '已租赁金额'"
                prop="plAmounted">
                <el-input-number
                  clearable
                  :controls="false"
                  :precision="2"
                  :min="0"
                  align="left"
                  class="w-full!"
                  v-model="form.plAmounted"
                  :placeholder="
                    form.assetProperty === 'zy' ? '请输入已提折旧金额' : '请输入已租赁金额'
                  " />
              </el-form-item>
              <el-form-item label="剩余金额" prop="remainAmount">
                <el-input-number
                  clearable
                  :controls="false"
                  :precision="2"
                  :min="0"
                  align="left"
                  class="w-full!"
                  v-model="form.remainAmount"
                  placeholder="请输入剩余金额" />
              </el-form-item>
              <el-form-item label="每月折旧金额" prop="monthAmount">
                <el-input-number
                  clearable
                  :controls="false"
                  :precision="2"
                  :min="0"
                  align="left"
                  class="w-full!"
                  v-model="form.monthAmount"
                  placeholder="请输入每月折旧金额" />
              </el-form-item>
              <el-form-item label="总折旧月份" prop="totalMonth">
                <el-input-number
                  clearable
                  :controls="false"
                  :precision="0"
                  :min="0"
                  align="left"
                  class="w-full!"
                  v-model="form.totalMonth"
                  placeholder="请输入总折旧月份" />
              </el-form-item>
              <el-form-item label="币种" prop="currency">
                <el-input clearable v-model="form.currency" placeholder="请输入币种" />
              </el-form-item>
            </div>
          </div>
        </section>

        <section v-if="dynamicFields.length" class="info-card">
          <div class="info-card__header">
            <div class="info-card__title">
              <span class="info-card__marker"></span>
              <span>其他信息</span>
            </div>
            <el-button
              link
              type="primary"
              class="info-card__toggle"
              @click="toggleSection('other')">
              <Icon
                :icon="sectionExpanded.other ? 'ep:arrow-up' : 'ep:arrow-down'"
                class="mr-4px" />
              {{ sectionExpanded.other ? '收起' : '展开' }}
            </el-button>
          </div>

          <div v-show="sectionExpanded.other" class="info-card__body">
            <div class="form-grid">
              <el-form-item
                v-for="field in dynamicFields"
                :key="field.code"
                :label="field.name"
                :prop="field.code"
                :required="Boolean(field.requiredFlag)"
                :class="{ 'dynamic-textarea-field': field.type === 'textarea' }">
                <el-input
                  v-if="field.type === 'text'"
                  clearable
                  v-model="form[field.code]"
                  :placeholder="`请输入${field.name}`" />
                <el-input
                  v-else-if="field.type === 'textarea'"
                  clearable
                  v-model="form[field.code]"
                  type="textarea"
                  :rows="4"
                  :placeholder="`请输入${field.name}`" />
                <el-date-picker
                  v-else-if="field.type === 'date'"
                  v-model="form[field.code]"
                  type="date"
                  value-format="YYYY-MM-DD"
                  :placeholder="`请选择${field.name}`" />
                <el-input-number
                  v-else-if="field.type === 'int'"
                  v-model="form[field.code]"
                  :controls="false"
                  :precision="0"
                  :min="0"
                  align="left"
                  class="w-full!"
                  :placeholder="`请输入${field.name}`" />
                <el-input-number
                  v-else-if="field.type === 'double'"
                  v-model="form[field.code]"
                  :controls="false"
                  :precision="2"
                  :min="0"
                  align="left"
                  class="w-full!"
                  :placeholder="`请输入${field.name}`" />
              </el-form-item>
            </div>
          </div>
        </section>
      </el-form>
    </main>

    <div class="form-action-bar">
      <el-button size="default" @click="expandAllSections">一键展开</el-button>
      <el-button size="default" @click="collapseAllSections">一键收起</el-button>
      <el-button size="default" @click="handleCancel">取消</el-button>
      <el-button size="default" type="primary" @click="handleSave">保存</el-button>
    </div>
  </div>
  <brand-list ref="brandRef" @choose="chooseBrand" />
  <model-list ref="modelRef" @choose="chooseModel" :brand="form.brand" />
  <customer-list ref="manufacturerRef" @choose="chooseManufacturer" />
  <customer-list ref="supplierRef" @choose="chooseSupplier" />
</template>

<style scoped lang="scss">
.iot-device-form-page {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: calc(
    100vh - 20px - var(--top-tool-height) - var(--tags-view-height) - var(--app-footer-height)
  );
  overflow-y: auto;
}

.form-content {
  flex: 1;
  padding: 20px;
}

.page-header {
  position: sticky;
  top: 0;
  z-index: 10;
  display: flex;
  min-height: 72px;
  padding: 12px 20px;
  background: linear-gradient(135deg, rgb(64 158 255 / 8%) 0%, rgb(103 194 58 / 7%) 100%),
    var(--el-bg-color);
  border-bottom: 1px solid rgb(64 158 255 / 14%);
  box-shadow: 0 8px 22px rgb(31 45 61 / 5%);
  align-items: center;
}

.page-header__main {
  display: flex;
  gap: 12px;
  align-items: center;
}

.page-header__icon {
  display: flex;
  width: 44px;
  height: 44px;
  color: var(--el-color-primary);
  background: rgb(64 158 255 / 12%);
  border: 1px solid rgb(64 158 255 / 18%);
  border-radius: 8px;
  align-items: center;
  justify-content: center;
}

.page-header__content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.page-title {
  display: flex;
  gap: 10px;
  font-size: 18px;
  font-weight: 600;
  line-height: 24px;
  color: var(--el-text-color-primary);
  align-items: center;
}

.page-subtitle {
  font-size: 13px;
  line-height: 18px;
  color: var(--el-text-color-secondary);
}

.info-card {
  overflow: hidden;
  background: var(--el-bg-color);
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 8px;
  box-shadow: 0 10px 28px rgb(31 45 61 / 6%);
}

.info-card__header {
  display: flex;
  min-height: 58px;
  padding: 0 20px;
  background: linear-gradient(90deg, rgb(64 158 255 / 8%) 0%, rgb(255 255 255 / 0%) 72%);
  border-bottom: 1px solid var(--el-border-color-lighter);
  align-items: center;
  justify-content: space-between;
}

.info-card__title {
  display: flex;
  gap: 10px;
  font-size: 16px;
  font-weight: 600;
  line-height: 22px;
  color: var(--el-text-color-primary);
  align-items: center;
}

.info-card__marker {
  width: 4px;
  height: 18px;
  background: var(--el-color-primary);
  border-radius: 2px;
}

.info-card__toggle {
  display: inline-flex;
  height: 32px;
  padding: 0;
  font-size: 13px;
  line-height: 18px;
  align-items: center;
}

.device-form {
  display: flex;
  flex-direction: column;
  gap: 18px;
}

.form-action-bar {
  position: sticky;
  bottom: 0;
  z-index: 12;
  display: flex;
  min-height: 64px;
  padding: 12px 20px;
  background: var(--el-bg-color);
  border-top: 1px solid var(--el-border-color-lighter);
  box-shadow: 0 -8px 22px rgb(31 45 61 / 6%);
  align-items: center;
  justify-content: flex-end;
  gap: 10px;
}

.info-card__body {
  padding: 22px 20px 20px;
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(3, minmax(0, 1fr));
  gap: 12px 22px;
}

.form-grid :deep(.el-form-item) {
  margin-bottom: 18px;
}

.form-grid :deep(.el-form-item__label) {
  margin-bottom: 7px;
  font-size: 13px;
  font-weight: 500;
  line-height: 18px;
  color: var(--el-text-color-regular);
}

.form-grid :deep(.el-select),
.form-grid :deep(.el-cascader),
.form-grid :deep(.el-tree-select),
.form-grid :deep(.el-date-editor),
.form-grid :deep(.el-input-number) {
  width: 100%;
}

.form-grid :deep(.el-input__wrapper),
.form-grid :deep(.el-textarea__inner) {
  box-shadow: 0 0 0 1px var(--el-border-color-lighter) inset;
}

.form-input-clear {
  color: var(--el-text-color-placeholder);
  cursor: pointer;
}

.form-input-clear:hover {
  color: var(--el-text-color-secondary);
}

.image-field {
  grid-row: span 2;
}

.image-uploader {
  display: flex;
  width: 100%;
  min-height: 126px;
  color: var(--el-text-color-secondary);
  cursor: pointer;
  background: var(--el-fill-color-lighter);
  border: 1px dashed var(--el-border-color);
  border-radius: 8px;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  gap: 8px;
  transition:
    color var(--el-transition-duration),
    border-color var(--el-transition-duration),
    background-color var(--el-transition-duration);
}

.image-uploader:hover {
  color: var(--el-color-primary);
  background: rgb(64 158 255 / 5%);
  border-color: var(--el-color-primary);
}

.remark-field {
  grid-column: span 2;
}

.nameplate-field {
  grid-column: span 2;
  grid-row: span 2;
}

.dynamic-textarea-field {
  grid-column: span 2;
}

@media (width <= 1200px) {
  .form-grid {
    grid-template-columns: repeat(2, minmax(0, 1fr));
  }
}

@media (width <= 768px) {
  .form-content {
    padding: 12px;
  }

  .form-action-bar {
    padding: 10px 12px;
  }

  .info-card__header {
    padding: 12px 16px;
    align-items: flex-start;
    flex-direction: column;
    gap: 4px;
  }

  .info-card__body {
    padding: 18px 16px 2px;
  }

  .form-grid {
    grid-template-columns: minmax(0, 1fr);
  }

  .remark-field {
    grid-column: auto;
  }

  .nameplate-field {
    grid-column: auto;
  }

  .dynamic-textarea-field {
    grid-column: auto;
  }
}
</style>
