<template>
  <div class="registerForm-container">
    <div class="operate">
      <div>住院信息</div>
    </div>
    <el-form
      class="register-from"
      :model="submitForm"
      style="padding-left: 8px"
      ref="registerRef"
      label-width="80px"
      :rules="rules"
    >
      <el-row :gutter="8">
        <el-col :span="6">
          <el-form-item label="住院号:" prop="encounterBusNo">
            {{ submitForm.busNo ? submitForm.busNo : '-' }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="住院次数:" prop="hospitalizationCount" autocomplete="off">
            {{ submitForm.inHospitalCount }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入院科室" prop="inHospitalOrgId">
            <el-tree-select
              clearable
              style="width: 100%"
              v-model="submitForm.inHospitalOrgId"
              filterable
              :data="organization"
              :props="{
                value: 'id',
                label: 'name',
                children: 'children',
              }"
              value-key="id"
              check-strictly
              :check-strictly-except-leaf="false"
              :default-expand-all="true"
              placeholder="请选择入院科室"
              @change="handleChange"
              @node-click="handleNodeClick"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入院病区" prop="wardLocationId">
            <el-select :disabled="props.alreadyEdit" v-model="submitForm.wardLocationId">
              <el-option
                v-for="item in wardListOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click="handleWardClick(item)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="床位数:" prop="bedCount">
            {{
              submitForm.totalBedsNum ? submitForm.idleBedsNum + '/' + submitForm.totalBedsNum : '-'
            }}
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="门诊医生" prop="ambDoctorPractitionerName">
            <el-input disabled v-model="submitForm.ambDoctorPractitionerName" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="诊断类别" prop="medTypeCode">
            <el-select
              v-model="submitForm.medTypeCode"
              placeholder="诊断类别"
              clearable
              filterable
              @change="
                (value) => {
                  submitForm.ybClassEnum = value;
                }
              "
            >
              <el-option
                v-for="item in med_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="!props.noFile">
          <el-form-item label="入院诊断" prop="ambDiagnosisName">
            <el-input v-model="submitForm.ambDiagnosisName" disabled />
          </el-form-item>
        </el-col>
        <el-col :span="6" v-else>
          <el-form-item label="入院诊断" prop="diagnosisDefinitionId">
            <el-select
              v-model="submitForm.diagnosisDefinitionId"
              placeholder="入院诊断"
              clearable
              filterable
              remote
              :remote-method="getDiagnosisInfo"
            >
              <el-option
                v-for="item in diagnosisDefinitionList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click="handleDiagnosisChange(item)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="props.noFile">
          <el-form-item label="诊断描述" prop="diagnosisDesc">
            <el-input v-model="submitForm.diagnosisDesc" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="患者病情">
            <el-select v-model="submitForm.priorityEnum">
              <el-option
                v-for="item in props.initOptions.priorityEnumList"
                :key="item.value"
                :label="item.info"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入院类型" prop="admitSourceCode">
            <el-select v-model="submitForm.admitSourceCode">
              <el-option
                v-for="item in admit_source_code"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入院方式" prop="inWayCode">
            <el-select v-model="submitForm.inWayCode">
              <el-option
                v-for="item in in_way_code"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="费用性质">
            <el-select
              v-model="submitForm.contractNo"
              placeholder="费用性质"
              clearable
              @change="getValue"
            >
              <el-option
                v-for="item in contractList"
                :key="item.busNo"
                :label="item.contractName"
                :value="item.busNo"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="入院日期" prop="startTime">
            <el-date-picker
              v-model="submitForm.startTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="date"
              placeholder="请选择日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script setup>
import {
  getInit,
  getOrgList,
  wardList,
  diagnosisInit,
  getBedInfo,
  getContractList,
  getDiagnosisDefinitionList,
} from './api';
const { proxy } = getCurrentInstance();
const { in_way_code, admit_source_code, med_type } = proxy.useDict(
  'in_way_code',
  'admit_source_code',
  'med_type'
);

import { formatDateStr } from '@/utils';
const emits = defineEmits([]);
const props = defineProps({
  patientInfo: {
    type: Object,
    require: true,
    default: () => ({}),
  },
  inHospitalInfo: {
    type: Object,
    require: true,
    default: () => ({}),
  },
  initOptions: {
    type: Object,
    require: true,
    default: () => ({}),
  },
  alreadyEdit: {
    type: Boolean,
    default: false,
  },
  noFile: {
    type: Boolean,
    default: false,
  },
});

const organization = ref([]);
const wardListOptions = ref([]);
const contractList = ref([]);
const verificationStatusOptions = ref([]);
const diagnosisDefinitionList = ref([]);
const rules = reactive({
  inHospitalOrgId: [
    {
      required: true,
      message: '入院科室未填写',
      trigger: ['blur', 'change'],
    },
  ],
  wardLocationId: [
    {
      required: true,
      message: '入院病区未填写',
      trigger: ['blur', 'change'],
    },
  ],
  startTime: [
    {
      required: true,
      message: '入院日期未填写',
      trigger: ['blur', 'change'],
    },
  ],
  diagnosisDefinitionId: [
    {
      required: true,
      message: '入院诊断未填写',
      trigger: ['blur', 'change'],
    },
  ],
  diagnosisDesc: [
    {
      required: true,
      message: '诊断描述未填写',
      trigger: ['blur', 'change'],
    },
  ],
});

/* 提交表单 */
const submitForm = reactive({
  inHospitalOrgId: props.inHospitalInfo.inHospitalOrgId,
  ambDoctorPractitionerName: props.inHospitalInfo.ambDoctorPractitionerName,
  wardLocationId: props.inHospitalInfo.wardLocationId, // 入院护理组编码
  admitSourceCode: '', // 患者入院类型（字典：PatientSource）
  inWayCode: '', // 入院方式（字典InpWay）
  startTime: formatDateStr(new Date(), 'YYYY-MM-DD HH:mm:ss'), // 	入院日期
  priorityEnum: props.inHospitalInfo.priorityEnum, // 患者病情（字典：PatAdmCondition）
  ambDiagnosisName: props.inHospitalInfo.ambDiagnosisName,
  medTypeCode: '21',
});
/* 科室 病区 */
watch(
  () => submitForm.inDocterWorkGroupCode,
  (newValue) => {
    if (newValue) {
      if (newValue == '') {
        submitForm.wardLocationId = '';
      }
    } else {
      submitForm.wardLocationId = '';
    }
  }
);

watch(
  () => submitForm.inNurseDeptCode,
  (newValue) => {
    if (newValue) {
      getBedInfo(newValue);
    }
  }
);

onMounted(() => {
  getInitOptions();
  setValue();
});

function handleWardClick(item) {
  submitForm.wardBusNo = item.busNo;
  getBedInfo(submitForm.wardBusNo).then((res) => {
    submitForm.totalBedsNum = res.data.totalBedsNum;
    submitForm.idleBedsNum = res.data.idleBedsNum;
  });
}

function getInitOptions() {
  getOrgList().then((res) => {
    organization.value = res.data.records;
  });
  if (!props.noFile) {
    wardList().then((res) => {
      wardListOptions.value = res.data;
    });
  }
  diagnosisInit().then((res) => {
    verificationStatusOptions.value = res.data.verificationStatusOptions;
  });
  getContractList().then((response) => {
    contractList.value = response.data;
    setValue();
  });
  getDiagnosisInfo(undefined);
}
function getDiagnosisInfo(value) {
  getDiagnosisDefinitionList({ pageSize: 500, pageNo: 1, searchKey: value }).then((res) => {
    diagnosisDefinitionList.value = res.data.records;
  });
}

function handleNodeClick(orgInfo) {
  wardList({ orgId: orgInfo.id }).then((res) => {
    wardListOptions.value = res.data;
  });
}

function handleChange(value) {
  if (!value) {
    wardListOptions.value = [];
    submitForm.wardLocationId = undefined;
  }
}

function handleDiagnosisChange(item) {
  submitForm.diagnosisYbNo = item.ybNo;
  submitForm.diagnosisDefinitionId = item.id;
}

function setValue() {
  submitForm.encounterId = props.inHospitalInfo?.encounterId;
  submitForm.busNo = props.inHospitalInfo?.busNo;
  submitForm.contractNo = props.inHospitalInfo?.contractNo;
  submitForm.inHospitalCount = props.inHospitalInfo?.inHospitalCount;
  submitForm.inHospitalOrgId = props.inHospitalInfo?.inHospitalOrgId;
  submitForm.inHospitalOrgName = props.inHospitalInfo?.inHospitalOrgName;
  submitForm.wardLocationId = props.inHospitalInfo?.wardLocationId;
  submitForm.wardName = props.inHospitalInfo?.wardName;
  submitForm.wardBusNo = props.inHospitalInfo?.wardBusNo;
  submitForm.totalBedsNum = props.inHospitalInfo?.totalBedsNum;
  submitForm.idleBedsNum = props.inHospitalInfo?.idleBedsNum;
  submitForm.ambEncounterId = props.inHospitalInfo?.ambEncounterId;
  submitForm.ambDoctorPractitionerId = props.inHospitalInfo?.ambDoctorPractitionerId;
  submitForm.ambDoctorPractitionerName = props.inHospitalInfo?.ambDoctorPractitionerName;
  submitForm.ambDiagnosisName = props.inHospitalInfo?.ambDiagnosisName;
  submitForm.priorityEnum = props.inHospitalInfo?.priorityEnum;
  submitForm.priorityEnum_enumText = props.inHospitalInfo?.priorityEnum_enumText;
  submitForm.admitSourceCode = props.inHospitalInfo?.admitSourceCode;
  submitForm.admitSourceCode_dictText = props.inHospitalInfo?.admitSourceCode_dictText;
  submitForm.inWayCode = props.inHospitalInfo?.inWayCode;
  submitForm.inWayCode_dictText = props.inHospitalInfo?.inWayCode_dictText;
}

const registerRef = ref();
/* 登记 */
const validateData = async (callback) => {
  if (!registerRef.value) return false;
  registerRef.value.validate((valid) => {
    if (valid) {
      callback();
      return true;
    } else {
      return false;
    }
  });
};

const init = () => {
  submitForm.inDocterWorkGroupCode = '';
  submitForm.wardLocationId = '';
};
defineExpose({ validateData, submitForm, init });
</script>
<style lang="scss" scoped>
.registerForm-container {
  margin-top: 16px;

  .operate {
    background: rgba(37, 109, 149, 0.05);
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 32px;
    border-radius: 4px 4px 0px 0px;
    padding-left: 16px;
    color: var(--hip-color-primary-light);
    font-weight: bold;
    margin-bottom: 8px;
  }

  .register-from {
    padding: 0 8px;
  }

  :deep(.el-form-item) {
    width: 100%;
    margin-right: 0px;
  }
}
</style>
