<template>
  <uv-navbar title="充值" bgColor="#C6171E" leftIconColor="#FFFFFF" :titleStyle="{ color: '#FFFFFF' }" :autoBack="true" :placeholder="true"></uv-navbar>
  <view class="container">
    <view class="title">选择充值金额</view>

    <view class="amount-list">
      <view
        v-for="(item, index) in state.configList"
        :key="index"
        :class="['amount-item', { active: state.chosenIdx === index }]"
        @click="handleRechargeClick(item, index)"
      >
        <view class="amount-text">{{ (item.rechargeAmount / 100).toFixed(0) }}元</view>
        <view v-if="item.grantsAmount > 0" class="gift-tag">
          <uv-icon name="gift" size="12"></uv-icon>
          {{ (item.grantsAmount / 100).toFixed(0) }}元
        </view>
      </view>
    </view>

    <view class="selected-info" v-if="state.chosenIdx > -1">
      <view class="selected-row">
        <text class="selected-label">充值金额</text>
        <text class="selected-amount">¥{{ (state.configList[state.chosenIdx].rechargeAmount / 100).toFixed(2) }}</text>
      </view>
      <view class="selected-row gift-row" v-if="state.rechargeItem.grantsAmount > 0">
        <text class="selected-label">赠送金额</text>
        <view class="gift-value">
          <uv-icon name="gift" size="16"></uv-icon>
          <text class="gift-amount">+¥{{ (state.rechargeItem.grantsAmount / 100).toFixed(2) }}</text>
        </view>
      </view>
    </view>

    <view class="pay-area">
      <uv-button
        type="primary"
        shape="circle"
        iconColor="#FFFFFF"
        color="#C6171E"
        text="立即充值"
        :loading="paying"
        :disabled="state.chosenIdx < 0 || paying"
        @click="debounceConfirm"
      ></uv-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from "vue";
import { onHide, onLoad, onShow } from "@dcloudio/uni-app";
import { debounce } from "@/utils/common";
import { get } from "@/utils/https";

const initState = () => ({
  configList: [] as any[],
  chosenIdx: -1,
  stationId: "000",
  rechargeItem: { grantsAmount: 0 } as any,
});

const state = reactive(initState());
const paying = ref(false);

onLoad((options: any) => {
  if (options.stationId) {
    state.stationId = options.stationId;
  }
});

onShow(() => {
  loadRechargeConfig();
});

onHide(() => {
  state.chosenIdx = -1;
  state.configList = [];
  state.rechargeItem = { grantsAmount: 0 };
});



const handleRechargeClick = (recharge: any, idx: number) => {
  state.chosenIdx = idx;
  state.rechargeItem = state.configList[idx];
};

const loadRechargeConfig = () => {
  // 优先使用归属站，无归属站时用当前消费站，都没有则不传（走默认分组）
  const homeStationId = getApp<any>().globalData.user?.stationId;
  const stationId = homeStationId || state.stationId || undefined;
  const params: any = {};
  if (stationId) {
    params.stationId = stationId;
  }
  get("/common/rechargeConfig", params)
    .then((res: any) => {
      state.configList = res;
    })
    .catch(() => {
      uni.showToast({ title: "加载失败，请下拉重试", icon: "none" });
    });
};

const debounceConfirm = debounce(() => {
  confirm();
}, 500);

const confirm = () => {
  if (state.chosenIdx < 0) return;

  paying.value = true;
  uni.showLoading({ title: "支付中..." });

  const recharge = state.configList[state.chosenIdx];
  get("/payment/wxPay", {
    rechargeConfigId: recharge.id,
    stationId: state.stationId,
  })
    .then((res: any) => {
      // #ifdef MP-WEIXIN
      wx.requestPayment({
        timeStamp: `${res.timeStamp}`,
        nonceStr: res.nonceStr,
        package: res.packageVal,
        signType: res.signType,
        paySign: res.paySign,
        success: () => {
          uni.showToast({ title: "充值完成", icon: "success" });
          getApp<any>().globalData.refresh = true;
          setTimeout(() => {
            uni.switchTab({ url: "/pages/user/index" });
          }, 500);
        },
        fail: () => {
          uni.hideLoading();
          uni.showToast({ title: "支付取消", icon: "none" });
        },
      });
      // #endif
      // #ifndef MP-WEIXIN
      uni.hideLoading();
      uni.showToast({ title: "目前仅支持微信支付", icon: "none" });
      // #endif
    })
    .catch(() => {
      uni.hideLoading();
      uni.showToast({ title: "网络异常，请重试", icon: "none" });
    })
    .finally(() => {
      paying.value = false;
    });
};
</script>

<style lang="scss" scoped>
.container {
  padding: 40rpx 30rpx;
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: $uni-bg-color-page;
  box-sizing: border-box;
}

.title {
  font-size: 28rpx;
  text-align: center;
  margin-bottom: 48rpx;
  font-weight: $uni-font-weight-semibold;
  color: $uni-text-color;
}

// 金额选择网格
.amount-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin-bottom: 48rpx;
  width: 100%;
  box-sizing: border-box;
}

.amount-item {
  background-color: $uni-bg-color-card;
  padding: 24rpx 12rpx;
  text-align: center;
  border: 2rpx solid $uni-border-color;
  border-radius: 16rpx;
  color: $uni-text-color;
  min-height: 128rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  box-sizing: border-box;
  transition: transform 0.15s ease, background-color 0.15s ease;

  &:active {
    transform: scale(0.96);
  }

  &.active {
    background-color: $uni-color-primary;
    color: $uni-text-color-inverse;
    border-color: $uni-color-primary;
    transform: scale(1.03);
  }
}

.amount-text {
  font-size: 32rpx;
  font-weight: $uni-font-weight-bold;
  line-height: 1;
}

// 赠金标签 — 金额下方的小字标签，与卡片内联而非悬浮角标
.gift-tag {
  display: inline-flex;
  align-items: center;
  gap: 4rpx;
  font-size: 24rpx;
  font-weight: $uni-font-weight-medium;
  color: $uni-color-primary;
  line-height: 1;
}

.amount-item.active .gift-tag {
  color: rgba(255, 255, 255, 0.85);
}

// 已选信息
.selected-info {
  background-color: $uni-bg-color-card;
  border-radius: 16rpx;
  padding: 32rpx;
  margin-bottom: 48rpx;

  .selected-row {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 8rpx 0;

    .selected-label {
      font-size: 26rpx;
      color: $uni-text-color-secondary;
    }

    .selected-amount {
      font-size: 36rpx;
      font-weight: $uni-font-weight-bold;
      color: $uni-text-color;
    }
  }

  .gift-row {
    margin-top: 16rpx;
    padding-top: 20rpx;
    border-top: 1rpx solid $uni-border-color-light;

    .gift-value {
      display: flex;
      align-items: center;
      gap: 8rpx;
      color: $uni-color-primary;

      .gift-amount {
        font-size: 28rpx;
        font-weight: $uni-font-weight-semibold;
      }
    }
  }
}

// 支付按钮区域
.pay-area {
  width: calc(100vw - 60rpx);
  position: fixed;
  bottom: 40rpx;
  bottom: calc(40rpx + constant(safe-area-inset-bottom));
  bottom: calc(40rpx + env(safe-area-inset-bottom));
  left: 30rpx;
}
</style>
