<template>
  <el-dialog
    title="住院登记"
    v-model="props.open"
    width="1000px"
    append-to-body
    destroy-on-close
    @close="close"
    @open="openDialog"
  >
    <div class="operate">
      <div>患者信息</div>
    </div>
    <el-row>
      <el-col :span="2" class="descriptions-item-label">
        <el-text truncated>患者姓名：</el-text>
      </el-col>
      <el-col :span="3" class="patInfo-value">
        <el-text truncated>{{ patientInfo.patientName }}</el-text>
      </el-col>
      <el-col :span="2" class="descriptions-item-label">
        <el-text truncated>年龄：</el-text>
      </el-col>
      <el-col :span="3" class="patInfo-value">
        <el-text truncated>{{ patientInfo.age }}</el-text>
      </el-col>
      <el-col :span="2" class="descriptions-item-label">
        <el-text truncated>性别：</el-text>
      </el-col>
      <el-col :span="3" class="patInfo-value">
        <el-text truncated>{{ patientInfo.genderEnum_enumText }}</el-text>
      </el-col>
      <el-col :span="2" class="descriptions-item-label">
        <el-text truncated>费用性质：</el-text>
      </el-col>
      <el-col :span="3" class="patInfo-value">
        <el-text truncated>{{ patientInfo.contractName }}</el-text>
      </el-col>
    </el-row>
    <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="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 v-model="submitForm.wardLocationId">
              <el-option
                v-for="item in wardListOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
              <template #empty>
                <div>请先选择入院科室</div>
              </template>
            </el-select>
          </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 priorityLevelOptionOptions"
                :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="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-row>
      <el-row :gutter="8">
        <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="12">
          <el-form-item label="入院诊断" prop="diagnosisDefinitionId">
            <el-select
              v-model="submitForm.diagnosisDefinitionId"
              placeholder="诊断"
              clearable
              filterable
              remote
              :remote-method="getDiagnosisInfo"
              style="width: 400px"
            >
              <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-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">确 定</el-button>
        <el-button @click="close">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
  
<script setup>
import {
  getInit,
  getOrgList,
  wardList,
  getDiagnosisDefinitionList,
  handleHospitalization,
} from './api.js';

const submitForm = reactive({
  medTypeCode: '21',
});

const props = defineProps({
  open: {
    type: Boolean,
    default: false,
  },
  patientInfo: {
    type: Object,
    default: () => ({}),
  },
  encounterId: {
    type: String,
    default: '',
  },
});
const emit = defineEmits(['close']);

const priorityLevelOptionOptions = ref(undefined);
const organization = ref([]);
const wardListOptions = ref([]);
const diagnosisDefinitionList = ref([]);
let diagnosisDefinitionId = '';
let diagnosisYbNo = '';

const { proxy } = getCurrentInstance();

const { med_type } = proxy.useDict('med_type');
const rules = reactive({
  diagnosisDefinitionId: [
    {
      required: true,
      message: '入院诊断未填写',
      trigger: ['blur', 'change'],
    },
  ],
  medTypeCode: [
    {
      required: true,
      message: '诊断类别未选择',
      trigger: ['blur', 'change'],
    },
  ],
  inHospitalOrgId: [
    {
      required: true,
      message: '入院科室未填写',
      trigger: ['blur', 'change'],
    },
  ],
});

function openDialog() {
  getOrgList().then((res) => {
    organization.value = res.data.records;
  });
  // wardList().then((res) => {
  //   wardListOptions.value = res.data;
  // });
  getInit().then((response) => {
    console.log(response, 'response');
    priorityLevelOptionOptions.value = response.data.priorityLevelOptionOptions; // 优先级
  });
  console.log(props.patientInfo, 'patientInfo');
  getDiagnosisInfo(undefined);
}

function getDiagnosisInfo(value) {
  getDiagnosisDefinitionList({ pageSize: 500, pageNo: 1, searchKey: value }).then((res) => {
    diagnosisDefinitionList.value = res.data.records;
  });
}

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

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

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

function submit() {
  proxy.$refs['registerRef'].validate((valid) => {
    if (valid) {
      let saveData = {
        ...submitForm,
        diagnosisYbNo: diagnosisYbNo,
        diagnosisDefinitionId: diagnosisDefinitionId,
        // 优先使用props.encounterId，确保就诊ID正确传递
        ambEncounterId: props.encounterId || props.patientInfo.encounterId,
        patientId: props.patientInfo.patientId,
      };
      console.log('提交住院数据:', saveData);
      handleHospitalization(saveData).then((res) => {
        if (res.code == 200) {
          proxy.$modal.msgSuccess('办理成功');
          close();
        } else {
          console.error('办理失败:', res.msg);
          proxy.$modal.msgError(res.msg || '办理失败，请检查数据后重试');
        }
      }).catch(error => {
        console.error('提交出错:', error);
        proxy.$modal.msgError('提交请求失败');
      });
    }
  });
}

function close() {
  emit('close');
}
</script>

<style lang="scss" scoped>
.operate {
  font-size: 16px;
  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: 10px 0;
}

.patInfo-value {
  width: 100px;
}
</style>