<script setup>
import { ref, reactive, watch } from 'vue'
import { message } from 'ant-design-vue'
import { runLogic } from '@vue2-client/services/api/common'

// 接受父组件传递的属性
const props = defineProps({
  visible: Boolean,
  id: {
    type: Number,
    default: 180
  },
  modalType: {
    type: String,
    default: 'create',
    validator: (value) => ['create', 'update'].includes(value)
  },
  editorReady: {
    type: Boolean,
    default: false
  }
})

// 定义组件事件
const emit = defineEmits(['update:visible', 'submit', 'cancel'])

// 常量
const modalTitles = {
  create: '创建体温单',
  update: '更新体温单'
}

// 响应式状态
const submitLoading = ref(false)
const formErrors = ref({})

// 表单数据
const formData = reactive({
  id: '',
  name: '',
  inDate: '',
  diag: '',
  dept: '',
  bed: '',
  medicalNo: '',
  begin: '',
  operateDate: '',
  notes: '',
  sex: '男',
  weight: '',
  heart: '',
  tempType: '',
  temperature: '',
  breath: '',
  sphygmus: '',
  physicalcool: '',
  labels: '',
  data1: '',
  data2: '',
  data3: '',
  data4: '',
  data5: '',
  data6: '',
  data7: '',
  data8: '',
  data9: '',
  pain: ''
})

// 监听 props 变化初始化表单
watch(() => props.visible, (newVal, oldVal) => {
  if (newVal) {
    // 如果是从关闭状态变为打开状态，重置表单错误
    formErrors.value = {}

    // 无论何种模式，都先尝试从服务加载数据
    initFormData()
  } else if (oldVal && !newVal) {
    // 当弹窗关闭时，清空表单数据，为下次打开做准备
    resetForm()
  }
}, { immediate: true })

watch(() => props.modalType, (newVal) => {
  if (props.visible) {
    // 无论何种模式，都先尝试从服务加载数据
    initFormData()
  }
})

watch(() => props.id, (newVal) => {
  if (newVal) {
    formData.id = newVal
  }
}, { immediate: true })

// 重置表单为默认值
function resetForm () {
  // 清空表单错误
  formErrors.value = {}
  const today = new Date().toISOString().split('T')[0]
  // 重置所有字段
  formData.id = props.id
  formData.name = ''
  formData.inDate = today
  formData.diag = ''
  formData.dept = ''
  formData.bed = ''
  formData.medicalNo = ''
  formData.begin = today
  formData.operateDate = ''
  formData.notes = ''
  formData.sex = ''
  formData.weight = ''
  formData.heart = ''
  formData.tempType = ''
  formData.temperature = ''
  formData.pulse = ''
  formData.breathing = ''
  formData.bloodPressure = ''
  formData.labels = ''
  formData.data1 = ''
  formData.data2 = ''
  formData.data3 = ''
  formData.data4 = ''
  formData.data5 = ''
  formData.data6 = ''
  formData.data7 = ''
  formData.data8 = ''
  formData.data9 = ''
  formData.pain = ''
}
// 处理JSON字符串数据
const parseFormData = (data) => {
  if (!data) return null
  try {
    // 如果是字符串，尝试解析为JSON
    if (typeof data === 'string') {
      return JSON.parse(data)
    }
    // 如果已经是对象且有f_data字段，尝试解析f_data
    if (typeof data === 'object' && data.f_data) {
      return JSON.parse(data.f_data)
    }
    // 如果是普通对象，直接返回
    return data
  } catch (error) {
    console.error('解析数据失败:', error)
    return null
  }
}

// 初始化表单数据
async function initFormData () {
  try {
    let parsedData = null
    let resultData = null
    try {
      // 尝试从服务器获取数据
      resultData = await runLogic('threeTestOrderDataLOGIC', { id: props.id }, 'af-his')
      console.log('体温单数据 = ', resultData)
      // 处理不同格式的返回数据
      if (resultData) {
        // 如果是数组，取第一项
        if (Array.isArray(resultData) && resultData.length > 0) {
          const firstItem = resultData[0]

          // 检查是否有f_data字段
          if (firstItem.f_data) {
            parsedData = parseFormData(firstItem.f_data)
          } else {
            // 可能整个对象就是数据
            parsedData = firstItem
          }
        } else if (typeof resultData === 'object') {
          if (resultData.f_data) {
            parsedData = parseFormData(resultData.f_data)
          } else { parsedData = resultData }
        }
      }
    } catch (error) {
      console.error('获取数据失败:', error)
    }
    // 如果解析成功且非创建模式，填充表单
    if (parsedData && props.modalType !== 'create') {
      console.log('解析后的数据:', parsedData)
      // 将解析后的数据填充到表单中
      Object.keys(parsedData).forEach(key => {
        if (key in formData) {
          formData[key] = parsedData[key]
        }
      })
      // 确保formData.id是正确设置的
      if (!formData.id && parsedData.id) {
        formData.id = parsedData.id
      }
      return
    } else if (props.modalType === 'create') {
      // 创建模式下重置表单
      resetForm()
      return
    }
  } catch (error) {
    console.error('初始化表单数据失败:', error)
    message.error('体温单数据加载失败，将使用默认值')
  }
  // 如果没有数据或解析失败，使用默认值
  resetForm()
}

// 关闭弹窗
const closeModal = () => {
  // 关闭弹窗前清空表单数据
  resetForm()
  emit('update:visible', false)
  emit('cancel')
}

// 验证表单
const validateForm = () => {
  const errors = {}
  let hasError = false
  // 通用字段验证
  const requiredFields = [
    { key: 'id', label: 'ID' },
    { key: 'name', label: '姓名' },
    { key: 'inDate', label: '入院日期' },
    { key: 'dept', label: '科室' },
    { key: 'bed', label: '床位' },
    { key: 'medicalNo', label: '病历号' },
    { key: 'begin', label: '开始日期' },
    { key: 'notes', label: '备注' },
    { key: 'heart', label: '心率' },
    { key: 'tempType', label: '体温类型' },
    { key: 'temperature', label: '体温' },
    { key: 'breath', label: '呼吸' },
    { key: 'labels', label: '标签' },
    { key: 'data1', label: '血压' },
    { key: 'data2', label: '入水量' },
    { key: 'data3', label: '出水量' },
    { key: 'data4', label: '大便次数' },
    { key: 'data5', label: '小便次数' },
    { key: 'diag', label: '诊断' },
    { key: 'operateDate', label: '手术日期' },
    { key: 'sphygmus', label: '脉搏' },
    { key: 'data6', label: '身高' },
    { key: 'data7', label: '体重' },
    { key: 'data8', label: '过敏药' },
    { key: 'data9', label: '其他数据' }
  ]
  // 检查每个必填字段
  requiredFields.forEach(field => {
    // 首先检查字段是否存在
    if (formData[field.key] === undefined || formData[field.key] === null) {
      errors[field.key] = `${field.label}不能为空`
      hasError = true
      return
    }
    // 将值转换为字符串后再检查是否为空
    const value = String(formData[field.key])
    if (value.trim() === '') {
      errors[field.key] = `${field.label}不能为空`
      hasError = true
    }
  })

  formErrors.value = errors
  if (hasError) {
    message.error('表单验证失败，请填写所有必填项')
    return false
  }
  return true
}

// 获取表单数据
const getFormData = () => {
  const commonData = {
    id: formData.id || `VS${Date.now()}`,
    name: formData.name,
    inDate: formData.inDate,
    dept: formData.dept,
    bed: formData.bed,
    medicalNo: formData.medicalNo,
    begin: formData.begin,
    notes: formData.notes,
    heart: formData.heart,
    tempType: formData.tempType,
    temperature: formData.temperature,
    breath: formData.breath,
    labels: formData.labels,
    data1: formData.data1,
    data2: formData.data2,
    data3: formData.data3,
    data4: formData.data4,
    data5: formData.data5,
    data6: formData.data6,
    data7: formData.data7,
    data8: formData.data8,
    data9: formData.data9,
    pain: formData.pain,
    diag: formData.diag,
    operateDate: formData.operateDate,
    sphygmus: formData.sphygmus
  }
  return {
    ...commonData,
    type: 'normal'
  }
}

// 提交表单
async function submitForm () {
  if (!props.editorReady) {
    message.error('体温单编辑器未加载完成，请等待或刷新页面')
    return
  }
  // 首先验证表单
  if (!validateForm()) {
    return
  }
  submitLoading.value = true
  try {
    const data = getFormData()
    emit('submit', data)
    // 关闭弹窗
    closeModal()
  } catch (err) {
    console.error('提交体温单数据出错:', err)
    message.error(`提交体温单数据失败: ${err.message || '未知错误'}`)
  } finally {
    submitLoading.value = false
  }
}
</script>

<template>
  <a-modal
    :title="modalTitles[modalType]"
    :visible="visible"
    @cancel="closeModal"
    :width="700"
    :footer="null">
    <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <!-- 通用基础信息字段 -->
      <a-form-item label="ID" :validateStatus="formErrors.id ? 'error' : ''" :help="formErrors.id">
        <a-input v-model="formData.id" :placeholder="`请输入ID，如：AD20230001`" />
      </a-form-item>
      <a-form-item label="姓名" :validateStatus="formErrors.name ? 'error' : ''" :help="formErrors.name">
        <a-input v-model="formData.name" placeholder="请输入姓名，如：张三" />
      </a-form-item>
      <a-form-item label="入院日期" :validateStatus="formErrors.inDate ? 'error' : ''" :help="formErrors.inDate">
        <a-input v-model="formData.inDate" placeholder="请输入日期，如：2023-08-01" />
      </a-form-item>
      <a-form-item label="诊断" :validateStatus="formErrors.diag ? 'error' : ''" :help="formErrors.diag">
        <a-input v-model="formData.diag" placeholder="请输入诊断，如：新型冠状病毒肺炎" />
      </a-form-item>
      <!-- 通用字段 -->
      <a-form-item label="科室" :validateStatus="formErrors.dept ? 'error' : ''" :help="formErrors.dept">
        <a-input v-model="formData.dept" :placeholder="`请输入科室，如：呼吸内科`" />
      </a-form-item>
      <a-form-item label="床位" :validateStatus="formErrors.bed ? 'error' : ''" :help="formErrors.bed">
        <a-input v-model="formData.bed" placeholder="请输入床位，如：801" />
      </a-form-item>
      <a-form-item label="病历号" :validateStatus="formErrors.medicalNo ? 'error' : ''" :help="formErrors.medicalNo">
        <a-input v-model="formData.medicalNo" placeholder="请输入病历号，如：202300991" />
      </a-form-item>
      <a-form-item label="开始日期" :validateStatus="formErrors.begin ? 'error' : ''" :help="formErrors.begin">
        <a-input v-model="formData.begin" placeholder="请输入日期，如：2023-08-01" />
      </a-form-item>
      <a-form-item label="手术日期" :validateStatus="formErrors.operateDate ? 'error' : ''" :help="formErrors.operateDate">
        <a-input v-model="formData.operateDate" placeholder="请输入日期，如：2023-08-03" />
      </a-form-item>
      <!-- 备注字段 -->
      <a-form-item label="备注" :validateStatus="formErrors.notes ? 'error' : ''" :help="formErrors.notes">
        <a-input v-model="formData.notes" :placeholder="`请输入备注，如：${modalType === 'baby' ? '出生-十时二十分' : '入院-十时二十分,,转入ICU,,,,,,,手术'}`" />
        <div class="input-tip">格式：多个值用逗号分隔，对应不同日期</div>
      </a-form-item>
      <!-- 根据表单类型显示不同的数据字段 -->
      <a-form-item label="脉搏" :validateStatus="formErrors.sphygmus ? 'error' : ''" :help="formErrors.sphygmus">
        <a-input v-model="formData.sphygmus" placeholder="脉搏数据，如：112,110,109,103,108,85" />
        <div class="input-tip">格式：多个值用逗号分隔</div>
      </a-form-item>
      <!-- 生命体征数据字段 -->
      <a-form-item label="心率" :validateStatus="formErrors.heart ? 'error' : ''" :help="formErrors.heart">
        <a-input v-model="formData.heart" placeholder="心率数据，多个值用逗号分隔，如：112,120,118,111" />
        <div class="input-tip">格式：多个值用逗号分隔</div>
      </a-form-item>
      <a-form-item label="体温类型" :validateStatus="formErrors.tempType ? 'error' : ''" :help="formErrors.tempType">
        <a-input v-model="formData.tempType" placeholder="体温类型，如：0,1,2,3,0,1" />
        <div class="input-tip">格式：多个值用逗号分隔，0-3表示不同类型</div>
      </a-form-item>
      <a-form-item label="体温" :validateStatus="formErrors.temperature ? 'error' : ''" :help="formErrors.temperature">
        <a-input v-model="formData.temperature" :placeholder="`体温数据，如：38.7,38.9,38.5,39.1,38.5,38.5|37.1`" />
        <div class="input-tip">格式：多个值用逗号分隔<template v-if="modalType !== 'baby'">，|表示新一行数据</template></div>
      </a-form-item>
      <!-- 通用数据字段 -->
      <a-form-item label="呼吸" :validateStatus="formErrors.breath ? 'error' : ''" :help="formErrors.breath">
        <a-input v-model="formData.breath" placeholder="呼吸数据，如：30,30,R,,35,35" />
        <div class="input-tip">格式：多个值用逗号分隔，R表示异常</div>
      </a-form-item>
      <a-form-item label="标签" :validateStatus="formErrors.labels ? 'error' : ''" :help="formErrors.labels">
        <a-input v-model="formData.labels" :placeholder="`标签数据，如：血压(mmHg)|入水量(ml)|出水量(ml)|大便(次)|小便(次)${modalType === 'baby' ? '' : '|身高(cm)|体重(kg)|过敏药'}`" />
        <div class="input-tip">格式：多个标签用|分隔</div>
      </a-form-item>
      <!-- 通用数据字段 -->
      <a-form-item label="血压" :validateStatus="formErrors.data1 ? 'error' : ''" :help="formErrors.data1">
        <a-input v-model="formData.data1" placeholder="血压数据，如：120/85,121/84,,110/75" />
        <div class="input-tip">格式：多个值用逗号分隔</div>
      </a-form-item>
      <a-form-item label="入水量" :validateStatus="formErrors.data2 ? 'error' : ''" :help="formErrors.data2">
        <a-input v-model="formData.data2" placeholder="入水量数据，如：1180ml,,,500ml,,40ml" />
        <div class="input-tip">格式：多个值用逗号分隔</div>
      </a-form-item>
      <a-form-item label="出水量" :validateStatus="formErrors.data3 ? 'error' : ''" :help="formErrors.data3">
        <a-input v-model="formData.data3" placeholder="出水量数据，如：500ml,,,,500ml,,67ml" />
        <div class="input-tip">格式：多个值用逗号分隔</div>
      </a-form-item>
      <a-form-item label="大便次数" :validateStatus="formErrors.data4 ? 'error' : ''" :help="formErrors.data4">
        <a-input v-model="formData.data4" placeholder="大便次数数据，如：2,4,5,3,3,3,2,,2" />
        <div class="input-tip">格式：多个值用逗号分隔</div>
      </a-form-item>
      <a-form-item label="小便次数" :validateStatus="formErrors.data5 ? 'error' : ''" :help="formErrors.data5">
        <a-input v-model="formData.data5" placeholder="小便次数数据，如：2,4,5,3,3,3,2,,2" />
        <div class="input-tip">格式：多个值用逗号分隔</div>
      </a-form-item>
      <a-form-item label="身高" :validateStatus="formErrors.data6 ? 'error' : ''" :help="formErrors.data6">
        <a-input v-model="formData.data6" placeholder="身高数据，如：167cm,,,,,,,,,164cm" />
        <div class="input-tip">格式：多个值用逗号分隔</div>
      </a-form-item>
      <a-form-item label="体重" :validateStatus="formErrors.data7 ? 'error' : ''" :help="formErrors.data7">
        <a-input v-model="formData.data7" placeholder="体重数据，如：95kg,,,,,90kg" />
        <div class="input-tip">格式：多个值用逗号分隔</div>
      </a-form-item>
      <a-form-item label="过敏药" :validateStatus="formErrors.data8 ? 'error' : ''" :help="formErrors.data8">
        <a-input v-model="formData.data8" placeholder="过敏药数据，如：青霉素," />
        <div class="input-tip">格式：多个值用逗号分隔</div>
      </a-form-item>
      <a-form-item label="其他数据" :validateStatus="formErrors.data9 ? 'error' : ''" :help="formErrors.data9">
        <a-input v-model="formData.data9" placeholder="其他数据，如：测试," />
        <div class="input-tip">格式：多个值用逗号分隔</div>
      </a-form-item>
      <!-- 按钮 -->
      <a-form-item :wrapper-col="{ span: 18, offset: 6 }">
        <a-button type="primary" @click="submitForm" :loading="submitLoading" style="margin-right: 10px">确定</a-button>
        <a-button @click="closeModal">取消</a-button>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped>
.input-tip {
  color: #999;
  font-size: 12px;
  margin-top: 4px;
}
</style>
