<template>
  <Dialog title="招聘会门票设置" v-model="dialogVisible">
    <div class="mb-50px color-orange text-16px" style="display: flex; align-items: center;">
      <Icon :size="20" icon="ep:warning" class="mr-3px" />
      提示：不需要设置门票限制时则不需要填写以下内容
    </div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <el-form-item label="门票金额" prop="admissionPrice">
        <el-input-number v-model="formData.admissionPrice" :precision="2" :min="0.01" :step="100" />
				<span class="mx-10px">元</span>
				<Icon @click="formData.admissionPrice = null" class="cursor-pointer" :size="25" icon="ep:circle-close-filled" /> 
      </el-form-item>
      <el-form-item label="可发布职位数量" prop="allowedJobNum">
        <el-input-number v-model="formData.allowedJobNum" :min="0" :step="10" />
				<span class="mx-10px">个</span>
				<Icon @click="formData.allowedJobNum = null" class="cursor-pointer" :size="25" icon="ep:circle-close-filled" /> 
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
defineOptions({ name: 'JobFairManageTicketSettings' })
import { JobFairManageApi } from '@/api/menduner/system/jobFair/manage'

const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  admissionPrice: undefined,
  allowedJobNum: undefined
})
const formRules = reactive({
  // admissionPrice: [{ required: true, message: '门票金额不能为空', trigger: 'change' }],
  // allowedJobNum: [{ required: true, message: '企业可发布职位不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (data: Object) => {
  dialogVisible.value = true
  resetForm()
	formData.value = data || {}
	if (formData.value.admissionPrice > 0) formData.value.admissionPrice = formData.value.admissionPrice / 100
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()

	const { id, admissionPrice, allowedJobNum } = formData.value
	const params = {
		id,
		admissionPrice: admissionPrice > 0 ? (admissionPrice * 100) : null,
		allowedJobNum
	}

  // 提交请求
  formLoading.value = true
  try {
    await JobFairManageApi.updateTicketSettings(params)
    message.success('设置成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    admissionPrice: undefined,
    allowedJobNum: undefined
  }
  formRef.value?.resetFields()
}
</script>