<template>
  <div class="patientInfo-container">
    <div class="operate">
      <div>基础信息</div>
      <!-- <div
        v-if="props.registrationType"
        type="primary"
        @click="toggleEdit"
        style="margin-right: 0; cursor: pointer; margin-right: 12px"
      >
        {{ isEditing ? '取消' : '编辑' }}
      </div> -->
      <div>
        <el-radio-group v-model="typeCode" :disabled="props.isRegistered">
          <el-radio label="电子凭证" value="01"></el-radio>
          <el-radio label="医保卡" value="03"></el-radio>
          <el-radio label="身份证" value="02"></el-radio>
        </el-radio-group>
        <span
          @click="handleReadCard(typeCode)"
          style="cursor: pointer; margin: 0 12px 0 30px; color: #409eff"
          v-if="!props.isRegistered"
        >
          {{ '读卡' }}
        </span>
      </div>
    </div>

    <!-- 展示模式 -->
    <div v-if="!noFile" style="margin-left: 30px">
      <el-row class="patientInfos">
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>患者编码：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <el-text truncated>{{ patientInfo?.busNo || '-' }}</el-text>
        </el-col>
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>患者姓名：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <el-text truncated>{{ patientInfo?.patientName || '-' }}</el-text>
        </el-col>
        <!-- <el-col :span="2" class="patInfo-label">
          <el-text truncated>费别类型：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <el-text truncated>{{ patientInfo?.ybClassEnum_enumText || '-' }}</el-text> -->
        <!-- TODO -->
        <!-- <svg-icon
            size="20"
            icon-class="hipEdit"
            style="cursor: pointer"
            @click="changFeeType"
            v-if="!props.isRegistered"
          />
        </el-col> -->
      </el-row>
      <el-row class="patientInfos">
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>证件类型：</el-text>
        </el-col>
        <!-- TODO -->
        <el-col :span="4" class="patInfo-value">
          <el-text truncated>{{ patientInfo?.patientTypeCode_dictText || '-' }}</el-text>
        </el-col>
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>证件号：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <el-text truncated>{{ patientInfo?.idCard || '-' }}</el-text>
        </el-col>
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>出生日期：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <el-text truncated>{{ patientInfo?.birthDate || '-' }}</el-text>
        </el-col>
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>年龄：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <el-text truncated>{{ patientInfo?.age || '-' }}</el-text>
        </el-col>
      </el-row>
      <el-row class="patientInfos">
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>性别：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <div>{{ patientInfo?.genderEnum_enumText || '-' }}</div>
        </el-col>
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>民族：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <div>{{ getDictLabel(nationality_code, patientInfo?.nationalityCode) || '-' }}</div>
        </el-col>
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>国籍：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <div>{{ patientInfo?.countryCode || '-' }}</div>
        </el-col>
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>婚姻：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <div>{{ patientInfo?.maritalStatusEnum_enumText || '-' }}</div>
        </el-col>
      </el-row>
      <el-row class="patientInfos">
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>职业：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <div>{{ patientInfo?.prfsEnum_enumText || '-' }}</div>
        </el-col>
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>手机：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <div>{{ patientInfo.phone || '-' }}</div>
        </el-col>
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>现住址：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <div>{{ patientInfo?.address || '-' }}</div>
        </el-col>
      </el-row>
      <el-row class="patientInfos">
        <!-- <el-col :span="2" class="patInfo-label">
          <el-text truncated>户口地址：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <div>{{ patientInfo?.nativeExactAddr }}</div>
        </el-col> -->
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>籍贯：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <div>{{ patientInfo?.nativePlace || '-' }}</div>
        </el-col>
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>病人来源：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <div>{{ props.inHospitalInfo?.inHospitalOrgName || '-' }}</div>
        </el-col>
        <el-col :span="2" class="patInfo-label">
          <el-text truncated>单位名称：</el-text>
        </el-col>
        <el-col :span="4" class="patInfo-value">
          <div>{{ patientInfo?.workCompany || '-' }}</div>
        </el-col>
      </el-row>
    </div>
    <div v-else>
      <PatientInfoForm ref="patientInfoFormRef" :is-view-mode="props.isRegistered" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue';
import PatientInfoForm from './patientInfoForm.vue';
import { patientlLists, getOrgList, gerPreInfo } from './api';
import { invokeYbPlugin5001 } from '@/api/public';
import useUserStore from '@/store/modules/user';
import { useRouter } from 'vue-router';

const { proxy } = getCurrentInstance();
const typeList = ref({});
const patientInfoFormRef = ref();
let userCardInfo = ref({});
const BusiCardInfo = ref('');
const userStore = useUserStore();
const router = useRouter();

const props = defineProps({
  patientInfo: {
    type: Object,
    require: true,
    default: () => ({}),
  },
  inHospitalInfo: {
    type: Object,
    default: () => ({}),
  },
  registrationType: {
    type: [String, Boolean, Number], // 根据实际类型调整
    default: null, // 或者 false、'' 等
  },
  initOptions: {
    type: Object,
    require: true,
    default: () => ({}),
  },
  noFile: {
    type: Boolean,
    default: false,
  },
  //待入院，已入院区分
  isRegistered: {
    type: Boolean,
    default: false,
  },
  inHospitalInfo: {
    type: Object,
    default: () => ({}),
    required: false,
  },
});
const emits = defineEmits(['onChangFeeType', 'carReading']);
const registerRef = ref();
const typeCode = ref('01');
const organization = ref([]);
const { nationality_code } = proxy.useDict('nationality_code');

const readCardLoading = ref(false);
const loadingText = ref('正在读取...');

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

// 编辑状态
const isEditing = ref(false);

watch(
  () => props.registrationType,
  (newValue) => {
    isEditing.value = !newValue;
  },
  { immediate: true }
);

watch(
  () => props.patientInfo,
  (newValue) => {},
  { immediate: true }
);

function getInitOptions() {
  patientlLists().then((res) => {
    typeList.value = res.data;
  });
  getOrgList().then((res) => {
    organization.value = res.data.records;
  });
}

// 表单数据
const form = reactive({});

// 切换编辑状态
const toggleEdit = () => {
  if (!isEditing.value) {
    // 取消时恢复原值
    Object.assign(form, props.patientInfo);
  }
  isEditing.value = !isEditing.value;
};

// 提交表单
const submitForm = async (callback) => {
  console.log('提交更新:', form);
  if (!registerRef.value) return false;
  registerRef.value.validate((valid) => {
    if (valid) {
      callback();
      return true;
    } else {
      return false;
    }
  });
};
const getDictLabel = (dictList, value) => {
  if (!dictList || !value) return '';
  const item = dictList.find((item) => item.value === value);
  return item ? item.label : value;
};
async function handleReadCard(value) {
  try {
    // await CefSharp.BindObjectAsync('boundAsync');
    // string url,
    // string fixmedins_code,
    // string businessType,
    // string operatorCode,
    // string operatorName,
    // string officeId,
    // string officeName

    // readCardLoading.value = true;
    // let jsonResult = null;
    let jsonResult;
    let cardInfo;
    let userMessage = undefined;

    // 调试日志，检查patientInfo中的值
    console.log('patientInfo:', props.patientInfo);
    console.log('patientInfo中的id:', props.patientInfo?.id);
    console.log('patientInfo中的encounterId:', props.patientInfo?.encounterId);
    switch (value) {
      case '01': // 电子凭证
        // readCardLoading.value = true;
        // await boundAsync
        //   .getInfoByQrCodeAsync(

        //   )
        await invokeYbPlugin5001({
          FunctionId: 3,
          url: 'http://10.47.0.67:8089/localcfc/api/hsecfc/localQrCodeQuery',
          orgId: 'H22010200672',
          businessType: '01101',
          operatorId: userStore.id.toString(),
          operatorName: userStore.name,
          officeId: 'D83',
          officeName: '财务科',
        })
          .then((res) => {
            readCardLoading.value = true;
            loadingText.value = '正在读取...';
            console.log(res);
            jsonResult = res.data;

            cardInfo = JSON.parse(JSON.stringify(jsonResult));
            let message = JSON.parse(cardInfo.message);
            console.log('patientInfo中的encounterId:', props.patientInfo);
            const encounterId = props.inHospitalInfo.encounterId || '1993854019030441985';
            console.log('1111111111111111111准备使用的encounterId:', encounterId);

            userMessage = {
              certType: '02', // 证件类型
              certNo: message.data.idNo, // 身份证号
              psnCertType: '02', // 居民身份证
              encounterId: encounterId || '1993854019030441985',
            };
            userCardInfo = {
              certType: '01', // 证件类型
              certNo: message.data.idNo, // 身份证号
              psnCertType: '01', // 居民身份证
              busiCardInfo: message.data.ecToken, // 令牌
              encounterId: encounterId || '1993854019030441985',
            };
            BusiCardInfo.value = message.data.ecToken;
            console.log(BusiCardInfo.value);

            emits('carReading', jsonResult);
          })
          .catch(() => {
            readCardLoading.value = false;
          });
        break;
      case '02':
        break;
      case '03': // 社保卡
        readCardLoading.value = true;
        loadingText.value = '正在读取...';
        await invokeYbPlugin5001(
          JSON.stringify({
            FunctionId: 1,
            IP: 'ddjk.jlhs.gov.cn',
            PORT: 20215,
            TIMEOUT: 60,
            SFZ_DRIVER_TYPE: 1,
          })
        )
          .then((res) => {
            jsonResult = JSON.stringify(res.data);

            let message1 = JSON.parse(jsonResult);
            // 从patientInfo中获取encounterId，如果没有则尝试从住院号中获取
            // const encounterId =
            //   props.patientInfo?.encounterId || props.patientInfo?.visitNo || props.patientInfo?.busNo;
            // console.log('准备使用的encounterId:', encounterId);

            userMessage = {
              certType: '02', // 证件类型
              certNo: message1.SocialSecurityNumber, // 身份证号
              psnCertType: '02', // 居民身份证
              encounterId: encounterId || '1993854019030441985',
            };
            userCardInfo = {
              certType: '02', // 证件类型
              certNo: message1.SocialSecurityNumber, // 身份证号
              psnCertType: '02', // 居民身份证
              busiCardInfo: message1.BusiCardInfo, //卡号
              encounterId: encounterId || '1993854019030441985',
            };
            BusiCardInfo.value = message1.BusiCardInfo;
            console.log(message1.BusiCardInfo);

            emits('carReading', res.data);
          })
          .finally(() => {
            readCardLoading.value = false;
          });
        break;
      case '99':
        break;
    }
    readCardLoading.value = true;
    // 调试日志，检查发送给gerPreInfo的参数
    console.log('发送给gerPreInfo的参数:', userMessage);

    if (userMessage && userMessage.certNo) {
      gerPreInfo(userMessage)
        .then((res) => {
          console.log('gerPreInfo返回结果:', res);
          if (res && res.code == 200 && res.data) {
            form.patientId = res.data.id;
            form.name = res.data.name;
            form.age = res.data.age;
            form.idCard = res.data.idCard;
            form.card = res.data.id;
            form.contractNo = res.data.contractBusNo;
            form.genderEnum = res.data.genderEnum;
            form.ybAreaNo = res.data.contractName;
            form.encounterId = res.data.encounterId;
            // 成功获取数据后跳转到 registerEdit 页面，并传递数据
            // router.push({
            //   name: '/ybmanagement/inhospital/register/edit', // 需要根据实际路由名称调整
            //   params: {
            //     cardData: JSON.stringify(res.data), // 将完整数据作为参数传递
            //     cardType: value, // 卡类型
            //   },
            // });
          } else {
            // 处理无有效数据的情况
            ElMessage.error('未获取到有效的患者信息');
          }
        })
        .catch((error) => {
          console.error('gerPreInfo调用失败:', error);
        })
        .finally(() => {
          readCardLoading.value = false;
        });
    }
  } catch (error) {
    console.error('调用失败:', error);
    readCardLoading.value = false;
  }
  // }
}

// 患者费别变更
const changFeeType = () => {
  emits('onChangFeeType');
};

// 无档登记收集信息
const getPatientForm = () => {
  return patientInfoFormRef?.value?.form;
};
defineExpose({ submitForm, form, isEditing, getPatientForm });
</script>

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

  > .patientInfos {
    margin-bottom: 16px;

    &:not(.patientInfo-container :has(+ .patientInfos)) {
      margin-bottom: 0px;
    }
  }
}
.patInfo-label {
  color: #606266 !important;
  font-size: 14px;
  font-weight: 700 !important;
  margin-bottom: 10px;
}
</style>
