<template>
  <el-dialog
    v-model="visible"
    top="6vh"
    :width="width"
    title="入科选床"
    @open="openAct"
    @closed="closedAct"
    :z-index="20"
    destroy-on-close
  >
    <div class="transferIn-container">
      <el-form :model="interventionForm" :rules="rules" ref="interventionFormRef">
        <div class="admission-information">
          <el-row>
            <el-col :span="24">
              <div class="patient-info">
                <div style="display: flex;align-items: center;margin-bottom: 16px;">
                  <div style="margin-right: 36px;font-size: 18px;font-weight: 700;">{{ props.pendingInfo.houseName + '-' + props.pendingInfo.bedName }}</div>
                  <div style="border-radius: 50px;border: 2px solid slategray;padding: 4px 12px;">{{ props.pendingInfo.contractName }}</div>
                </div>
                <div>
                  <el-row>
                    <el-col :span="12">
                      <div style="margin-bottom: 12px;">
                        {{ props.pendingInfo.patientName}}
                        <span style="color: #9f9f9f;">{{ props.pendingInfo.genderEnum_enumText}}/</span>
                        <span style="color: #9f9f9f;">{{ props.pendingInfo.age}}</span>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div>
                        电话：{{ pendingInfo.phone }}
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div>
                        住院诊断：{{ pendingInfo.conditionNames }}
                      </div>
                    </el-col>
                    <el-col :span="12">{{ props.pendingInfo.patientId }}</el-col>
                  </el-row>
                  
                  
                </div>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="info-title">
                入院体征
              </div>
            </el-col>
            <el-col :span="8">
              <el-form-item label="身高" label-width="50px">
                <el-input-number :controls="false" style="width: 160px" clearable v-model="interventionForm.height" placeholder="请输入" :min="0"
                  :max="999"></el-input-number><span class="unit">cm</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="体重" label-width="50px">
                <el-input-number :controls="false" style="width: 160px" v-model="interventionForm.weight" clearable placeholder="请输入" :min="0"
                  :max="999"></el-input-number>
                <span class="unit">kg</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="体温" label-width="50px">
                <el-input-number :controls="false" style="width: 160px" v-model="interventionForm.temperature" clearable placeholder="请输入"
                  :min="0" :max="99"></el-input-number>
                <span class="unit">℃</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="心率" label-width="50px">
                <el-input-number :controls="false" style="width: 160px" v-model="interventionForm.hertRate" clearable placeholder="请输入" :min="0"
                  :max="999"></el-input-number>
                <span class="unit">BPM</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="脉搏" label-width="50px">
                <el-input-number :controls="false" style="width: 160px" v-model="interventionForm.pulse" clearable placeholder="请输入" :min="0"
                  :max="999"></el-input-number><span class="unit">P</span>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="血压" label-width="50px">
                <el-input-number :controls="false" style="width: 72px" v-model="interventionForm.endBloodPressure" clearable placeholder="请输入"
                  :min="0" :max="999"></el-input-number>
                <span style="display: inline-block; width: 8px; margin: 0 4px"> ~ </span>

                <el-input-number :controls="false" style="width: 72px" v-model="interventionForm.highBloodPressure" clearable placeholder="请输入"
                  :min="0" :max="999"></el-input-number>
                <span class="unit">mmHg</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="info-title">
                入院信息
              </div>
            </el-col>
            <el-col :span="8">
              <el-form-item label="入院科室" label-width="100px">
                <el-input
                  class="w-p100"
                  clearable
                  disabled
                  v-model="interventionForm.organizationName"
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="入院病区" label-width="100px">
                <el-input
                  class="w-p100"
                  v-model="interventionForm.wardName"
                  disabled
                  clearable
                  placeholder="请输入"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="入住床位" label-width="100px">
                <el-input
                  class="w-p100"
                  v-model="interventionForm.bedName"
                  disabled
                  clearable
                  placeholder="请输入"
                ></el-input>
                <!-- <el-select v-model="interventionForm.bedLocationId" placeholder="请选择入住床位" style="width: 100%">
                  <el-option
                    v-for="item in bedInfoOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select> -->
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="住院医生" label-width="100px" prop="admittingDoctorId">
                <el-select
                  v-model="interventionForm.admittingDoctorId"
                  placeholder="请选择住院医生"
                  style="width: 240px"
                  :disabled="props.pendingInfo.encounterStatus == 5 && props.pendingInfo.entranceType == 2"
                >
                  <el-option
                    v-for="item in doctorInfoOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="主治医生" label-width="100px">
                <el-select
                  v-model="interventionForm.attendingDoctorId"
                  placeholder="请选择主治医生"
                  style="width: 240px"
                  :disabled="props.pendingInfo.encounterStatus == 5 && props.pendingInfo.entranceType == 2"
                >
                  <el-option
                    v-for="item in doctorInfoOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="主任医生" label-width="100px">
                <el-select
                  v-model="interventionForm.chiefDoctorId"
                  placeholder="请选择主任医生"
                  style="width: 240px"
                  :disabled="props.pendingInfo.encounterStatus == 5 && props.pendingInfo.entranceType == 2"
                >
                  <el-option
                    v-for="item in doctorInfoOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="入科时间" label-width="100px">
                <el-date-picker
                  class="w-p100"
                  v-model="interventionForm.startTime"
                  type="datetime"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  placeholder="请输入"
                  :disabled="props.pendingInfo.encounterStatus == 5"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="责任护士" label-width="100px" prop="primaryNurseId">
                <el-select
                  v-model="interventionForm.primaryNurseId"
                  placeholder="请选择责任护士"
                  style="width: 240px"
                  :disabled="props.pendingInfo.encounterStatus == 5 && props.pendingInfo.entranceType == 2"
                >
                  <el-option
                    v-for="item in nurseInfoOptions"
                    :key="item.practitionerId"
                    :label="item.name"
                    :value="item.practitionerId"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="患者病情" label-width="100px">
                <el-select
                  v-model="interventionForm.priorityEnum"
                  placeholder="请选择患者病情"
                  style="width: 240px"
                  :disabled="props.pendingInfo.encounterStatus == 5 && props.pendingInfo.entranceType == 2"
                >
                  <el-option
                    v-for="item in props.priorityOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </el-form>
    </div>
    <template #footer>
      <!-- <div class="transferInDialog-footer"> -->
      <div class="isPrintWristband">
        <el-checkbox v-model="printWristband">打印腕带</el-checkbox>
      </div>
      <el-button class="margin-left-auto" @click="cancelAct">取消 </el-button>
      <el-button type="primary" @click="handleSubmit">入科</el-button>
      <!-- </div> -->
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import { reactive, ref, onMounted, inject, type Ref, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { dayjs, ElMessage } from 'element-plus'
// import type { IInPatient } from '@/model/IInPatient'
import { getBedInfo, getDoctorInfo, getNurseInfo, getInit, bedAssignment, getPatientInfo } from './api'

const props = defineProps({
  pendingInfo: {
    type: Object,
    require: true,
    default: () => ({})
  },
  priorityOptions: {
    type: Object,
    require: true,
    default: () => ({})
  },
})

const currentInPatient = ref<Partial<IInPatient>>({})
const bedInfoOptions = ref<{ label: string; value: string }[]>([])
const doctorInfoOptions = ref<{ name: string; id: string }[]>([])
const nurseInfoOptions = ref<{ name: string; practitionerId: string }[]>([])
const InitInfoOptions = ref<any>({})
const priorityListOptions = ref<{ info: string; value: string }[]>([])
const pendingInfo = ref<any>({})

const initCurrentInPatient = () => {
  currentInPatient.value = {
    feeType: '08',
    sexName: '男',
    age: '0',
  }
}

/* 入科 */
const interventionForm = ref({
  height: undefined,
  weight: undefined,
  temperature: undefined,
  hertRate: undefined,
  pulse: undefined,
  endBloodPressure: undefined,
  highBloodPressure: undefined,
  bedLocationId: '', // 床号
  admittingDoctorId: '', // 住院医师
  attendingDoctorId: '', // 主治医师
  chiefDoctorId: '', // 主任医师
  primaryNurseId: '', // 责任护士
  priorityEnum: '', //患者病情
  organizationName: '',
  wardName: '',
  bedName: '',
  attendingDocUpdateId: '',
  startTime: '', //入院时间
})

watch(() => props.pendingInfo, (newVal, oldVal) => {
  console.log(newVal)
  if(newVal) {
    getPatientInfo({encounterId: newVal.encounterId}).then(res => {
      pendingInfo.value = res.data
      interventionForm.value.admittingDoctorId = res.data.admittingDoctorId
      interventionForm.value.attendingDoctorId = res.data.attendingDoctorId
      interventionForm.value.chiefDoctorId = res.data.chiefDoctorId
      interventionForm.value.primaryNurseId = res.data.primaryNurseId
      if(res.data.startTime) {
        interventionForm.value.startTime = dayjs(res.data.startTime).format('YYYY-MM-DD HH:mm:ss')
      }else {
        interventionForm.value.startTime = dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')
      }
    })
    interventionForm.value.priorityEnum = newVal.priorityEnum
    interventionForm.value.organizationName = newVal.organizationName
    interventionForm.value.wardName = newVal.wardName
    interventionForm.value.bedName = newVal.bedName
  }
},{ deep: true })

/* 初始化数据 */
const init = () => {
  initCurrentInPatient()
  getInit().then(res => {
    InitInfoOptions.value = res.data
    // 安全地设置priorityListOptions
    if (res.data && res.data.priorityListOptions) {
      priorityListOptions.value = res.data.priorityListOptions
    }
  }).catch(error => {
    console.error('获取初始化数据失败:', error)
  })
  
  if (props.pendingInfo.wardLocationId) {
    getBedInfo({wardLocationId: props.pendingInfo.wardLocationId}).then(res => {
      bedInfoOptions.value = res.data || []
    }).catch(error => {
      console.error('获取床位信息失败:', error)
      bedInfoOptions.value = []
    })
  }
  
  if (props.pendingInfo.organizationId) {
    getDoctorInfo({organizationId: props.pendingInfo.organizationId}).then(res => {
      doctorInfoOptions.value = res.data.records || []
    }).catch(error => {
      console.error('获取医生信息失败:', error)
      doctorInfoOptions.value = []
    })
    
    getNurseInfo({organizationId: props.pendingInfo.organizationId}).then(res => {
      nurseInfoOptions.value = res.data || []
    }).catch(error => {
      console.error('获取护士信息失败:', error)
      nurseInfoOptions.value = []
    })
  }
}

const rules = reactive<FormRules>({
  admittingDoctorId: [{ required: true, message: '请选择住院医生', trigger: ['blur', 'change'] }],
  primaryNurseId: [{ required: true, message: '请选择责任护士', trigger: ['blur', 'change'] }],
  bedLocationId: [{ required: true, message: '请选择入住床位', trigger: ['blur', 'change'] }],
})

const printWristband = ref(false)
const emits = defineEmits(['okAct'])
const visible = defineModel('visible')
const width = '950px'

/* 取消 */
const cancelAct = () => {
  resetForm()
  visible.value = false
}

const resetForm = () => {
  // interventionForm.value = {
  //   height: undefined,
  //   weight: undefined,
  //   temperature: undefined,
  //   hertRate: undefined,
  //   pulse: undefined,
  //   endBloodPressure: undefined,
  //   highBloodPressure: undefined,
  //   bedLocationId: '', // 床号
  //   admittingDoctorId: '', // 住院医师
  //   attendingDoctorId: '', // 主治医师
  //   chiefDoctorId: '', // 主任医师
  //   primaryNurseId: '', // 责任护士
  //   priorityEnum: '', //患者病情
  //   organizationName: '',
  //   wardName: '',
  //   attendingDocUpdateId: '',
  //   startTime: '', //入院时间
  // }

  // 可选：清空校验状态
  if (interventionFormRef.value) {
    interventionFormRef.value.resetFields()
  }
}

/* 入科 */
const interventionFormRef = ref<FormInstance | null>(null)
const handleSubmit = async () => {
  // TODO 登记入科
  if (!interventionFormRef.value) {
    console.error('表单引用不存在')
    return
  }
  try {
    const valid = await interventionFormRef.value.validate()
    if (valid) {
      const params = { 
        ...pendingInfo.value,
        ...interventionForm.value,
        targetBedId: props.pendingInfo.bedId,
        busNo: props.pendingInfo.busNo,
        inHosTime: props.pendingInfo.inHosTime,
        targetHouseId : props.pendingInfo.targetHouseId,
        targetEncounterId: props.pendingInfo.targetEncounterId,
        editFlag: props.pendingInfo.entranceType == 1 ? 1 : 0
      }
      
      bedAssignment(params).then((res: any) => {
        ElMessage({
          message: '登记成功！',
          type: 'success',
          grouping: true,
          showClose: true,
        })
        resetForm()
        emits('okAct')
        visible.value = false // 关闭对话框
      }).catch((error: any) => {
        console.error('登记失败:', error)
        ElMessage({
          message: '登记失败！',
          type: 'error',
          grouping: true,
          showClose: true,
        })
      })
    }
  } catch (error) {
    console.log('表单验证失败:', error)
  }
}

const openAct = () => {
  init()
  if (props.pendingInfo) {
    interventionForm.value.priorityEnum = props.pendingInfo.priorityEnum || ''
    interventionForm.value.admittingDoctorId = props.pendingInfo.practitionerId || ''
    interventionForm.value.organizationName = props.pendingInfo.organizationName || ''
    interventionForm.value.wardName = props.pendingInfo.wardName || ''
    interventionForm.value.attendingDocUpdateId = props.pendingInfo.admittingDoctorId || ''
  }
}

const closedAct = () => {
  resetForm()
  visible.value = false
}

onMounted(() => {})
</script>
<style lang="scss" scoped>
.transferIn-container {
  width: 100%;

  .admission-information {
    width: 896px;
    .unit {
      display: inline-block;
      margin-left: 10px;
      color: #bbb;
      font-weight: 400;
      font-size: 14px;
      font-family: '思源黑体 CN';
    }
  }
  .beds {
    margin-bottom: 8px;
  }
}

.patient-info {
  padding: 16px;
  margin: 10px;
  border-radius: 4px;
  box-shadow: 0 2px 2px 0 rgba(58, 69, 86, 0.2);
  position: relative;
  transition: all 0.2s ease;
}

.isPrintWristband {
  float: left;
  display: inline-block;
}
.w-p100 {
  width: 100%;
}

.w-80 {
  width: 80px;
}

.info-title {
  background: #f6f7f9;
  color: #4f6877;
  padding: 5px 10px;
  margin-bottom: 16px;
}
</style>