<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">
          <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"
        >
          {{ '读卡' }}
        </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?.name || '-' }}</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" />
        </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?.ageString || '-' }}</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>{{ 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>{{ patientInfo?.organizationId_dictText || '-' }}</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" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import PatientInfoForm from './patientInfoForm.vue';
import { patientlLists, getOrgList } from './api';

const typeList = ref({});
const patientInfoFormRef = ref();
const props = defineProps({
  patientInfo: {
    type: Object,
    require: true,
    default: () => ({}),
  },
  registrationType: {
    type: [String, Boolean, Number], // 根据实际类型调整
    default: null, // 或者 false、'' 等
  },
  initOptions: {
    type: Object,
    require: true,
    default: () => ({}),
  },
  noFile: {
    type: Boolean,
    default: false,
  },
});
const emits = defineEmits(['onChangFeeType']);
const registerRef = ref();
const typeCode = ref('01');
const organization = 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;
    }
  });
};
async function handleReadCard(value) {
  if (window.CefSharp === undefined) {
    alert('请在医保版本中调用读卡功能！');
  } else {
    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;
      let cardInfo;
      let userMessage = undefined;
      switch (value) {
        case '01': // 电子凭证
          // readCardLoading.value = true;
          await boundAsync
            .getInfoByQrCodeAsync(
              'http://10.47.0.67:8089/localcfc/api/hsecfc/localQrCodeQuery',
              'H22010200672',
              '01101',
              userStore.id,
              userStore.name,
              'D83',
              '财务科'
            )
            .then((res) => {
              readCardLoading.value = true;
              loadingText.value = '正在读取...';
              jsonResult = res;
            })
            .catch(() => {
              readCardLoading.value = false;
            });
          cardInfo = JSON.parse(jsonResult);
          let message = JSON.parse(cardInfo.message);
          userMessage = {
            certType: '02', // 证件类型
            certNo: message.data.idNo, // 身份证号
            psnCertType: '02', // 居民身份证
          };
          break;
        case '02':
          break;
        case '03': // 社保卡
          readCardLoading.value = true;
          loadingText.value = '正在读取...';
          await boundAsync
            .readHeaSecCardAsync(
              JSON.stringify({
                IP: 'ddjk.jlhs.gov.cn',
                PORT: 20215,
                TIMEOUT: 60,
                SFZ_DRIVER_TYPE: 1,
              })
            )
            .then((res) => {
              jsonResult = res;
            })
            .finally(() => {
              readCardLoading.value = false;
            });
          // console.log(
          //   'jsonResult',
          //   JSON.parse({
          //     IssuingAreaCode: '310000',
          //     SocialSecurityNumber: '371324198810224515',
          //     CardNumber: 'M501A1A78',
          //     CardIdentificationCode: '310000D15600000535925154E880AB97',
          //     Name: '\u5218\u5CF0',
          //     CardResetInfo: '00814A444686603100333E4FA9',
          //     SpecificationVersion: '3.00',
          //     IssuingDate: '20190313',
          //     ExpirationDate: '20290313',
          //     TerminalNumber: '000000000000',
          //     TerminalDeviceNumber: '00041161201901000005',
          //     Code: 0,
          //     ErrorMessage: null,
          //   })
          // );
          let message1 = JSON.parse(jsonResult);
          userMessage = {
            certType: '02', // 证件类型
            certNo: message1.SocialSecurityNumber, // 身份证号
            psnCertType: '02', // 居民身份证
          };
          break;
        case '99':
          break;
      }
      readCardLoading.value = true;
      if (userMessage.certNo) {
        gerPreInfo(userMessage)
          .then((res) => {
            if (res.code == 200) {
              form.value.patientId = res.data.id;
              form.value.name = res.data.name;
              form.value.age = res.data.age;
              form.value.idCard = res.data.idCard;
              form.value.card = res.data.id;
              form.value.contractNo = res.data.contractBusNo;
              form.value.genderEnum = res.data.genderEnum;
              form.value.ybAreaNo = res.data.contractName;
            }
          })
          .finally(() => {
            readCardLoading.value = false;
          });
      }
    } catch (error) {
      console.error('调用失败:', error);
      readCardLoading.value = false;
    }
  }
}
function getPatientForm() {
  console.log(patientInfoFormRef.value.form);

  return patientInfoFormRef.value.form;
}

// 患者费别变更
const changFeeType = () => {
  emits('onChangFeeType');
};
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>