<template>
  <el-dialog
    title="MANUAL TOP UP"
    :visible="visible"
    custom-class="toptop-dialog"
    :before-close="hideDialog"
    :close-on-click-modal="false">
    <el-form
      ref="topUpForm"
      :model="this"
      :rules="rules"
      label-width="140px"
      label-position="right">
      <el-form-item
        label="Current User:">
        <el-input
          class="input-text"
          :value="userInfo.email"
          readonly/>
      </el-form-item>
      <el-form-item
        label="Current Amount:">
        <el-input
          class="input-text"
          :value="userInfo.credit"
          readonly/>
      </el-form-item>
      <el-form-item
        label="Top Up Amount:"
        prop="amount">
        <el-input
          class="input-text"
          v-model="amount"
          maxlength="5"
          :placeholder="userInfo.currencySymbol"/>
      </el-form-item>
      <div class="flexcc" style="padding-top: 20px;">
        <el-button
          class="cancel-button"
          @click="hideDialog">
          Cancel
        </el-button>
        <el-button
          type="primary"
          @click="clickTopUp"
          :loading="loading">
          Top Up
        </el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import api from '@/http/api/apiUser'
export default {
  name: "TopUp",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    userInfo: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      amount: "",
      rules: {
        amount: [{
          required: true,
          trigger: 'blur',
          message: 'Please type amount',
        }, {
          pattern: /^[1-9]+\d*\.?\d*$/,
          trigger: 'blur',
          message: 'Please type a correct number'
        }]
      },
      loading: false
    };
  },
  mounted() {
    
  },
  methods: {
    hideDialog() {
      this.amount = ""
      this.$emit("hide");
    },
    clickTopUp() {
      this.$refs.topUpForm.validate((valid) => {
        if (valid) {
          this.toTopUp();
        }
      })
    },
    toTopUp() {
      this.loading = true;
      api.userTopup({
        userPk: this.userInfo.userPk,
        amount: this.amount
      }).then(res => {
        this.loading = false;
        this.$message({
          message: res.msg,
          type: 'success',
        })
        this.amount = ""
        this.$emit("success")
      }).catch(err => {
        this.loading = false;
        this.$message({
          message: err,
          type: 'error',
        })
      })
    }
  }
}
</script>

<style>
  .toptop-dialog {
    width: 100%;
    padding: 0 10px;
    max-width: 520px;
  }
</style>