<template>
  <el-dialog
    v-model="dialogVisible"
    top="6vh"
    :width="width"
    :title="props.title"
    @open="openAct"
    @closed="closedAct"
    :z-index="20"
    destroy-on-close
  >
    <el-scrollbar height="650px">
      <PatientInfoComp
        :patientInfo="props.patientInfo"
        :registrationType="props.registrationType"
        :initOptions="initOptions"
        :noFile="noFile"
        ref="patientInfoRef"
        @onChangFeeType="onChangFeeType"
      />
      <!-- <PatientRelationList
        class="relationList"
        :patCode="patientInfo.code"
        ref="PatientRelationListRef"
      /> -->
      <!--联系人组件  -->
      <RegisterForm
        :code="code"
        ref="RegisterFormRef"
        :patientInfo="patientApiInfo"
        :initOptions="initOptions"
        :alreadyEdit="alreadyEdit"
        :inHospitalInfo="inHospitalInfo"
        :noFile="noFile"
      />
    </el-scrollbar>
    <template v-slot:footer>
      <div class="advance-container">
        <el-space>
          <div>缴费预交金</div>
          <el-input
            style="width: 142px"
            placeholder="请输入"
            v-model="advance"
            @input="handleAdvanceInput"
            :formatter="handleAdvanceFormatter"
            :parser="handleAdvanceParser"
          ></el-input>
          <div
            class="feeType"
            :class="currentFeeType == typeitem.type ? 'activeFeeType' : ''"
            v-for="typeitem in feeTypeOptions"
            :key="typeitem.type"
            @click="currentFeeType = typeitem.type"
          >
            <svg-icon
              :icon-class="typeitem.type"
              :color="currentFeeType == typeitem.type ? '#13C0B3' : '#666666'"
              height="18px"
              width="18px"
              style="margin-right: 4px"
            />
            {{ typeitem.label }}
          </div>
        </el-space>
      </div>
      <el-button size="fixed" class="margin-left-auto" @click="cancelAct">取消 </el-button>
      <el-button size="fixed" type="primary" @click="handleSubmit">登记</el-button>
      <!-- <hip-button size="fixed" type="primary" @click="supplementMi">医保登记</hip-button> -->
      <!-- <AdvancePayment
        v-model="advancePaymentVisible"
        @submitOk="advancePaymentSubmitOk"
        :money="advance"3
      /> -->
    </template>
  </el-dialog>
</template>
<script setup>
const { proxy } = getCurrentInstance();
import { ElMessageBox } from 'element-plus';
import PatientInfoComp from './patientInfo.vue';
import RegisterForm from './registerForm.vue';
import { noFilesRegister, registerInHospital, getInit } from './api';
const emits = defineEmits(['okAct', 'cancelAct']);

const props = defineProps({
  title: '',
  registrationType: {
    type: [String, Boolean, Number], // 根据实际类型调整
    default: null, // 或者 false、'' 等
  },
  patientInfo: {
    type: Object,
  },
  inHospitalInfo: {
    type: Object,
  },
  alreadyEdit: {
    type: Boolean,
    default: false,
  },
  noFile: {
    type: Boolean,
    default: false,
  },
});

watch(
  () => props.registrationType,
  (newValue) => {
    console.log('registrationType changed:', newValue);
  },
  { immediate: true }
);

const dialogVisible = defineModel('dialogVisible', {
  type: Boolean,
  default: false,
});
const code = defineModel('code');
import { ElMessage } from 'element-plus';
const width = '1128px';
const patientApiInfo = ref({});
const initOptions = ref({});

/* 取消 */
const cancelAct = () => {
  emits('cancelAct');
};
const patientInfoRef = ref();

/* 预交金 */
const advancePaymentVisible = ref(false);
/* 保存 */
const handleSubmit = () => {
  let params = {};
  if (props.noFile) {
    RegisterFormRef.value.validateData(async () => {
      params.inHospitalInfo = RegisterFormRef.value.submitForm;
      params.patientInformation = patientInfoRef.value.getPatientForm();
      if (params.patientInformation.idCard) {
        // 验证身份证号长度是否为18位
        const idCard = params.patientInformation.idCard.toString();
        if (idCard.length === 18) {
          params.patientInformation.birthDate =
            idCard.substring(6, 10) +
            '-' +
            idCard.substring(10, 12) +
            '-' +
            idCard.substring(12, 14);
        }
      }
      console.log('params', params);
      params.inHospitalInfo.balanceAmount = advance.value;
      const performRegistration = () => {
        noFilesRegister(params).then((res) => {
          if (res.code == 200) {
            emits('okAct');
            ElMessage.success(res.msg);
            advancePaymentVisible.value = true;
          } else {
            ElMessage.error(res.msg);
          }
        });
      };
      if (advance.value == 0) {
        ElMessageBox.confirm('住院预交金额未填写，确认登记吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            performRegistration();
          })
          .catch(() => {});
      } else {
        performRegistration();
      }
    });
  } else {
    params.balanceAmount = advance.value;
    params.patientId = props.patientInfo.patientId;
    RegisterFormRef.value.validateData(async () => {
      params = { ...params, ...RegisterFormRef.value.submitForm };
      console.log('params', params);
      const performRegistration = () => {
        registerInHospital(params).then((res) => {
          if (res.code == 200) {
            emits('okAct');
            ElMessage.success(res.msg);
            advancePaymentVisible.value = true;
          } else {
            ElMessage.error(res.msg);
          }
        });
      };

      if (advance.value == 0) {
        ElMessageBox.confirm('住院预交金额未填写，确认登记吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            performRegistration();
          })
          .catch(() => {});
      } else {
        performRegistration();
      }
    });
  }
};

const openAct = () => {
  console.log(props.patientInfo, 'patientRegister.vue');
  console.log(props.inHospitalInfo, 'inHospitalInfo.vue');
  /* 初始化数据 */
  advance.value = props.inHospitalInfo.balanceAmount || 0;
  advancePaymentVisible.value = false;
  RegisterFormRef.value.init();
};
const closedAct = () => {
  dialogVisible.value = false;
  if (patientInfoRef.value?.isEditing) {
    patientInfoRef.value.isEditing = false;
  }
};

onMounted(() => {
  getInit().then((res) => {
    initOptions.value = res.data;
  });
});

/* 登记 */
const RegisterFormRef = ref();

const feeTypeOptions = reactive([
  {
    type: 'hipCash',
    label: '现金',
  },
  {
    type: 'hipAlipay',
    label: '支付宝',
  },
  {
    type: 'wechat',
    label: '微信',
  },
  {
    type: 'hipPayCard',
    label: '银行卡',
  },
]);
const advance = ref('0.00');
const currentFeeType = ref('hipCash');
/* 预交金录入框格式 */
const handleAdvanceInput = (value) => {
  if (value.length === 1 && value === '.') {
    value = '0.';
  } else {
    advance.value = value.replace(/[^\d.]/g, '').replace(/^(\d*\.\d{2}).*$/, '$1');
  }
};
const handleAdvanceFormatter = (value) => {
  return `¥ ${value}`;
};
const handleAdvanceParser = (value) => {
  return value.replace(/\$\s?|(,*)/g, '');
};
const medicalInsuranceVisible = ref(false);
const medicalInsuranceTitle = ref('');

/* 患者费别变更 */
const onChangFeeType = () => {
  medicalInsuranceTitle.value = '医保信息'; //医保信息、医保登记
  medicalInsuranceVisible.value = true;
};

/*  */
</script>
<style lang="scss" scoped>
.patientRegister-container {
  height: 700px;
  overflow-y: auto;
}

.advance-container {
  width: 660px;
  display: flex;

  .feeType {
    display: flex;
    align-items: center;
    height: 32px;
    padding: 0px 8px;
    color: #666666;
    border-radius: 4px;
    cursor: pointer;

    :deep(.svg-icon) {
      color: #666666;
    }
  }

  .activeFeeType {
    color: #13c0b3;
    background: rgba(19, 192, 179, 0.1);

    :deep(.svg-icon) {
      color: #13c0b3;
    }
  }
}
</style>
