<template>
  <div style="width:100%; height: 50px;background-color: #3700B3;"></div>

  <charge-notice-bar v-if="user.admin_contact" :contact="user.admin_contact" />
  <!-- 可以使用 CellGroup 作为容器 -->
  <van-cell-group>
    <van-cell size="large" title="账户余额" :value="user.balance ?? '--'" />
    <van-field v-model="chargeCode" center clearable label="充值" placeholder="请输入充值码" size="large">
      <template #button>
        <van-button size="small" type="primary" @click="confirmCharge">确认充值</van-button>
      </template>
    </van-field>
  </van-cell-group>

  <charge-code v-if="user.is_admin === true" />

  <balance-history ref="balanceHistory" />


</template>

<script setup>
import BalanceHistory from "@/components/BalanceHistory.vue";
import ChargeCode from "@/components/ChargeCode.vue";
import ChargeNoticeBar from "@/components/ChargeNoticeBar.vue";
import request from "@/utils/request";
import { ref } from 'vue';

const user = ref({});
const chargeCode = ref("")
const balanceHistory = ref(null);

const loadUserInfo = () => {
  request.get("/users/info").then((res) => {
    user.value = res.data;
  }).catch((err) => {
    console.log(err);
  });
};

onMounted(() => {
  loadUserInfo();
});


const confirmCharge = () => {
  if (!chargeCode.value) {
    return showFailToast('请输入充值码');
  }

  showConfirmDialog({
    title: '充值确认',
    message: "充值成功后此充值码将无法再次使用!",
  })
    .then(() => {
      request
        .patch(`/users/charge/${chargeCode.value}`)
        .then(() => {
          loadUserInfo();
          chargeCode.value = "";
          balanceHistory.value.loadHistories(); // Refresh BalanceHistory
          showSuccessToast('充值成功');
        })
        .catch((err) => {
          let message = err.response.data.message;
          showFailToast(message);
        });
    })
    .catch(() => {
      console.log("取消充值");
    });
};

</script>


<style>
.balance {
  padding: 2em 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: azure;
}

.balance .title {
  font-size: 1.5em;
  color: #666;
  padding-bottom: 1em;
}

.balance .num {
  font-size: 2em;
  color: #333;
  font-weight: bold;
}
</style>