<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
    <el-form :formData="formData" :rules="formRule">
      <el-form-item label="任务单数">
        <el-input-number v-model="formData.taskLimit" placeholder="请输入任务单数" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="submit" :disabled="submitDisable">确定</el-button>
      <el-button type="default" @click="dialogVisible = false">取消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts" name="CustomTaskTable">
import { createCustomTask, getCustomTaskByUserId } from '@/api/member/customTask'
import { ElMessage } from 'element-plus'

defineOptions({ name: 'CustomTaskTable' })
const emits = defineEmits(['success'])

const { t } = useI18n() // 国际化
const submitDisable = ref(false) // 提交按钮是否禁用

const formData = ref({
  userId: undefined,
  taskLimit: undefined
}) // 表单数据
const formRule = reactive({
  taskLimit: [{ type: 'number', required: true, message: '请输入任务单数', trigger: 'burl' }]
})
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  formData.value.userId = id as any
  await initTaskLimit()
  dialogVisible.value = true
  dialogTitle.value = t('member.customTask.' + type)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 获取今天的任务数量
const initTaskLimit = async () => {
  const data = await getCustomTaskByUserId(formData.value)
  formData.value.taskLimit = data.taskLimit
}

const submit = async () => {
  submitDisable.value = true
  try {
    await createCustomTask(formData.value)
    ElMessage.success(t('common.success'))
    dialogVisible.value = false
    emits('success')
  } finally {
    submitDisable.value = false
  }
}
</script>
