<script setup lang="ts">
import { Cell as VanCell, CellGroup as VanCellGroup, Field as VanField, Switch as VanSwitch } from 'vant'
import { onMounted, onUnmounted, ref } from 'vue'

interface DeviceFormProps {
  setRef?: (refValue: any) => void
  removeRef?: (refValue: any) => void
  formGroupName?: string
  formData?: any
}

const props = withDefaults(defineProps<DeviceFormProps>(), {
  setRef: () => {},
  removeRef: () => {},
  formGroupName: 'deviceInfo',
  formData: () => ({}),
})

const formData = ref({
  deviceId: '',
  deviceName: '',
  deviceType: '',
  status: 'active',
  isOnline: false,
  ...props.formData,
})

async function validate() {
  if (!formData.value.deviceId) {
    throw new Error('设备ID不能为空')
  }
  if (!formData.value.deviceName) {
    throw new Error('设备名称不能为空')
  }
  return Promise.resolve()
}

function getFormData() {
  return {
    deviceId: formData.value.deviceId,
    deviceName: formData.value.deviceName,
    deviceType: formData.value.deviceType,
    status: formData.value.status,
    isOnline: formData.value.isOnline,
  }
}

function resetForm() {
  formData.value = {
    deviceId: '',
    deviceName: '',
    deviceType: '',
    status: 'active',
    isOnline: false,
  }
}

const exposeObj = {
  validate,
  getFormData,
  resetForm,
  formGroupName: props.formGroupName,
}

defineExpose(exposeObj)

onMounted(() => {
  props.setRef(exposeObj)
})

onUnmounted(() => {
  props.removeRef(exposeObj)
})
</script>

<template>
  <div class="device-form">
    <VanCellGroup inset>
      <VanField
        v-model="formData.deviceId"
        label="设备ID"
        placeholder="请输入设备ID"
        :rules="[{ required: true, message: '请输入设备ID' }]"
      />
      <VanField
        v-model="formData.deviceName"
        label="设备名称"
        placeholder="请输入设备名称"
        :rules="[{ required: true, message: '请输入设备名称' }]"
      />
      <VanField
        v-model="formData.deviceType"
        label="设备类型"
        placeholder="请输入设备类型"
      />
      <VanCell title="设备状态">
        <template #value>
          <span :class="formData.status === 'active' ? 'text-success' : 'text-warning'">
            {{ formData.status === 'active' ? '正常' : '异常' }}
          </span>
        </template>
      </VanCell>
      <VanCell title="在线状态">
        <template #value>
          <VanSwitch v-model="formData.isOnline" />
        </template>
      </VanCell>
    </VanCellGroup>
  </div>
</template>

<style scoped lang="less">
.device-form {
  padding: 16px;
  .text-success {
    color: #07c160;
  }
  .text-warning {
    color: #ff976a;
  }
}
</style>
