<template>
  <el-dialog v-model="visible" title="抽奖配置" width="500px">
    <el-form :model="form" label-width="100px" :rules="formRules" ref="formRef">
      <el-form-item label="开放时间" prop="openRangeTime">
        <el-date-picker
          v-model="form.openRangeTime"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="X"
        />
      </el-form-item>
      <el-form-item label="参与费用" prop="costYaCoin">
        <el-input-number
          v-model="form.costYaCoin"
          :min="0"
          :max="1000000"
          controls-position="right"
        />
        <span class="ml-2">YA币</span>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getWheelConfig, setWheelConfig } from '@/api/backend'
import { useResetData } from '@/hooks'
import type { FormInstance, FormRules } from 'element-plus'
import { push } from 'notivue'
import { formatSeconds } from '@/utils'

const formRules: FormRules = {
  openRangeTime: [{ required: true, message: '请选择开放时间', trigger: 'change' }],
  costYaCoin: [{ required: true, message: '请输入参与费用', trigger: 'change' }],
}

const [form, resetForm] = useResetData<{
  openRangeTime: string[]
  costYaCoin: number
}>({
  openRangeTime: [],
  costYaCoin: 0,
})

const visible = ref(false)
const formRef = ref<FormInstance>()
const loading = ref(false)

const open = async () => {
  const { data } = await getWheelConfig()
  if (!data) {
    resetForm()
  } else {
    form.value = {
      openRangeTime: [String(data.startTime), String(data.endTime)],
      costYaCoin: data.costYaCoin,
    }
  }
  visible.value = true
}

const handleSubmit = async () => {
  await formRef.value?.validate()
  loading.value = true
  try {
    await setWheelConfig({
      startTime: form.value.openRangeTime[0]!,
      endTime: formatSeconds(form.value.openRangeTime[1]!),
      costYaCoin: form.value.costYaCoin,
    })
    push.success('保存成功')
    visible.value = false
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

defineExpose({ open })
</script>
