<!-- 增加或者减少余额弹窗 -->
<template>
  <el-dialog :title="`余额${form.type == 1 ? '增加' : '扣减'}`" width="400px" v-model="visible" @closed="onClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px" label-position="left">
      <el-form-item label="店铺名称">
        <el-input v-model="row.shopName" readonly style="width: 300px;"></el-input>
      </el-form-item>
      <el-form-item :label="`${form.type == 1 ? '充值' : '扣减'}金额`" prop="expense">
        <el-input v-model="form.expense" placeholder="请输入金额" style="width: 300px;"
          @input="e => form.expense = filterNumberInput(e)">
          <template #append>元</template>
        </el-input>
        <div>当前余额：<span style="color: red;">{{ multiplyAndFormat(row.money) }}</span></div>
      </el-form-item>
      <el-form-item label="扣减原因" v-if="form.type == 2" prop="reason">
        <el-input type="textarea" :rows="5" v-model="form.reason" placeholder="请输入扣减原因，必填 "></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="submitHandle" :loading="loading">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref } from 'vue'
import { smsMoneyChange } from '@/api/coupon'
import { ElNotification } from 'element-plus'
import { multiplyAndFormat, filterNumberInput } from '@/utils'

const visible = ref(false)

const loading = ref(false)
const formRef = ref(null)
const row = ref({
  shopName: '',
  money: 0
})
const form = ref({
  expense: '',
  type: 1,
  reason: ''
})

const rules = ref({
  expense: [
    {
      required: true,
      message: '请输入充值金额',
      triiger: 'blur'
    }
  ],
  reason: [
    {
      required: true,
      message: '请输入扣减原因',
      triiger: 'blur'
    }
  ]
})

function onClose() {
  form.value = {
    expense: '',
    type: 1,
    reason: ''
  }
  formRef.value.resetFields()
}

const emit = defineEmits(['success'])
function submitHandle() {
  formRef.value.validate(async (valid) => {
    try {
      if (valid) {
        loading.value = true
        await smsMoneyChange({
          shopId: row.value.shopId,
          ...form.value
        })
        emit('success')
        visible.value = false

        ElNotification({
          title: '注意',
          message: `${form.value.type == 1 ? '增加' : '扣减'}成功`,
          type: 'success'
        })
      }
    } catch (error) {
      console.log(error);
    }
    loading.value = false
  })
}

// 显示
function show(obj = {}, type = 1) {
  visible.value = true
  row.value = { ...obj }
  form.value.type = type
}

defineExpose({
  show
})
</script>