<template>
  <el-dialog
    width="700px"
    :title="`分销商余额${title}`"
    :before-close="handleClose"
    :visible.sync="visible"
  >
    <el-form
      inline
      :model="form"
      ref="form"
      label-width="180px">
      <div class="dialog-info">
        <el-form-item
          verify
          prop="amount"
          :label="`${title}金额(￥)`"
          style="width:100%">
          <el-input-number
            :step="0.01"
            :precision="2"
            v-model="form.amount"></el-input-number>
        </el-form-item>
      </div>

      <div class="dialog-btn-wrap">
        <el-button
          @click="submit"
          :loading="loading"
          type="primary">保存</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script>
import { otaAmount } from '@/api/ota'
export default {
  data () {
    return {
      visible: false,
      type: 'recharge', // recharge: 充值, decrease: 扣款
      moneyTimes: 0,
      loading: false,
      form: {
        otaSourceId: '',
        amount: 0
      }
    }
  },
  computed: {
    // 充值或扣款的标题
    title () {
      return this.type === 'recharge' ? '充值' : '扣款'
    }
  },
  methods: {
    show (data, type = 'recharge') {
      this.type = type
      this.visible = true
      this.moneyTimes = 1 // 显示充值弹窗后允许且只允许充值一次
      this.form.otaSourceId = data.otaSourceId
      this.form.amount = 0
    },
    handleClose () {
      this.visible = false
    },
    submit () {
      // 若不作限制，会出现可以连点可以充值多次的情况;充值只能允许发一次请求
      if (this.moneyTimes <= 0) return
      this.moneyTimes = 0
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true
          otaAmount(this.type, this.form).then(res => {
            this.loading = false
            this.$message.success('修改成功')
            this.handleClose()
            this.$emit('update')
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
