<template>
  <el-dialog :title="title" v-model="dialogOpen" width="600px" append-to-body>
    <el-form :model="form" :rules="rules" ref="deviceRef" label-width="80px">
      <el-row :gutter="10">
        <el-col :span="24">
          <el-form-item label="设备图片" prop="imgUrl">
            <image-upload v-model="uploadImg" :limit="1" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备类型" prop="type">
            <el-select v-model="form.type" placeholder="请选择设备类型" clearable style="width: 200px">
              <el-option v-for="dict in deviceTypes" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备号" prop="deviceNo">
            <el-input v-model="form.deviceNo" placeholder="请输入设备号" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备型号" prop="model">
            <el-input v-model="form.model" placeholder="请输入设备型号" maxlength="50" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备地址" prop="deviceAddr">
            <el-input v-model="form.deviceAddr" placeholder="请输入设备地址" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="设备点位" prop="installPointDes">
            <el-input v-model="form.installPointDes" placeholder="请输入设备点位" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="卡号" prop="cardNumber">
            <el-input v-model="form.cardNumber" placeholder="请输入卡号" maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-radio-group v-model="form.status">
              <el-radio v-for="item in statusOptions" :key="item.value" :value="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-if="form.type === '4'">
          <el-form-item label="视频流" prop="videoPlayUrl">
            <el-input v-model="form.videoPlayUrl" placeholder="请输入视频流地址" maxlength="200" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.remark" type="textarea" placeholder="请输入备注内容"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form> 
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { addDevice, updateDevice } from '@/api/device'
import { defaultForm } from '../config'

defineExpose({
  setForm,
  resetForm
})

const props = defineProps({
  open: { type: Boolean, required: true },
  title: { type: String, required: true },
  deviceTypes: { type: Array, required: true },
  statusOptions: { type: Array, required: true },
})

const emits = defineEmits(['update:open', 'success'])

// 创建本地状态来响应open属性的变化
const dialogOpen = ref(props.open)

const form = ref({ ...defaultForm })

const uploadImg = ref('')

watch(() => uploadImg.value, (newVal) => {
  form.value.imgUrl = newVal
})

watch(() => form.value.imgUrl, (newVal) => {
  uploadImg.value = newVal
})

// 表单验证规则
const rules = {
  cardNumber: [{ required: true, message: '请输入卡号', trigger: 'blur' }],
  imgUrl: [{ required: true, message: '请上传设备图片', trigger: 'blur' }],
  type: [{ required: true, message: '请选择设备类型', trigger: 'change' }],
  deviceNo: [{ required: true, message: '设备号不能为空', trigger: 'blur' }],
  deviceAddr: [{ required: true, message: '设备地址不能为空', trigger: 'blur' }],
  model: [{ required: true, message: '设备型号不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '请选择状态', trigger: 'blur' }],
  installPointDes: [{ required: true, message: '安装点描述不能为空', trigger: 'blur' }],
  videoPlayUrl: [{ required: true, message: '视频流地址不能为空', trigger: 'blur' }],
}

// 创建表单引用
const deviceRef = ref(null)

const { proxy } = getCurrentInstance()

onMounted(() => {
  // 重置表单
  setTimeout(() => {
    deviceRef.value?.resetFields()
  }, 0)
})

// 监听props.open的变化，同步到本地状态
watch(
  () => props.open,
  (newValue) => {
    dialogOpen.value = newValue
  }
)

// 监听本地状态的变化，通知父组件更新
watch(
  dialogOpen,
  (newValue) => {
    if (newValue !== props.open) {
      emits('update:open', newValue)
    }
  }
)

// 移除或修改相关函数中的emits调用
// 提交表单
async function submitForm() {
  try {
    await deviceRef.value.validate()

    if (form.value.id) {
      await updateDevice(form.value)
      proxy.$modal.msgSuccess('修改成功')
    } else {
      await addDevice(form.value)
      proxy.$modal.msgSuccess('新增成功')
    }

    dialogOpen.value = false
    resetForm()
    emits('success')
  } catch (error) {
    // 表单验证失败不提示错误
    if (error !== 'cancel') {
      proxy.$modal.msgError('操作失败: ' + (error.message || '未知错误'))
    }
  }
}

function setForm(data) {
  form.value = { ...data }
}

function resetForm() {
  form.value = { ...defaultForm }
  deviceRef.value?.resetFields()
}

// 取消按钮操作
function cancel() {
  dialogOpen.value = false
  deviceRef.value?.resetFields()
}
</script>