<template>
  <el-dialog v-model="visible" title="抽奖配置" width="600px">
    <el-form :model="form" label-width="120px" :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="autoCloseWeekend">
        <!-- 加一个tips -->
        <template #label>
          <div class="flex items-center gap-1">
            <span>自动关闭</span>
            <el-tooltip content="如果开启，则会在周末自动关闭抽奖" placement="top">
              <el-icon size="16"><IEpInfoFilled /></el-icon>
            </el-tooltip>
          </div>
        </template>
        <el-switch
          v-model="form.autoCloseWeekend"
          :active-value="1"
          :inactive-value="0"
          active-text="是"
          inactive-text="否"
        />
      </el-form-item>
      <!-- 报名时间 整点 -->
      <el-form-item label="报名时间" prop="registrationRangeTime">
        <el-time-picker
          v-model="form.registrationRangeTime"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          is-range
          format="HH:mm"
          value-format="HH:mm"
        />
      </el-form-item>
      <!-- 报名费用 -->
      <el-form-item label="报名费用" prop="registrationFee">
        <el-input-number
          v-model="form.registrationFee"
          :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 { getLotteryConfigDetail, setLotteryConfig } from '@/api/backend'
import { useResetData } from '@/hooks'
import type { FormInstance, FormRules } from 'element-plus'
import { BooleanFlag } from '@/constants'
import { formatSeconds } from '@/utils'
import { push } from 'notivue'

const formRules: FormRules = {
  openRangeTime: [{ required: true, message: '请选择开放时间', trigger: 'change' }],
  autoCloseWeekend: [{ required: true, message: '请选择是否自动关闭', trigger: 'change' }],
  registrationRangeTime: [{ required: true, message: '请选择报名开始时间', trigger: 'change' }],
  registrationFee: [{ required: true, message: '请输入报名费用', trigger: 'change' }],
}

const [form, resetForm] = useResetData<{
  id: number | undefined
  openRangeTime: string[]
  autoCloseWeekend: BooleanFlag
  registrationRangeTime: string[]
  registrationFee: number
}>({
  id: undefined,
  openRangeTime: [],
  autoCloseWeekend: 1,
  registrationRangeTime: [],
  registrationFee: 0,
})

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

const formatRegistrationTime = (hour: number, minute = 0) =>
  `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`

const parseRegistrationTime = (time: string) => {
  const [hour = 0, minute = 0] = time.split(':').map(Number)

  return {
    hour,
    minute,
  }
}

const open = async () => {
  const { data } = await getLotteryConfigDetail()
  if (!data) {
    resetForm()
  } else {
    form.value = {
      id: data.id,
      openRangeTime: [String(data.startDate), String(data.endDate)],
      autoCloseWeekend: data.autoCloseWeekend,
      registrationRangeTime: [
        formatRegistrationTime(data.registrationStartHour, data.registrationStartMinute),
        formatRegistrationTime(data.registrationEndHour, data.registrationEndMinute),
      ],
      registrationFee: data.registrationFee,
    }
  }
  visible.value = true
}

const handleSubmit = async () => {
  await formRef.value?.validate()
  const registrationStartTime = parseRegistrationTime(form.value.registrationRangeTime[0]!)
  const registrationEndTime = parseRegistrationTime(form.value.registrationRangeTime[1]!)
  const data = {
    startDate: form.value.openRangeTime[0]!,
    endDate: formatSeconds(form.value.openRangeTime[1]!),
    autoCloseWeekend: form.value.autoCloseWeekend,
    registrationStartHour: registrationStartTime.hour,
    registrationStartMinute: registrationStartTime.minute,
    registrationEndHour: registrationEndTime.hour,
    registrationEndMinute: registrationEndTime.minute,
    registrationFee: form.value.registrationFee,
  }
  loading.value = true
  try {
    await setLotteryConfig(data)
    push.success('保存成功')
    visible.value = false
  } catch (error) {
    console.error(error)
  } finally {
    loading.value = false
  }
}

defineExpose({
  open,
})
</script>
