<template>
  <view class="pl-30 pr-30">
    <view class="pay">
      <view class="title pt-30 pb-30">充值金额</view>
      <view class="flex-wrap">
        <view
            :class="[
            'option',
            'flex-center',
            `option-${index === payOption && !payValue ? 'active' : ''}`,
          ]"
            v-for="(item, index) in payOptions"
            :key="index"
            @click="changeOption(index)">
          <image
              v-if="payOptionsDiscount[index]"
              src="/static/images/coupon-center.png"
              mode="widthFix"
              class="tag fs-24 color-fff fw-500  width-40"
          />
          <!--          <view
                        class="tag fs-24 color-fff fw-500"
                        v-if="payOptionsDiscount[index]">{{ payOptionsDiscount[index] }}
                    </view>-->
          {{ item }}
        </view>
      </view>
      <view v-if="activityStationList&&activityStationList.length>0" class="flex-align-center" @click="handleShowActivityStationDialog">
        <view class="fs-30 color-666 pd-10" style="padding: 10px 0;">
          活动站点：{{activityStationList[0]}}
        </view>
        <view
            v-if="activityStationList.length>1"
            class="ml-12 color-primary fs-30">
          <text>更多</text>
        </view>
      </view>

      <view v-if="payOptionsDiscountDay[payOption]" class="flex-align-center">
        <view class="fs-30 color-666">
          {{ (payOptionsDiscount[payOption] && payOptionsDiscount[payOption] > 0) ? `享服务费${payOptionsDiscount[payOption]}折，` : '' }}权益有效期{{
            payOptionsDiscountDay[payOption]
          }}天
        </view>
        <view
            class="ml-12 color-primary fs-30"
            @click="to(`/pages-common/activity/activity?id=${activityId}`)">
          <text>详细规则</text>
          <text class="fs-24 ml-6">>></text>
        </view>
      </view>
      <view class="title pt-60 pb-30">自定义金额</view>
      <style-input
          :value="payValue > 0 ? payValue : ''"
          title="金额"
          type="digit"
          @input="input"/>
    </view>
  </view>

  <style-dialog
  v-if="stationVisible"
  title="活动站点"
  @close="stationVisible=false">
    <view class="activity-station">
      <view v-for="station in activityStationList" :key="station" class="activity-station-item">
        <text>{{station}}</text>
      </view>
    </view>

  </style-dialog>

  <style-bottom-view v-if="!stationVisible">
    <view class="pl-60 pr-60 pb-20">
      <style-button size="small" type="primary" @click="debounceConfirm">充值</style-button>
    </view>
  </style-bottom-view>
</template>

<script setup lang="ts">
import {ref} from "vue";
import {fetchProfile, insertMoney} from "../../api/user";
import {onLoad} from "@dcloudio/uni-app";
import {back, to} from "@/utils/navigate";
import {debounce} from "@/utils/util";
import StyleDialog from "@/components/style-dialog/style-dialog.vue";

const balance = ref(0);
const payOption = ref(3);
const payOptions = ref([30, 50, 100, 200, 500, 1000]);
const payOptionsDiscount = ref(["", "", "", "", "", ""]);
const payOptionsDiscountDay = ref([0, 0, 0, 0, 0, 0]);
const payValue = ref(0);
const activityId = ref();
const rechargeRightsId = ref();
const rechargeRightsList = ref([]);
const needBack = ref(false);
const activityStationList = ref([]);
const stationVisible = ref(false)


const handleShowActivityStationDialog = () => {
  console.log(stationVisible)
  if(activityStationList.value&&activityStationList.value.length>0){
    stationVisible.value = true;
    console.log(stationVisible)
  }
}

const input = (e: any) => {
  payValue.value = e.value;
  rechargeRightsId.value = 0;
};
const changeOption = (index: number) => {
  payValue.value = 0;
  payOption.value = index;
  let find = rechargeRightsList.value.find((k:any) => (k.amountMin || 0) / 100 === payOptions.value[index]);
  if (find) {
    rechargeRightsId.value = find?.id;
  }
};

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

const confirm = () => {
  if (payValue.value && !/^[0-9]*(\.\d{1,2})?$/.test(`${payValue.value}`)) {
    uni.showModal({
      title: "温馨提示",
      content: "请输入正确的金额",
      showCancel: false,
      confirmColor: "#2d9e95",
    });
    return;
  }
  const params = payValue.value
      ? Number(payValue.value)
      : payOptions.value[payOption.value];
  if (params > 10000 || params <= 0) {
    uni.showModal({
      title: "温馨提示",
      content: "每次最大充值金额10000，请修改金额",
      showCancel: false,
      confirmColor: "#2d9e95",
    });
    return;
  }
  uni.showLoading({
    title: "加载中",
  });
  insertMoney(params, rechargeRightsId.value)
      .then(() => {
        return fetchProfile();
      })
      .then((res) => {
        payValue.value = 0;
        balance.value = res.balance;
        uni.hideLoading();
        uni.showToast({
          title: "已支付",
          icon: "success",
        });
        setTimeout(() => {
          if (needBack.value) {
            back();
          } else {
            to("/pages-user/wallet/wallet");
          }
        }, 2000);
      })
      .catch((err) => {
        if (/cancel/.test(err.errMsg)) {
          return;
        }
        uni.showModal({
          content: `${err.errMsg},请重试`,
        });
      });
};


onLoad((options: any) => {
  console.log(options)
  if (options.value) {
    payOption.value = payOptions.value.findIndex(
        (item) => item === Number((Number(options.value) / 100).toFixed(2))
    );
    needBack.value = !!options.back;
  }

  if (options.discount) {
    payValue.value = Number((Number(options.discount) / 100).toFixed(2));
  }
  fetchProfile().then((res) => {
    // console.log(res);
    balance.value = res.balance;
    if (res && res.activityList && res.activityList.length) {
      let stationList = res.activityList[0].stationList;
      if(stationList&&stationList.length>0){
        activityStationList.value = stationList.map(k=>k.stationName)
      }

      res.activityList[0].rechargeRightsList.forEach((item: any) => {
        const val = Number((Number(item.amountMin) / 100).toFixed(2));
        const fi = payOptions.value.findIndex((o) => o === val);
        if (fi >= 0) {
          payOptionsDiscount.value[fi] = ((item.discount || 0) / 10).toFixed(1);
          payOptionsDiscountDay.value[fi] = item.validity > 0 ? item.validity : 1;
        }
      });
      if (res.activityList && res.activityList[0].rechargeRightsList && res.activityList[0].rechargeRightsList.length > 0) {
        rechargeRightsList.value = res?.activityList[0]?.rechargeRightsList
      }
      activityId.value = res.activityList[0].id;
    }
  });
});
</script>

<style lang="scss">
.pay {
  .title {
    font-weight: 500;
    font-size: 32rpx;
    color: #000;
  }

  .option {
    position: relative;
    width: 214rpx;
    height: 140rpx;
    background: var(--color-sec);
    border-radius: 10rpx;
    margin-left: 20rpx;
    margin-bottom: 20rpx;
    font-size: 36rpx;
    color: #000;
    font-weight: 500;
    //overflow: hidden;

    &:nth-child(3n + 1) {
      margin-left: 0;
    }

    .tag {
      position: absolute;
      top: -9px;
      right: -10px;
      padding: 2rpx 2rpx;
    }
  }

  .option-active {
    color: var(--color-primary);
    //border-color: var(--color-primary);
    //color: #fff;
    font-weight: 700;
  }
}

.activity-station{
  min-height: 450px;
  width: 100%;
  background-color: #f6f7fa;
  display: flex;
  flex-direction: column;
  align-items: center;
  align-content: center;

  &-item{
    margin: 8rpx 0;
      font-size: 15px;
  }
}
</style>
