<template>
  <view class="container">
    <view class="content" v-if="showCon">
      <userInfo :userInfo="currentUser" bgClass="bgLinGra"></userInfo>
      <view class="content_inner">
        <view class="public_info_list">
          <view class="public_info_item border_bottom displayFlexLeft">
            <view class="public_info_tit">可退金额</view>
            <view class="public_info_val colorRed">{{info.RefundableBalance/100}}元</view>
            <view class="public_info_remark">（通过微信公众号缴纳的预交金余额）</view>
          </view>
          <view class="public_info_item border_bottom displayFlexLeft">
            <view class="public_info_tit">就诊卡金额</view>
            <view class="public_info_val">{{info.Balance/100}}元</view>
          </view>
          <view class="public_info_item" @click="toDetails">
            <view class="public_info_tit">退款记录</view>
            <image class="public_right_img" :src="iconUrl.icon_right"></image>
          </view>
        </view>
        <view class="text_tip">
          <text>*温馨提示：</text>
          <text>1、退款金额将采用原路退还的方式，通过原缴费渠道（微信零钱包、银行卡），退还至您的初始支付账户（微信、银行账户），退款到账时间约为1-3个工作日</text>
          <text>2、可退金额：3个月内通过微信公众号缴纳的门诊预交金，经门诊结算后的剩余部分</text>
          <text>3、非通过微信公众号缴纳预交金的，请携带就诊卡本人有效身份证件、代办人有效身份证件及缴款凭据等资料前往门诊收费处办理退款手续。</text>
          <text>4、换卡、冻结、挂失卡不支持此渠道退款。</text>
        </view>
      </view>
      <view class="content_btn backgroundCustom" @click="refund">申请退款</view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { onShow } from '@dcloudio/uni-app';
import common from '@/utils/common';
import icon from '@/utils/icon';
import userInfo from '@/pagesPersonal/st1/components/userInfo/userInfo.vue';
import { queryMemberRefundableMoney, applySelfServiceRefund } from '@/pagesPatient/service/outpatient/index';

const app = getApp();
const iconUrl = icon;
const info = ref<any>({});
const showCon = ref(false);
const currentUser = ref<any>({});
const startkey = ref<any>(undefined);

onShow(() => {
  currentUser.value = app.globalData.currentUser;
  main();
});

const main = async () => {
  let user = currentUser.value;
  let queryData = {
    CardNo: user.cardNo,
    CardType: user.cardType,
    HisMemberId: user.hisMemberId,
    MemberId: user.memberId,
    Store: {
      cardEncryptionStore: user.encryptionStore || '',
      baseMemberEncryptionStore: user.baseMemberEncryptionStore
    }
  };
  let resp = await queryMemberRefundableMoney(queryData);
  let infoData: any = {};
  if (!common.isEmpty(resp)) {
    infoData = resp[0];
  }
  if (user.cardType == '1') {
    if (common.idCodeValid(user.cardNo).pass) {
      infoData.Balance = '0';
      infoData.RefundableBalance = '0';
      startkey.value = '0';
    }
  }
  
  info.value = infoData;
  showCon.value = true;
};

/**
 * 退费
 */
const refund = () => {
  let infoData = info.value;
  let user = currentUser.value;
  if (infoData.RefundableBalance == 0) {
    common.showModal(`可退金额为0`);
    return;
  }
  common.showModal(`￥${infoData.RefundableBalance / 100}`, async () => {
    let queryData = {
      CardNo: user.cardNo,
      CardType: user.cardType,
      HisMemberId: user.hisMemberId,
      MemberId: user.memberId,
      RefundableBalance: infoData.RefundableBalance,
      Page: {
        PIndex: 0,
        PSize: 1
      }
    };
    let result = await applySelfServiceRefund(queryData);
    // Note: The original code destructured {resp, resData}, but handle.promistHandleNew typically returns just the response body or similar.
    // However, looking at handle.promistHandleNew implementation (based on knowledge/memories), it returns [err, res].
    // But the service layer wrapper I saw:
    // let resp = handle.promistHandleNew(...)
    // return handle.catchPromiseNew(resp, () => resp)
    // catchPromiseNew usually returns the data if success.
    // In original code: let {resp,resData} = await outpatient.applySelfServiceRefund(queryData)
    // This suggests the service might have returned an object with resp and resData, OR the original code was using a different service wrapper.
    // In the new service/outpatient/index.ts:
    // return handle.catchPromiseNew(resp, () => resp);
    // This typically returns the `data` part of the response.
    // If the API returns { RespCode: "10000", ... }, then `result` will be that object.
    // Let's assume result contains RespCode.
    
    // Wait, the original code: let {resp,resData} = await outpatient.applySelfServiceRefund(queryData)
    // This destructuring looks suspicious if the service returns a standard response.
    // If the service returns `handle.catchPromiseNew(...)`, it usually returns the data directly.
    // If `resData` is what we need, maybe the original service returned `{resp, resData}`.
    // But the new service I see just returns `resp`.
    // Let's assume `result` is the response data and check `result.RespCode`.
    
    if (result && result.RespCode == "10000") {
      common.goToUrl(`/pagesPatient/st1/business/pay/payState/payState?isSuccess=true&pageType=refund`);
    }
  }, {
    confirmText: '确认退款',
    cancelText: '取消',
    title: '温馨提示'
  });
};

const toDetails = () => {
  common.goToUrl(`/pagesPatient/st1/business/outpatient/outpatientRefundRecord/outpatientRefundRecord?startkey=${startkey.value}`);
};
</script>

<style lang="scss" scoped>
.public_info_list{
  background-color: #fff;
  margin: 32upx;
  border-radius: 24upx;
  padding: 0 24upx;
}
.public_info_item {
  position: relative;
  padding: 40upx 0;
  margin: 0;
}

.public_info_tit {
  font-size: 32upx;
  font-weight: 400;
  color: rgba(0, 0, 0, 1);
  width: 160upx;
}

.public_info_val {
  font-size: 32upx;
  font-weight: 400;
  color: rgba(85, 85, 85, 1);
} 

.public_info_remark {
  font-size: 23upx;
  font-weight: 400;
  color: rgba(85, 85, 85, 1);
  line-height:44upx
} 


.text_tip {
  margin: 55upx 30upx 30upx;
  font-size: 30upx;
  font-family: PingFang SC;
  color: rgba(153, 153, 153, 1);
}
.text_tip text {
  display: inline-block;
  line-height: 45upx;
}

.content_btn {
  width: 100%;
  height: 98upx;
  line-height: 98upx;
  text-align: center; 
  font-size: 36upx;
  font-weight: 500;
  color: rgba(255, 255, 255, 1);
  position: fixed;
  bottom: 0;
}
</style>
