<template>
  <view class='content'>
    <view class='balance-view'>
      <image :src='assetsUrl("bg_member_recharge.png")' />
      <view class='balance-content'>
        <text>累计余额（元）</text>
        <text>￥{{ userInfo?.totalIncoming }}</text>
      </view>
      <view class='balance-content'>
        <text>当前余额（元）</text>
        <text class='accent-text-color'>￥{{ userInfo?.balance }}</text>
      </view>
    </view>

    <view class='recharge-option-card'>
      <view class='top-border'></view>
      <text class='title'>充值金额</text>
      <scroll-view scroll-y style='flex: 1;padding-bottom: 180rpx'>
        <view class='option-item' :class="{'option-item-active': currentIndex==index}"
              v-for='(item,index) in rechargeItems' :key='index' @click.stop='change(index)'>
          <image v-if='currentIndex==index' class='checked-image' src='/static/images/ic_recharge_checked.png' />
          <label class='amount-title'>{{ item.rechargeamount }}元</label>
          <view class='divider' style='margin-bottom: 36rpx' />
          <view class='card-view'>
            <view class='title-container'>
              <text>充值{{ item?.rechargeamount || 0 }}送{{ item?.rewardamount || 0
                }}元
              </text>
              <text class='accent-text-color'>
                实得{{ item?.rechargeamount + (item?.rewardamount) }}元
              </text>
            </view>
            <text class='description'>送{{ item.rewardamount || 0 }}元、送{{ item.rewardcouponamount || 0
              }}元优惠券共{{ item.rewardcouponnum || 0 }}张、
              返利{{ item.rewardrefundamount || 0 }}元
            </text>
          </view>
        </view>
      </scroll-view>
    </view>

    <view class='bottom-button-view'>
      <!--      <payment-button style='flex: 1' :payParams='buildSignParams'>-->
      <sqb-pay style='width: 100%;' @navigateTo='navigateTo'
               :return_url='buildSqbParams.return_url'
               :total_amount='buildSqbParams.total_amount'
               :terminal_sn='buildSqbParams.terminal_sn'
               :client_sn='buildSqbParams.client_sn'
               :subject='buildSqbParams.subject'
               :merchant_name='buildSqbParams.merchant_name'
               :notify_url='buildSqbParams.notify_url'
               :sign='buildSqbParams.sign'>
        <button class='primary-button'>充值</button>
      </sqb-pay>
      <!--      </payment-button>-->
    </view>
  </view>
</template>

<script lang='ts' setup>
import { assetsUrl } from '@/utils/assets';
import { useUserStore } from '@/store';
import { getRechargeList, preRecharge, rechargeVerify } from '@/api/user';
import { parseParameter, sortASCII } from '@/utils';
import { hexMD5 } from '@/utils/common/md5';
import { handlePayResult } from '@/utils/order';

const userState = useUserStore();
const { userInfo, terminalInfo } = storeToRefs(userState);

const rechargeOptionBackgroundUrl = assetsUrl('bg_member_recharge_item.png');

const rechargeItems = ref<{
  itemid: string
  rechargeamount: number
  rewardamount: number
  rewardcouponamount: number,
  rewardcouponnum: number
  rechargetype: number,
  rewardrefundamount: number
}[]>([]);
const currentIndex = ref<number>(0);
const preRechargeOrderId = ref();

onLoad(async () => {
  const { ruleitems } = await getRechargeList();
  rechargeItems.value = ruleitems;
  // rechargeItems.value.push(rechargeItems.value[0]);
  // rechargeItems.value.push(rechargeItems.value[0]);
  // rechargeItems.value.push(rechargeItems.value[0]);
  // rechargeItems.value.push(rechargeItems.value[0]);

  console.log(rechargeItems.value);
  await change(0);
});

const change = async (index: number) => {
  currentIndex.value = index;
  const { id } = await preRecharge({
    itemid: rechargeItems.value[index].itemid
  });
  preRechargeOrderId.value = id;
};

const buildSqbParams = computed(() => {
  const params = sortASCII({
    client_sn: preRechargeOrderId.value,
    return_url: '/pages/common/payresult/index',
    total_amount: Number(((rechargeItems.value[currentIndex.value]?.rechargeamount || 0) * 100).toFixed(2)),
    terminal_sn: terminalInfo.value.terminalSn,
    subject: '充值',
    merchant_name: terminalInfo.value.companyName,
    notify_url: 'https://www.baidu.com'
  }, true);
  return {
    ...params,
    sign: hexMD5(parseParameter(params) + '&key=' + terminalInfo.value.terminalKey).toUpperCase()
  };
});

const navigateTo = (e: any) => {
  handlePayResult(preRechargeOrderId.value, e, {
    onSuccess: async () => {
      await goRecharge();
      await userState.setUserInfo({
        ...userInfo.value,
        balance: Number(userInfo.value.balance) + Number(rechargeItems.value[currentIndex.value].rechargeamount) + Number(rechargeItems.value[currentIndex.value]?.rewardamount)
      });
      await uni.navigateBack();
    },
    onFailure: () => {
    }
  });
};

const goRecharge = async () => {
  // const result = await recharge({
  //   itemid: rechargeItems.value[currentIndex.value].itemid
  // });
  // console.log('platform recharge result ', result);
  await rechargeVerify({
    payid: preRechargeOrderId.value
  });
};
</script>

<style lang='scss' scoped>
.balance-view {
  display: flex;
  flex-direction: row;
  height: 280rpx;
  position: relative;

  image {
    width: 100%;
    height: 100%;
    position: absolute;
  }

  .balance-content {
    display: flex;
    flex-direction: column;
    position: relative;
    flex: 1;
    align-items: center;
    justify-content: center;

    color: white;

    text:nth-of-type(1) {
      font-size: 30rpx;
    }

    text:nth-of-type(2) {
      font-size: 40rpx;
      margin-top: 10rpx;
    }
  }
}

.recharge-option-card {
  display: flex;
  flex-direction: column;
  background: #F5F5F5;
  position: relative;
  //margin-top: -25rpx;

  .top-border {
    background: #FFFFFF;
    height: 30rpx;
    margin-top: -35rpx;
    border-radius: 30rpx 30rpx 0 0;
  }

  .title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333333;
    background: #FFFFFF;
    border-radius: 10rpx 10rpx 0 0;
    padding: 10rpx 20rpx 20rpx 20rpx;
    margin-bottom: 20rpx;
    margin-top: -15rpx;
  }

  .option-item {
    display: flex;
    flex-direction: column;
    margin: 10rpx 20rpx 20rpx 20rpx;
    background: #FFFFFF;
    border-radius: 20rpx;
    padding-top: 20rpx;
    box-sizing: border-box;
    border: solid #00000000 2rpx;
    position: relative;

    .amount-title {
      font-weight: bold;
      font-size: 40rpx;
      width: fit-content;
      color: #333333;
      margin-left: 30rpx;
    }

    .amount-title:after {
      content: "";
      display: block;
      border: 2rpx solid black;
    }

    .checked-image {
      width: 70rpx;
      height: 70rpx;
      position: absolute;
      right: 0;
      top: 0;
      border-radius: 0 18rpx 0 0
    }

    .card-view {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 167rpx;
      border-radius: 20rpx;
      //background-image: url(v-bind(rechargeOptionBackgroundUrl));
      background-image: url('https://img.lakeapp.cn/wx/images/bg_member_recharge_item.png');
      background-size: 100% 100%;
      justify-content: flex-start;
      color: #FFFFFF;

      .title-container {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        margin-top: 27rpx;
        padding: 0 30rpx;

        text:nth-of-type(1) {
          display: flex;
          font-size: 36rpx;
        }

        text:nth-of-type(2) {
          display: flex;
          font-size: 30rpx;
          align-items: center;
          justify-content: center;
          width: 185rpx;
          height: 50rpx;
          background: #FFFFFF;
          border-radius: 25rpx;
        }
      }

      .description {
        margin-top: 30rpx;
        margin-left: 30rpx;
      }
    }
  }

  .option-item-active {
    @extend .option-item;
    border: 2rpx solid #f95e5d;
  }
}
</style>
