<template>
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      :disabled="formType === 'detail'"
    >
      <el-form-item label="单位名称" prop="name">
        <el-input v-model="formData.name" placeholder="请输入单位名称" />
      </el-form-item>
      <el-form-item label="登录账号" prop="loginname" v-if="formType === 'create'">
        <el-input v-model="formData.loginname" placeholder="请输入登录账号" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="formType === 'create'">
        <el-input v-model="formData.password" type="password" placeholder="请输入密码" show-password />
      </el-form-item>
      <el-form-item label="联系人" prop="contact">
        <el-input v-model="formData.contact" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="formData.phone" placeholder="请输入联系电话" />
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="formData.address" placeholder="请输入地址" />
      </el-form-item>
      <el-form-item label="是否默认" prop="isDefault">
        <el-select v-model="formData.isDefault" placeholder="请选择是否默认" class="!w-full">
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="默认名称" prop="defaultName" v-if="formData.isDefault === '1'">
        <el-input v-model="formData.defaultName" placeholder="请输入默认名称" />
      </el-form-item>
    </el-form>
    <template #footer v-if="formType !== 'detail'">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitForm" :loading="formLoading">确定</el-button>
    </template>
    <template #footer v-else>
      <el-button @click="dialogVisible = false">关闭</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {
  getOrgDetail,
  addOrg,
  updateOrg,
  type Org,
  type AddOrgData,
  type UpdateOrgData
} from '@/api/interphone/org'

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref<'create' | 'update' | 'detail'>('create') // 表单的类型：create - 新增；update - 修改；detail - 详情
const formData = ref<any>({
  id: undefined,
  name: '',
  loginname: '',
  password: '',
  contact: '',
  phone: '',
  address: '',
  isDefault: '0',
  defaultName: ''
})
const formRules = {
  name: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
  loginname: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: 'create' | 'update' | 'detail', id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增单位' : type === 'update' ? '编辑单位' : '单位详情'
  formType.value = type
  resetForm()
  
  // 修改或详情时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const res = await getOrgDetail(id)
      if (res.code === 0) {
        formData.value = { ...res.data }
      } else {
        message.error(res.msg || '获取单位详情失败')
        dialogVisible.value = false
      }
    } catch (error) {
      console.error('获取单位详情失败:', error)
      message.error('获取单位详情失败')
      dialogVisible.value = false
    } finally {
      formLoading.value = false
    }
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  if (!formRef.value) return
  const valid = await formRef.value.validate()
  if (!valid) return
  
  // 提交请求
  formLoading.value = true
  try {
    let res
    if (formType.value === 'create') {
      res = await addOrg(formData.value as AddOrgData)
    } else {
      res = await updateOrg({
        id: formData.value.id,
        corgName: formData.value.name,
        contact: formData.value.contact,
        address: formData.value.address
      } as UpdateOrgData)
    }
    
    if (res.code === 0) {
      message.success(formType.value === 'create' ? '新增成功' : '修改成功')
      dialogVisible.value = false
      // 发送操作成功的事件
      emit('success')
    } else {
      message.error(res.msg || '操作失败')
    }
  } catch (error) {
    console.error('操作失败:', error)
    message.error('操作失败')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: '',
    loginname: '',
    password: '',
    contact: '',
    phone: '',
    address: '',
    isDefault: '0',
    defaultName: ''
  }
  formRef.value?.resetFields()
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗
</script>
