<template>
  <Dialog title="添加白名单" v-model="dialogVisible" class="!w-80%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="企业别名" prop="enterpriseIds">
        <el-select
          v-model="formData.enterpriseIds"
          multiple
          size="large"
          filterable
          clearable
          remote
          tag-type="primary"
          :remote-method="remoteMethod"
          :loading="loading"
          placeholder="请输入企业别名进行查找"
        >
          <el-option
            v-for="(item, index) in enterpriseList"
            :key="index"
            :label="formatName(item.anotherName || item.name)"
            :value="item.id"
          >
            <span>{{ formatName(item.anotherName || item.name) }}</span>
          </el-option>
          <p v-if="showLoadMore" class="text-center color-lightblue cursor-pointer" @click="handleLoadMore">加载更多</p>
        </el-select>
      </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">
import { JobFairWhiteApi } from '@/api/menduner/system/jobFair/white'
import { formatName } from '@/utils'
import { EnterpriseApi } from '@/api/menduner/system/enterprise/message'

/** 招聘会 表单 */
defineOptions({ name: 'JobFairDetailsForm' })

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

const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  enterpriseIds: [],
  jobFairId: ''
})
const formRules = reactive({
  enterpriseIds: [{ required: true, message: '请选择要添加的企业', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref

const showLoadMore = ref(true) // 是否展示加载更多按钮
const loading = ref(false)
const enterpriseList = ref([])

const queryParams = reactive({
  pageNo: 1,
  pageSize: 20
})
const getEnterpriseList = async () => {
  const result = await EnterpriseApi.getEnterprisePage(queryParams)
  const list = result.list || []
  enterpriseList.value = enterpriseList.value.concat(list)
  if (enterpriseList.value.length === result.total) showLoadMore.value = false
}
getEnterpriseList()

const remoteMethod = async (query: string) => {
  if (query) {
    loading.value = true
    enterpriseList.value = []
    queryParams.pageNo = 1
    queryParams.anotherName = query
    await getEnterpriseList()
    loading.value = false
  }
}

const handleLoadMore = () => {
  queryParams.pageNo++
  getEnterpriseList()
}

/** 打开弹窗 */
const open = async (id: string) => {
  resetForm()
  formData.value.jobFairId = id
  dialogVisible.value = true
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  
  // 提交请求
  formLoading.value = true
  try {
    await JobFairWhiteApi.addJobFairWhiteList({ jobFairId: formData.value.jobFairId, enterpriseIds: formData.value.enterpriseIds.join(',') })
    message.success('添加成功')
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    enterpriseIds: [],
    jobFairId: ''
  }
  formRef.value?.resetFields()
}
</script>

<style scoped lang="scss">
:deep(.el-select__wrapper) {
  align-items: start;
  min-height: 100px;
}
</style>