<template>
  <view class="container">
    <view class="content">
      <!-- <cardPanel>
        <view slot="header">
          <view class="text-primary display-flex__ac btn-record">申请退款记录</view>
          <view class="btn_arrow"></view>
        </view>
      </cardPanel> -->

      <view class="white-panel" @click="toRecord">
        <view class="text-primary display-flex__ac btn-record">申请退款记录</view>
        <view class="btn_arrow"></view>
      </view>

      <!-- 就诊人卡片 -->
      <view class="white-panel no-padding" v-for="(item, index) in memberList" :key="index">
        <view class="panel-header">
          <view class="title-main display-flex__ac">
            <view class="text-color__dominant font-bold">{{ item.memberName }}</view>
            <view class="text-color__secondary" style="margin-left: 20upx; font-size: 30upx;">{{ item.mobile }}</view>
          </view>

          <view class="title-sub display-flex__ac">
            <view class="text-color__secondary">{{ item.certTypeName }}：{{ item.certNum }}</view>
          </view>
        </view>

        <!-- 分割线 -->
        <cardDiv colorLine="#eee" colorGap="#f0f1f6"></cardDiv>

        <view class="panel-main">
          <!-- 卡列表 -->
          <view class="card-list">
            <view class="card-list__item display-flex__ac displayFlexBetween" v-for="(cardItem, cardIndex) in item.cardList" :key="cardIndex">
              <view>就诊卡：{{ cardFormatter(cardItem.CardNo) }}</view>
              <view>余额：{{ amountFormatter(cardItem.Balance) / 100 || 0 }}元</view>
            </view>
          </view>
        </view>

        <view class="panel-footer">
          <view class="public_btn backgroundCustom" @click="selectRefundChannel(item)">退款</view>
        </view>
      </view>
    </view>
  </view>

  <!-- 遮罩层 -->
  <view class="mask" v-if="showModalStatus"></view>
  <!-- 弹窗 -->
  <view class="modal" :style="{ animation: showModalStatus ? 'slideIn 0.3s' : 'slideOut 0.3s' }" v-if="showModalStatus">
    <!-- 弹窗头部 -->
    <view class="modal-header">
      <text>门诊历史预缴金退款申请需知</text>
    </view>
    <!-- 弹窗内容 -->
    <view class="modal-content">
      <view class="p">尊敬的患者：</view>
      <view class="p text-ident">
        此功能针对退款对象为医院就诊卡有账户余额的患者。
      </view>
      <view class="p">
        1.原路退的方式仅支持近期在线上进行充值的患者。如果原路退的可退金额为0，请选择转账退费。
      </view>
      <view class="p">
        2.转账退支持银行卡转账、微信/支付宝转账方式。如果无法提供转账退费所需要的信息，请您携带就诊卡及就诊人的身份证件，到医院收费处窗口办理。
      </view>
      <view class="p">
        3、改善就医感受、提升患者体验，我们一直在努力！感谢您的支持与配合！
      </view>
      <view class="p">
        友情提醒：为了保障您预缴金的资金安全，线上转账退申请登记完成后，医院将进行基本信息审核，核验无误后为您办理退款。办理时间约30个工作日，请您耐心等待，有疑问欢迎在工作时间拨打电话 0594-00000；
      </view>
    </view>
    <!-- 弹窗底部按钮区域 -->
    <view class="modal-footer">
      <!-- Note: Original bindtap="selectRefundChannel" but passed no arg? -->
      <!-- Original: bindtap="selectRefundChannel". In selectRefundChannel(e), it uses e.currentTarget.dataset.item. -->
      <!-- But here in modal footer, there is no dataset.item. -->
      <!-- However, the modal seems to confirm the selection? -->
      <!-- Wait, looking at original WXML: -->
      <!-- <view class="btn btn-confirm" bindtap="selectRefundChannel">确认</view> -->
      <!-- But selectRefundChannel(e) expects e.currentTarget.dataset.item. -->
      <!-- If called from modal, item is undefined. -->
      <!-- app.globalData.queryBean = item; -->
      <!-- If item is undefined, queryBean is undefined. -->
      <!-- Then common.goToUrl(...) -->
      <!-- This seems like a bug or incomplete logic in the original code, or I missed something. -->
      <!-- Ah, the modal is shown when? -->
      <!-- showModalStatus is false initially. -->
      <!-- There is NO code that sets showModalStatus to true in the original JS file! -->
      <!-- So the modal is never shown? -->
      <!-- Line 16: showModalStatus: false -->
      <!-- No usage of setData({showModalStatus: true}). -->
      <!-- So the modal code is dead code or unfinished. -->
      <!-- I will implement it as is (hidden), but fix the click handler to avoid error if it were to be shown. -->
      <!-- Actually, I should just replicate the original logic. If original calls selectRefundChannel, I call it. -->
      <!-- But I can't pass 'item' if it's not available. -->
      <!-- I'll just bind @click="selectRefundChannel(null)" and handle null in the function or just let it fail/pass undefined as original. -->
      <!-- Wait, if I pass null, item is null. -->
      <view class="btn btn-confirm" @click="selectRefundChannel(null)">确认</view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { REQUEST_CONFIG } from '@/config';
import { request, handle } from '@kasite/uni-app-base';
import { common } from '@/utils';
import cardDiv from '../components/cardDiv/cardDiv.vue';

const app = getApp();
const currentUser = ref<any>({});
const memberList = ref<any[]>([]);
const showModalStatus = ref(false);

const amountFormatter = (val: any) => {
  if (!val) return 0;
  return Number(val);
};

const cardFormatter = (val: string) => {
  if (!val) return '';
  if (val.length !== 36) { // 非现金卡
    return val;
  }
  // 现金卡
  return val.substring(5, 13);
};

onLoad((options) => {
  initPageParam(options);
});

onShow(async () => {
  await getMemberList(); // 获取就诊人列表
  await buildQueue_getMemberCardList();    // 获取卡列表及卡余额
});

/**
 * 构建请求队列-获取患者就诊卡列表
 */
const buildQueue_getMemberCardList = async () => {
  if (common.isEmpty(memberList.value)) {
    return;
  }
  const reqArr = memberList.value.map(async (item) => {
    item.cardList = await getMemberCardList(item);
    return item;
  });
  await Promise.all(reqArr);
  // No need to setData, memberList is reactive
};

/**
 * 获取就诊人列表
 */
const getMemberList = async () => {
  // const resp = await publicFn.getMember('memberList');
  const queryData = {
    isCache: false,
    isEncrypt: true,
    hosId: app.globalData.districtId || app.globalData.hosId,
    openid: uni.getStorageSync('openid'),
    mobileFormatDesensitization: "false",
    memberNameFormatDesensitization: "false",
    certNumFormatDesensitization: "false",
    cardNoFormatDesensitization: "false"
  };
  
  let resp = handle.promistHandleNew(
    await request.doPost(
      `${REQUEST_CONFIG.BASE_URL}wsgw/accountMember/api/QueryBaseMemberList_V3/callApiJSON.do`,
      queryData
    )
  );
  
  const { resp: listResp } = handle.catchPromiseNew(resp, () => resp);

  // 只构建需要的结构，下列明文展示的就是当前业务逻辑所需的所有参数
  const list = (listResp || []).map((item: any) => ({
    memberId: item.memberId,  // memberId
    memberName: item.memberName,  // 姓名
    mobile: item.mobile,    // 联系电话
    certType: item.certType,  // 证件类型编码
    certTypeName: item.certTypeName,  // 证件类型名称
    certNum: item.certNum,    // 证件号
    baseMemberEncryptionStore: item.baseMemberEncryptionStore,  // 加密串
    cardList: [], // 卡列表
  }));
  memberList.value = list || [];
};

/**
 * 获取就诊人的就诊卡
 */
const getMemberCardList = async (data: any) => {
  const reqData = {
    BaseMemberEncryptionStore: data.baseMemberEncryptionStore,
    MemberId: data.memberId,
    IsQueryHis: 1,  // 就诊卡列表是否实时查HIS（0——本地（旧版），1——查HIS（新版））
  };
  
  let resp = handle.promistHandleNew(
    await request.doPost(
      `${REQUEST_CONFIG.BASE_URL}wsgw/accountMember/api/QueryMemberCardListAdnCardBalance/callApiJSON.do`,
      reqData,
      {
        showModal: false, 
      }
    )
  );

  const { resData, resp: listResp } = handle.catchPromiseNew(resp, () => resp);

  if (resData && resData.RespCode != "10000") {
    return [];
  }
  return listResp || [];
};

/**
 * 查看申请记录
 */
const toRecord = () => {
  // 旧
  // common.goToUrl(`/pagesPatient/st1/business/refund/refundApplicationRecord/refundApplicationRecord`, { skipWay: "navigateTo", data: "" });
  // 新
  common.goToUrl(`/pagesPatient/st1/business/outpatient/outpatientRefundNew/refundRecord/refundRecord`, { skipWay: "navigateTo", data: "" });
};

/**
 * 前往选择退款方式页面
 */
const selectRefundChannel = (item: any) => {
  // Original logic:
  // const { item } = e.currentTarget.dataset;
  // If called from modal, item might be null/undefined.
  // In Vue, we pass item directly from v-for.
  
  if (item) {
    app.globalData.queryBean = item;
  }
  
  common.goToUrl(`/pagesPatient/st1/business/outpatient/outpatientRefundNew/selectRefundChannel/selectRefundChannel`);
};

/**处理页面入参 */
const initPageParam = (options: any) => {
  currentUser.value = getApp().globalData.currentUser;
};
</script>

<style>
@import "../static/css/refund.wxss";

.white-panel {
  padding: 30upx 40upx;
}

.white-panel .panel-header {
  width: 100%;
  padding: 30upx 40upx 0;
  min-height: 60upx;
  height: fit-content;
}

.white-panel .panel-main {
  width: 100%;
  padding: 0upx 40upx;
  /* min-height: 100upx; */
  height: fit-content;
  overflow: hidden;
}

.white-panel .panel-footer {
  width: 100%;
  padding: 40upx 40upx;
}

.btn-record {
  font-size: 30upx;
}

.title-main {
  font-size: 34upx;
  height:  60upx;
}

.title-sub {
  color: #4D4D53;
  margin-top: 20upx;
}

/* 卡列表 */
.card-list{}

.card-list .card-list__item {
  width: 100%;
  height: 90upx;
  border-radius: 14upx;
  background-color: #F7F7F9;
  padding: 20upx;
}

.card-list .card-list__item + .card-list__item {
  margin-top: 30upx;
}

/* 弹窗 */
/* 遮罩层样式 */
.mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 1000;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  max-height: 80vh;
  background-color: #fff;
  border-radius: 8px;
  overflow: hidden;
  z-index: 1001;
  display: flex;
  flex-direction: column;
}

/* 弹窗头部样式 */
.modal-header {
  padding: 30upx 40upx ;
  border-bottom: 1px solid #e5e5e5;
  font-size: 34upx;
  font-weight: bold;
  text-align: center;
}

/* 弹窗内容样式 */
.modal-content {
  padding: 15px;
  flex: 1;
  overflow-y: auto;
}

.p {
  font-size: 30upx;
  line-height: 50upx;
  text-align: justify;
}

/* 弹窗底部样式 */
.modal-footer {
  border-top: 1px solid #e5e5e5;
  text-align: right;
  height: 100upx;
  display: flex;
  align-items: stretch;
  justify-content: stretch;
}

.btn {
  flex: 1 0 0;
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn:active {
  backdrop-filter: brightness(0.86);
}

.btn + .btn {
  border-left: 2upx solid #e5e5e5;
}

/* 弹窗动画 */
@keyframes slideIn {
  from {
    opacity: 0;
    transform: translate(-50%, -40%);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
}

@keyframes slideOut {
  from {
    opacity: 1;
    transform: translate(-50%, -50%);
  }
  to {
    opacity: 0;
    transform: translate(-50%, -40%);
  }
}
</style>
