<script setup>
import { ref } from 'vue'
// import { timeAddService } from '@/api/time'
import { userRechargeService } from '@/api/user'

const dialogVisible = ref(false)
const formData = new FormData()

// 组件对外暴露一个方法 open ，基于 open 传来的参数，区分添加还是编辑
const open = (id, username) => {
  formData.append('id', id)
  formData.append('username', username)
  console.log(username)

  dialogVisible.value = true
}
// 向外暴露
defineExpose({
  open
})

const emit = defineEmits(['success'])

// 金额选项
const selectEdOption = ref(0)
const options = ref([
  {
    label: 10.0,
    value: 10.0
  },
  {
    label: 20.0,
    value: 20.0
  },
  {
    label: 50.0,
    value: 50.0
  },
  {
    label: 100.0,
    value: 100.0
  },
  {
    label: 150.0,
    value: 150.0
  },
  {
    label: 200.0,
    value: 200.0
  }
])

const formDataDel = () => {
  formData.delete('id')
  formData.delete('amount')
  formData.delete('username')
}

// 提交充值信息
const onSubmit = () => {
  if (selectEdOption.value === 0) {
    ElMessage.info('请选择充值金额')
    return
  }
  ElMessageBox.confirm(
    '是否确认向 ' +
      formData.get('username') +
      ' 充值 ' +
      selectEdOption.value +
      ' 元？',
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      formData.append('amount', selectEdOption.value)
      await userRechargeService(formData)
      ElMessage({
        type: 'success',
        message: '充值成功'
      })
      dialogVisible.value = false
      formDataDel()
      selectEdOption.value = 0
      emit('success')
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '充值取消'
      })
      formDataDel()
      selectEdOption.value = 0
      dialogVisible.value = false
    })
}
</script>
<template>
  <el-dialog v-model="dialogVisible" title="充值" width="450" draggable>
    <el-select
      v-model="selectEdOption"
      placeholder="Select"
      size="large"
      style="width: 240px"
      @change="moneyChange"
    >
      <el-option
        v-for="item in options"
        :key="item.value"
        :label="item.label.toFixed(2)"
        :value="item.value"
      />
    </el-select>
    <el-button type="primary" style="margin-left: 30px" @click="onSubmit"
      >确认</el-button
    >
  </el-dialog>
</template>
