<template>
  <el-dialog :model-value="visible" title="挂号记录详情" :close-on-press-escape="false" :close-on-click-modal="!loading"
    @close="close()">
    <el-scrollbar v-loading="waiting" wrap-style="max-height: 60vh">
      <div class="p-15px">
        <el-descriptions title="" :column="2">
          <el-descriptions-item label="医生：">{{data.doctorName}}</el-descriptions-item>
          <el-descriptions-item label="职称：">{{data.title}}</el-descriptions-item>
          <el-descriptions-item label="科室：">{{data.deptName}}</el-descriptions-item>
          <el-descriptions-item label="门店："> {{ data.shopname }}</el-descriptions-item>
          <el-descriptions-item label="总额：">
            {{ data.preSettle ? data.preSettle.totalamount :'' }}
          </el-descriptions-item>
          <el-descriptions-item label="医保支付：">
            {{ ybFee }}
          </el-descriptions-item>
          <el-descriptions-item label="自付金额：">
            {{ data.preSettle ? data.preSettle.selfpay :'' }}
          </el-descriptions-item>
          <el-descriptions-item label="挂号时间：">{{data.time}}</el-descriptions-item>
          <el-descriptions-item label="状态：">{{PayStatus[payStatus]}}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-scrollbar>
    <template #footer>
      <div text-center>
        <el-button plain class="w-100px" type="primary" @click="close()">关闭</el-button>
        <el-button v-if="payStatus === '0'" class="w-100px" :loading="loading" type="primary" @click="confirm()">
          退费
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, computed } from 'vue';
import { storeToRefs } from 'pinia';
import { ElMessage, ElMessageBox } from 'element-plus';
import { memberStore } from "@/store/member";
import { hlwRegRefund, getRegPayStatus } from '@/api/hlw';
import BigNumber from "bignumber.js";
import { getReadCardApi } from '@/api/card-jsonp.js';
import validate from "@/utils/validate";


const emits = defineEmits(['close', 'change', 'changeHisStatus'])
const props = defineProps({
  PayStatus: { type: Object, default: () => ({}) },
  data: { type: Object, default: () => ({}) },
  cardInfo: { type: Object, default: () => ({}) },
  visible: { type: Boolean, default: false },
})

const loading = ref(false)
const waiting = ref(false)
const payStatus = ref()
const { memberInfo } = storeToRefs(memberStore());

const ybFee = computed(() => {
  if (props.data && props.data.preSettle && typeof props.data.preSettle.totalamount === 'number' && typeof props.data.preSettle.selfpay === 'number') {
    return new BigNumber(props.data.preSettle.totalamount).minus(props.data.preSettle.selfpay).toNumber()
  }
  return ''
})

function close() {
  emits('close')
}

async function confirm() {
  if (loading.value) return;
  await ElMessageBox.confirm('确定退费吗？', '提示', { type: 'warning' });
  loading.value = true;
  const res = await readCard();
  if (!res) {
    loading.value = false;
    return
  }
  const params = {
    _id: props.data._id,
    registerId: props.data.registerId,
    storeId: memberInfo.value.drugStoreId,
    mdtrtCertNo: props.cardInfo.CardNum,
    cardSn: props.cardInfo.CardIDCode
    // operatorCode: 'YCZSSMYD',
    // operatorName: '滨海新城朱邵三民药店',
  }
  const { success, message } = await hlwRegRefund(params);
  loading.value = false;
  if (success) {
    ElMessage.success(message)
    close()
    emits('change')
  } else {
    ElMessage.error(message)
  }
}

async function getPayStatus() {
  waiting.value = true;
  const { success, message, data } = await getRegPayStatus({ registerId: props.data.registerId, patientId: props.data.patientId, id: props.data._id, hisStatus: props.data.hisStatus })
  waiting.value = false;
  if (success) {
    payStatus.value = data.status;
    emits('changeHisStatus', data.status)
  } else {
    ElMessage.error(message)
  }
}


async function readCard() {
  try {
    const { close } = ElMessage.info('正常读取卡信息...')
    const readRes = await getReadCardApi();
    const IDNum = readRes && validate.isChinaId(readRes.IDNum || '')[0] ? readRes.IDNum : '';
    const msg = typeof readRes === 'string' ? readRes : '';
    const objMsg = readRes && typeof readRes.Message ? readRes.Message : '';
    close()
    if (!IDNum) {
      loading.value = false;
      ElMessage.info(objMsg || msg || '读取卡信息失败')
      return false
    }
    if (readRes.CardNum === props.cardInfo.CardNum && readRes.CardIDCode === props.cardInfo.CardIDCode) {
      return true
    } else {
      ElMessage.info('患者信息与挂号记录不匹配, 请插入正确的实体卡')
      return false
    }
  } catch (e) {
    console.log(e)
    ElMessage.info(e)
    return false
  }
}

watch(() => props.visible, n => {
  if (!n) return;
  payStatus.value = props.data.payStatus || ''
  if (props.data._id && !props.data.payStatus) {
    getPayStatus()
  }
})

</script>