<template>
  <view class="container">
    <userInfo
      :is-show-switch-patient="true"
      :is-show-balance="true"
      :is-show-recharge="false"
      @refresh-data="refreshData"
    ></userInfo>
    <view class="recharge-money">
      <view class="recharge-money-title">充值金额</view>
      <view class="recharge-money-input">
        <text class="recharge-money-symbol">¥</text>
        <input
          class="recharge-money-input-val"
          type="digit"
          placeholder="请输入充值金额"
          placeholder-class="placeholder-class"
          v-model="rechargeMoney"
          @input="bindKeyInput"
        />
      </view>
      <view class="recharge-money-list">
        <view
          class="recharge-money-item"
          :class="{ active: item === rechargeMoney }"
          v-for="(item, index) in moneyList"
          :key="index"
          @click="selectMoney(item)"
        >
          <text class="recharge-money-item-val">{{ item }}元</text>
        </view>
      </view>
    </view>
    <view class="recharge-btn">
      <button class="btn" @click="jumpConfirmaPay">立即充值</button>
    </view>
    <view class="recharge-tips">
      <view class="recharge-tips-title">温馨提示</view>
      <view class="recharge-tips-content">
        <view class="recharge-tips-item">1. 充值金额将存入您的就诊卡账户中，可用于门诊缴费、住院缴费等。</view>
        <view class="recharge-tips-item">2. 请仔细核对充值金额，充值成功后无法撤销。</view>
        <view class="recharge-tips-item" v-if="frontPayLimit.MinPayMoney">3. 每次充值最低{{ frontPayLimit.MinPayMoney }}元。</view>
        <view class="recharge-tips-item" v-if="frontPayLimit.MaxPayMoney">4. 每次充值最高{{ frontPayLimit.MaxPayMoney }}元。</view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue';
import { onShow, onLoad } from '@dcloudio/uni-app';
import { useOnLoad } from '@/hook';
import { queryFrontPayLimit } from '@/pagesPatient/service/recharge';
import { queryCardBalance_V3, addOrderLocal } from '@/pagesPatient/service/pay';
import { pagesPatientFn } from '@/utils';
import { common } from '@/utils';
import userInfo from '@/pagesPersonal/st1/components/userInfo/userInfo.vue';

const rechargeMoney = ref('');
const currentUser = ref<any>({});
const pageType = ref('mzjf');
const balance = ref(0);
const frontPayLimit = ref<any>({});
const moneyList = [100, 200, 500, 1000];

useOnLoad((options: any) => {
  if (options.pageType) {
    pageType.value = options.pageType;
  }
  const app = getApp();
  if (app.globalData.defaultMember) {
    currentUser.value = app.globalData.defaultMember;
  }
});

onShow(async () => {
  await getFrontPayLimit();
  await getCardBalance();
});

const refreshData = (user: any) => {
  currentUser.value = user;
  getCardBalance();
};

const getFrontPayLimit = async () => {
  try {
    const res = await queryFrontPayLimit();
    if (res.Code === 10000 && res.Data) {
      frontPayLimit.value = res.Data;
    }
  } catch (e) {
    console.error(e);
  }
};

const getCardBalance = async () => {
  if (!currentUser.value || !currentUser.value.MemberId) return;
  try {
    const res = await queryCardBalance_V3({
      MemberId: currentUser.value.MemberId,
      CardType: currentUser.value.CardType,
      CardNo: currentUser.value.CardNo,
    });
    if (res.Code === 10000 && res.Data) {
      balance.value = res.Data.Balance;
    }
  } catch (e) {
    console.error(e);
  }
};

const bindKeyInput = (e: any) => {
  let val = e.detail.value;
  // Limit to 2 decimal places
  val = val.replace(/[^\d.]/g, ""); 
  val = val.replace(/\.{2,}/g, "."); 
  val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
  val = val.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');
  if (val.indexOf(".") < 0 && val != "") {
    val = parseFloat(val);
  }
  rechargeMoney.value = val;
};

const selectMoney = (money: number) => {
  rechargeMoney.value = money.toString();
};

const jumpConfirmaPay = async () => {
  if (!rechargeMoney.value) {
    common.showToast('请输入充值金额');
    return;
  }
  if (parseFloat(rechargeMoney.value) <= 0) {
    common.showToast('充值金额必须大于0');
    return;
  }
  
  if (frontPayLimit.value.MinPayMoney && parseFloat(rechargeMoney.value) < frontPayLimit.value.MinPayMoney) {
    common.showToast(`充值金额不能小于${frontPayLimit.value.MinPayMoney}元`);
    return;
  }

  if (frontPayLimit.value.MaxPayMoney && parseFloat(rechargeMoney.value) > frontPayLimit.value.MaxPayMoney) {
    common.showToast(`充值金额不能大于${frontPayLimit.value.MaxPayMoney}元`);
    return;
  }

  // Check pending orders
  let serviceId = pageType.value == 'mzjf' ? '006' : pageType.value == 'zyjf' ? '007' : '';
  if (await pagesPatientFn.hasOrderToBePaid(serviceId)) return;

  const app = getApp();
  // Construct order data
  let data = {
    PayMoney: rechargeMoney.value,
    MemberId: currentUser.value.MemberId,
    CardType: currentUser.value.CardType,
    CardNo: currentUser.value.CardNo,
    MemberName: currentUser.value.MemberName,
    ServiceId: serviceId,
    PayType: '2', // WeChat Pay
  };

  try {
    common.showLoading();
    const res = await addOrderLocal(data);
    common.hideLoading();
    if (res.Code === 10000 && res.Data) {
      // Navigate to payment page
      // Assuming rechargePay is the next page. 
      // Need to check where to go. rechargeMoney.js says:
      // wx.navigateTo({ url: '../rechargePay/rechargePay?orderId=' + res.Data.OrderId + '&payMoney=' + this.data.rechargeMoney + '&pageType=' + this.data.pageType });
      // Or rechargePayZy if pageType is zyjf.
      
      let url = '';
      if (pageType.value === 'mzjf') {
        url = `../rechargePay/rechargePay?orderId=${res.Data.OrderId}&payMoney=${rechargeMoney.value}&pageType=${pageType.value}`;
      } else {
         // Assuming rechargePayZy exists or logic is similar
         // rechargeMoney.js: 
         // if (this.data.pageType == 'mzjf') url = '../rechargePay/rechargePay?orderId=' + res.Data.OrderId ...
         // else url = '../rechargePayZy/rechargePayZy?orderId=' + res.Data.OrderId ...
         url = `../rechargePayZy/rechargePayZy?orderId=${res.Data.OrderId}&payMoney=${rechargeMoney.value}&pageType=${pageType.value}`;
      }
      common.goToUrl(url);
    } else {
      common.showToast(res.Message || '创建订单失败');
    }
  } catch (e) {
    common.hideLoading();
    common.showToast('网络异常，请稍后重试');
  }
};
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 40upx;
}

.recharge-money {
  background-color: #fff;
  margin-top: 20upx;
  padding: 30upx;
  
  &-title {
    font-size: 32upx;
    font-weight: bold;
    color: #333;
    margin-bottom: 30upx;
  }

  &-input {
    display: flex;
    align-items: center;
    border-bottom: 1upx solid #eee;
    padding-bottom: 20upx;
    margin-bottom: 30upx;

    &-val {
      flex: 1;
      font-size: 60upx;
      height: 80upx;
      margin-left: 10upx;
    }
  }

  &-symbol {
    font-size: 40upx;
    color: #333;
    font-weight: bold;
  }

  &-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
  }

  &-item {
    width: 48%;
    height: 100upx;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1upx solid #ddd;
    border-radius: 8upx;
    margin-bottom: 20upx;
    color: #333;
    font-size: 32upx;

    &.active {
      border-color: #007aff;
      color: #007aff;
      background-color: rgba(0, 122, 255, 0.1);
    }
  }
}

.recharge-btn {
  margin: 60upx 30upx;
  
  .btn {
    width: 100%;
    height: 90upx;
    line-height: 90upx;
    background-color: #007aff;
    color: #fff;
    font-size: 32upx;
    border-radius: 45upx;
    
    &:active {
      opacity: 0.8;
    }
  }
}

.recharge-tips {
  padding: 0 30upx;
  
  &-title {
    font-size: 28upx;
    color: #666;
    margin-bottom: 20upx;
  }

  &-item {
    font-size: 24upx;
    color: #999;
    line-height: 1.5;
    margin-bottom: 10upx;
  }
}

.placeholder-class {
  font-size: 32upx;
  color: #ccc;
}
</style>
