<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <!-- 第一行 -->
        <el-col :span="8">
          <el-form-item label="用户姓名" prop="userName">
            <el-input v-model="formData.userName" placeholder="请输入用户姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="手机号" prop="phoneNumber">
            <el-input v-model="formData.phoneNumber" placeholder="请输入手机号" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="活动名称" prop="activityId">
            <el-select v-model="formData.activityId" placeholder="请选择活动名称">
              <el-option
                v-for="activity in activityNames"
                :key="activity.id"
                :label="activity.activityTitle"
                :value="activity.id"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 第二行 -->
        <el-col :span="8">
          <el-form-item label="公司名称" prop="companyName">
            <el-input v-model="formData.companyName" placeholder="请输入公司名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="职位" prop="position">
            <el-input v-model="formData.position" placeholder="请输入职位" />
          </el-form-item>
        </el-col>
<!--        <el-col :span="8">-->
<!--          <el-form-item label="活动场所" prop="operationPlatform">-->
<!--            <el-select v-model="formData.operationPlatform" placeholder="请选择活动场所">-->
<!--              <el-option-->
<!--                v-for="dict in getStrDictOptions(DICT_TYPE.PROMOTION_REGISTRATION_OPERATION_PLATFORM)"-->
<!--                :key="dict.value"-->
<!--                :label="dict.label"-->
<!--                :value="dict.value"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->

        <!-- 第三行 -->
        <el-col :span="8">
          <el-form-item label="主营品类" prop="mainCategory">
            <el-select v-model="formData.mainCategory" placeholder="请选择主营品类">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PROMOTION_REGISTRATION_MAIN_CATEGORY)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="代理城市" prop="agencyCity">
            <el-select v-model="formData.agencyCity" placeholder="请选择代理城市">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PROMOTION_REGISTRATION_AGENCY_CITY)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="产品意向" prop="productIntent">
            <el-select v-model="formData.productIntent" placeholder="请选择产品意向">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PROMOTION_REGISTRATION_PRODUCT_INTENT)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 第四行 -->
        <el-col :span="8">
          <el-form-item label="参会目的" prop="purpose">
            <el-select v-model="formData.purpose" placeholder="请选择参会目的">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PROMOTION_REGISTRATION_PURPOSE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="参会身份" prop="attendeeIdentity">
            <el-select v-model="formData.attendeeIdentity" placeholder="请选择参会身份">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PROMOTION_REGISTRATION_ATTENDEE_IDENTITY)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="报名状态" prop="registrationStatus">
            <el-select v-model="formData.registrationStatus" placeholder="请选择报名状态">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PROMOTION_REGISTRATION_REGISTRATION_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 第五行 -->
        <el-col :span="8">
          <el-form-item label="核销码" prop="verificationCode">
            <el-input v-model="formData.verificationCode" placeholder="请输入核销码" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="核销状态" prop="verificationStatus">
            <el-select v-model="formData.verificationStatus" placeholder="请选择核销状态">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PROMOTION_REGISTRATION_VERIFICATION_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="是否付费" prop="isPaid">
            <el-select v-model="formData.isPaid" placeholder="请选择是否付费">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PROMOTION_REGISTRATION_IS_PAID)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <!-- 第六行 -->
        <el-col :span="8">
          <el-form-item label="审核状态" prop="reviewStatus">
            <el-select v-model="formData.reviewStatus" placeholder="请选择审核状态">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PROMOTION_REGISTRATION_REVIEW_STATUS)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </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">
import {  DICT_TYPE ,getStrDictOptions} from '@/utils/dict'
import { RegistrationApi, RegistrationVO } from '@/api/promotion/registration'
import { ActivityInfoVO} from "@/api/promotion/activityinfo"

/** 活动报名 表单 */
defineOptions({ name: 'RegistrationForm' })

const activityNames = ref<ActivityInfoVO[]>([]);

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  userName: undefined,
  phoneNumber: undefined,
  companyName: undefined,
  position: undefined,
  operationPlatform: undefined,
  mainCategory: undefined,
  agencyCity: undefined,
  productIntent: undefined,
  purpose: undefined,
  attendeeIdentity: undefined,
  activityId: undefined,
  activityTitle: undefined,
  registrationStatus: undefined,
  verificationCode: undefined,
  verificationStatus: undefined,
  isPaid: undefined,
  reviewStatus: undefined,
})
const formRules = reactive({
  userName: [{ required: true, message: '用户姓名不能为空', trigger: 'blur' }],
  phoneNumber: [{ required: true, message: '手机号不能为空', trigger: 'blur' }],
  registrationStatus: [{ required: true, message: '报名状态不能为空', trigger: 'change' }],
  activityId: [{ required: true, message: '活动id不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    console.log('id', id)
    formLoading.value = true
    try {
      formData.value = await RegistrationApi.getRegistration(id);
      const registration = await RegistrationApi.getRegistration(id); // 将返回值存储到 `registration` 变量中
      formData.value = { ...registration, activityId: registration.activityId }; // 正确引用 `registration`
      console.log('loaded registration:', formData.value);
    } finally {
      console.log('id查找失败', id)
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  console.log('submit form:', formData.value);
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RegistrationVO
    if (formType.value === 'create') {
      await RegistrationApi.createRegistration(data)
      message.success(t('common.createSuccess'))
    } else {
      await RegistrationApi.updateRegistration(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}


//初始化机构名称下拉框
const getActivityNames = async () => {
  try {
    const result = await RegistrationApi.getActivityNames();
    activityNames.value = result;
    console.log('activityNames:', activityNames.value);
  } catch (error) {
    console.error('获取活动名称失败:', error);
  }
}


/** 重置表单 */
const resetForm = () => {
  formData.value = {
    userName: undefined,
    phoneNumber: undefined,
    companyName: undefined,
    position: undefined,
    operationPlatform: undefined,
    mainCategory: undefined,
    agencyCity: undefined,
    productIntent: undefined,
    purpose: undefined,
    attendeeIdentity: undefined,
    activityId: undefined,
    activityTitle: undefined,
    registrationStatus: undefined,
    verificationCode: undefined,
    verificationStatus: undefined,
    isPaid: undefined,
    reviewStatus: undefined,
  }
  formRef.value?.resetFields()
}

/** 初始化 **/
onMounted(() => {
  getActivityNames()
  console.log("初始化成功！")
})
</script>
