<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import type { ContestItem } from '../types'
import { ElMessage } from 'element-plus'
import { pick } from 'lodash-es'
import { createDrawLot, updateDrawLot } from '../api'

interface Props {
  data?: any
}
const props = defineProps<Props>()

const emit = defineEmits<{
  (e: 'update'): void
  (e: 'update:modelValue', visible: boolean): void
}>()

const detail = $ref(inject('detail') as ContestItem)

const formRef = $ref<FormInstance>()
const form = reactive<any>({
  competition_id: detail.id,
  type: '1',
  total: undefined
})
watchEffect(() => {
  if (!props.data) return
  Object.assign(form, props.data)
})

const rules = ref<FormRules>({
  total: [{ required: true, message: '请输入总桌数' }]
})
const isUpdate = $computed(() => {
  return !!props.data?.id
})
const title = $computed(() => {
  return isUpdate ? '编辑抽签加密' : '新增抽签加密'
})

// 提交
function handleSubmit() {
  formRef?.validate().then(() => {
    const params = Object.assign({}, pick(form, ['competition_id', 'total', 'type']))
    isUpdate ? handleUpdate(params) : handleCreate(params)
  })
}
// 新增
function handleCreate(params: any) {
  createDrawLot(params).then(() => {
    ElMessage({ message: '创建成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
// 修改
function handleUpdate(params: any) {
  params.id = props.data?.id
  updateDrawLot(params).then(() => {
    ElMessage({ message: '修改成功', type: 'success' })
    emit('update')
    emit('update:modelValue', false)
  })
}
</script>

<template>
  <el-dialog :title="title" :close-on-click-modal="false" width="600px" @update:modelValue="$emit('update:modelValue')">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="90px">
      <el-form-item label="考试类型" prop="type">
        <el-radio-group v-model="form.type" :disabled="isUpdate">
          <el-radio label="1">1+X理论考试</el-radio>
          <el-radio label="2">商业数据分析师实操考试</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="总桌数" prop="total">
        <el-input v-model="form.total"></el-input>
      </el-form-item>
      <el-form-item label="关联赛项">
        <el-input :value="detail.name" disabled></el-input>
      </el-form-item>
      <el-row justify="center">
        <el-button type="primary" round auto-insert-space @click="handleSubmit">保存</el-button>
        <el-button round auto-insert-space @click="$emit('update:modelValue', false)">取消</el-button>
      </el-row>
    </el-form>
  </el-dialog>
</template>
