<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120"
      v-loading="formLoading"
    >
      <el-row gutter="20">
        <el-col :span="12">
          <el-form-item label="机构ID" prop="orgid">
            <el-input v-model="formData.orgid" placeholder="请输入机构ID" disabled />
          </el-form-item>
          <el-form-item label="机构名称" prop="orgName">
            <el-input v-model="formData.orgName" 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="orgSN">
            <el-input v-model="formData.orgSN" placeholder="请输入机构短号" />
          </el-form-item>
          <el-form-item label="机构码" prop="inHisCode">
            <el-input v-model="formData.inHisCode" placeholder="his系统中的机构码" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系电话" prop="contactTel">
            <el-input v-model="formData.contactTel" placeholder="请输入联系电话" />
          </el-form-item>
          <el-form-item label="联系人姓名" prop="contactPerson">
            <el-input v-model="formData.contactPerson" placeholder="请输入联系人姓名" />
          </el-form-item>
          <el-form-item label="医院机构类型" prop="orgType">
            <el-radio-group v-model="formData.orgType" @change="changeOrgType">
              <el-radio v-for="org in orgType" :value="org.value" :key="org">{{org.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="上级机构" prop="highLevelOrgID" v-if="formData.orgType && formData.orgType == 1">
            <el-select v-model="formData.highLevelOrgID" @change="changeHighOrg">
              <el-option v-for="org in orgInfoList" :label="org.orgName" :value="org.orgid" :key="org.orgid"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { InspectOrgApi, InspectOrgVO } from '@/api/inspect/inspectorg'
import { ElMessage } from 'element-plus'
import validator from 'validator'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
/** tb_org 表单 */
defineOptions({ name: 'InspectOrgForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  orgID: undefined,
  orgName: undefined,
  address: undefined,
  contactTel: undefined,
  contactPerson: undefined,
  reportName: undefined,
  highLevelOrgID: undefined,
  highLevelOrgName: undefined,
  orgSN: undefined,
  createDate: undefined,
  orgLogoUrl: undefined,
  inHisCode: undefined,
  orgType: undefined,
})
const formRules = reactive({
  highLevelOrgID: [{ required: true, message: '请选择上级机构', trigger: 'change' }],
  orgType: [{ required: true, message: '请选择医院机构类型', trigger: 'change' }],
  orgName: [{ required: true, message: '请输入机构名称', trigger: 'change' }],
  contactPerson: [{ required: true, message: '请输入联系人姓名', trigger: 'change' }],
  contactTel: [
    { required: true, message: '请填入正确的手机号', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value && !validator.isMobilePhone(value, 'zh-CN')) {
          callback(new Error('手机号格式错误'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
})
const formRef = ref() // 表单 Ref
// 医院机构类型
const orgType =ref([
  {label: "基层医院",value:1},
  {label: "主医院",value:2}
])
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  await getOrgAll()
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    await removeItemFromList(orgInfoList.value,"orgid",id)
    try {
      formData.value = await InspectOrgApi.getInspectOrg(id)
      if (formData.value)
      if (formData.value.highLevelOrgID){
        formData.value.orgType = 1
      }else {
        formData.value.orgType = 2
      }
    } finally {
      formLoading.value = false
    }
  }
  // console.log(formData.value.orgType)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as InspectOrgVO
    if (formType.value === 'create') {
      await InspectOrgApi.createInspectOrg(data)
      message.success(t('common.createSuccess'))
    } else {
      await InspectOrgApi.updateInspectOrg(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  formData.value.orgLogoUrl = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/png') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
/**
 * 改变医院机构类型
 */
const changeOrgType = () => {
  formData.value.highLevelOrgID = null
  formData.value.highLevelOrgName = null
}
/** 改变上级医院 */
const changeHighOrg = (e) => {
  if (e){
    formData.value.highLevelOrgName = orgInfoList.value.find(a=>a.orgid==e).orgName
  }
}
/**
 * 获取所有机构信息
 */
const getOrgAll =async () => {
  let data =await InspectOrgApi.getInspectOrgAll(null)
  orgInfoList.value = data.list
}
/**
 * 从对象数组中，通过对象的属性值去除指定元素
 * @param list
 * @param prop
 */
const removeItemFromList = async (list:[],prop:string,propValue) => {
  const targetIndex = list.findIndex(item => item[prop] === propValue);
  if (targetIndex !== -1) {
    list.splice(targetIndex, 1);
  }
}
const orgInfoList = ref([]) //  机构信息
/** 重置表单 */
const resetForm = () => {
  formData.value = {
    orgID: undefined,
    orgName: undefined,
    address: undefined,
    contactTel: undefined,
    contactPerson: undefined,
    reportName: undefined,
    highLevelOrgID: undefined,
    highLevelOrgName: undefined,
    orgSN: undefined,
    createDate: undefined,
    orgLogoUrl: undefined,
    inHisCode: undefined,
  }
  formRef.value?.resetFields()
}
</script>
