<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 v-if="item.label" class="activity-label">{{ item.label }}</view>
        <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 class="gift-tip" v-if="state.rechargeItem.grantsAmount > 0">
        <uv-icon class="gift-tip-icon" name="info-circle" size="14" color="#999"></uv-icon>
        <text class="gift-tip-text">赠金需在充值本金消耗完毕后使用，如申请退款将收回全部赠金，充值即视为同意活动规则，最终解释权归本平台所有。</text>
      </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: "",
  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;
      const defaultIdx = (res || []).findIndex((item: any) => item.isDefault);
      if (defaultIdx >= 0) {
        state.chosenIdx = defaultIdx;
        state.rechargeItem = res[defaultIdx];
      }
    })
    .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];
  const params: any = { rechargeConfigId: recharge.id };
  if (state.stationId) {
    params.stationId = state.stationId;
  }
  get("/payment/wxPay", params)
    .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 {
  position: relative;
  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;
  overflow: hidden;

  &: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);
  }
}

.activity-label {
  position: absolute;
  top: 0;
  right: 0;
  padding: 6rpx 16rpx;
  font-size: 20rpx;
  font-weight: 600;
  color: #FFFFFF;
  background: linear-gradient(135deg, #FF6B3D, #FF3D3D);
  border-radius: 0 12rpx 0 16rpx;
  line-height: 1.2;
  white-space: nowrap;
  z-index: 1;
}

.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: 36rpx;
        font-weight: $uni-font-weight-bold;
      }
    }
  }

  .gift-tip {
    display: flex;
    align-items: center;
    gap: 10rpx;
    margin-top: 20rpx;
    padding: 16rpx 20rpx;
    background-color: #f9f9f9;
    border-radius: 12rpx;

    .gift-tip-icon {
      flex-shrink: 0;
    }

    .gift-tip-text {
      font-size: 26rpx;
      color: #999;
      line-height: 1.5;
      flex: 1;
    }
  }
}

// 支付按钮区域
.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>
