<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" class="!w-60%">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <el-form-item label="招聘会标题" prop="title">
        <el-input v-model="formData.title" :rows="3" type="textarea" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="招聘会背景色" prop="backgroundColour">
        <div>
          <el-color-picker v-model="formData.backgroundColour" size="large" />
          <div>为了页面的美观性，请勿选择白色（#FFF / #FFFFFF）作为页面背景颜色</div>
        </div>
      </el-form-item>
      <el-form-item label="PC封面海报" prop="pcPreviewImg">
        <div>
          <UploadImg v-model="formData.pcPreviewImg" height="150px" width="300px" :fileSize="10" :validSpecifications="true" :maxWidth="800" :maxHeight="300" />
          <div class="flex" style="color: orange; align-items: center;"><Icon :size="20" icon="ep:warning" class="mr-3px" />提示：请上传宽800px*高300px规格的图片</div>
        </div>
      </el-form-item>
      <el-form-item label="小程序封面海报" prop="previewImg">
        <div>
          <UploadImg v-model="formData.previewImg" height="150px" width="300px" :fileSize="10" :validSpecifications="true" :maxWidth="750" :maxHeight="350" />
          <div class="flex" style="color: orange; align-items: center;"><Icon :size="20" icon="ep:warning" class="mr-3px" />提示：请上传宽750px*高350px规格的图片</div>
        </div>
      </el-form-item>
      <el-form-item label="PC顶部banner" prop="pcHeadImg">
        <div>
          <UploadImgs v-model="formData.pcHeadImg" :limit="20" />
          <div class="flex" style="color: orange; align-items: center;"><Icon :size="20" icon="ep:warning" class="mr-3px" />提示：请上传宽1920px*高553px规格的图片</div>
        </div>
      </el-form-item>
      <el-form-item label="小程序顶部banner" prop="headImg">
        <div>
          <UploadImgs v-model="formData.headImg" :limit="20" />
          <div class="flex" style="color: orange; align-items: center;"><Icon :size="20" icon="ep:warning" class="mr-3px" />提示：请上传宽750px*高350px规格的图片</div>
        </div>
      </el-form-item>
      <el-form-item label="招聘会分享海报" prop="shareImg">
        <UploadImg v-model="formData.shareImg" height="300px" width="250px" :fileSize="10" />
      </el-form-item>
      <el-form-item label="企业分享海报" prop="contentImg">
        <div>
          <UploadImg v-model="formData.contentImg" height="300px" width="250px" :fileSize="10" :validSpecifications="true" :maxWidth="540" :maxHeight="788" />
          <div class="flex" style="color: orange; align-items: center;"><Icon :size="20" icon="ep:warning" class="mr-3px" />提示：请上传宽540px*高788px规格的图片</div>
        </div>
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker v-model="formData.startTime" type="date" value-format="x" placeholder="选择开始时间" />
      </el-form-item>
      <el-form-item label="结束时间" prop="endTime">
        <el-date-picker v-model="formData.endTime" type="date" value-format="x" placeholder="选择结束时间" />
      </el-form-item>
      <!-- <el-form-item label="简历投递次数" prop="cvRelNum">
        <div>
          <el-input-number v-model="formData.cvRelNum" :min="1" :step="1" />
          <p>不填则默认为1次</p>
        </div>
      </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_STATUS)"
            :key="dict.value"
            :label="dict.value.toString()"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="类别" prop="category" @change="handleChangeCategory">
        <el-radio-group v-model="formData.category">
          <el-radio
            v-for="dict in categoryList"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="类别详情" prop="tag">
        <el-row v-for="(val, index) in formData.tag" :key="index" class="mb-10px">
          <el-col :span="8">
            <el-input v-model="val.title" clearable placeholder="请输入类别名称"/>
          </el-col>
          <el-col :span="10" class="mx-10px">
            <el-select v-model="val.value" filterable multiple placeholder="请选择类别数值" collapse-tags collapse-tags-tooltip>
              <el-option v-for="k in formData.category === '0' ? industry : position" :key="k.id" :label="k.nameCn" :value="k.id.toString()"/>
            </el-select>
          </el-col>
          <el-col :span="4">
            <el-button text circle @click="handleDelete(index)">
              <Icon icon="ep:close" />
            </el-button>
          </el-col>
        </el-row>
        <div>
          <el-button type="primary" @click="handleAdd"><Icon class="mr-5px" icon="ep:plus" />添加类别</el-button>
          <div>若填写了类别，请最少填写两项</div>
        </div>
      </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 { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { JobFairManageApi, JobFairManageVO } from '@/api/menduner/system/jobFair/manage'
import { PositionApi } from '@/api/menduner/system/position'
import { IndustryApi } from '@/api/menduner/system/industry'

/** 招聘会管理 表单 */
defineOptions({ name: 'JobFairManageForm' })

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({
  id: undefined,
  type: 1,
  title: undefined,
  headImg: [],
  pcHeadImg: [],
  backgroundColour: undefined,
  pcPreviewImg: undefined,
  previewImg: undefined,
  startTime: undefined,
  endTime: undefined,
  shareImg: undefined,
  contentImg: undefined,
  // cvRelNum: undefined,
  status: '0',
  category: '0',
  tag: []
})
const formRules = reactive({
  backgroundColour: [{ required: true, message: '招聘会背景颜色不能为空', trigger: 'change' }],
  previewImg: [{ required: true, message: 'PC封面海报不能为空', trigger: 'change' }],
  pcPreviewImg: [{ required: true, message: '小程序封面海报不能为空', trigger: 'change' }],
  headImg: [{ required: true, message: '小程序顶部banner图片不能为空', trigger: 'change' }],
  pcHeadImg: [{ required: true, message: 'PC顶部banner图片不能为空', trigger: 'change' }],
  shareImg: [{ required: true, message: '招聘会分享海报不能为空', trigger: 'change' }],
  contentImg: [{ required: true, message: '企业分享海报不能为空', trigger: 'change' }],
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
  status: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
  category: [{ required: true, message: '展示类别不能为空', trigger: 'blur' }]
})
const categoryList = [
  { label: '企业', value: '0' },
  { label: '招聘职位', value: '1' }
]
const formRef = ref() // 表单 Ref

// 职位类型
const position = ref([])
const getPositionList = async () => {
  const data = await PositionApi.getPositionList({})
  position.value = data || []
}
getPositionList()

// 企业行业类型
const industry = ref([])
const getIndustryList = async () => {
  const data = await IndustryApi.getIndustryList({})
  industry.value = data || []
  
}
getIndustryList()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await JobFairManageApi.getJobFair(id)
      if (!formData.value.tag || !formData.value.tag.length) {
        formData.value.tag = []
      }
      
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

// 切换类别时需将数据清空
const handleChangeCategory = () => {
  formData.value.tag.forEach(e => e.value = [])
}

const handleDelete = (index) => {
  formData.value.tag.splice(index, 1)
}

const handleAdd = () => {
  formData.value.tag.push({ title: '', value: [] })
}

// 效验内容是否填写完整
const checkObjectValues = (obj) => {
  for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
      if (obj[key] === undefined || obj[key] === null || obj[key] === '' || obj[key].length === 0) {
        return false
      }
    }
  }
  return true
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  if (['#ffffff', '#FFFFFF'].indexOf(formData.value.backgroundColour) !== -1) return message.warning('请勿将白色作为页面背景色')
  // 校验表单
  await formRef.value.validate()
  
  if (formData.value?.tag && formData.value?.tag.length > 0) {
    // 效验类别项是否填写完整
    const check = formData.value.tag.every(e => checkObjectValues(e))
    if (!check) return message.warning('请将类别详情中的项填写完整')
    if (formData.value.tag.length < 2) return message.warning('请至少填写两个类别详情')
    formData.value.tag.forEach(e => e.key = formData.value.category === '0' ? 'industryId' : 'positionId')
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as JobFairManageVO
    if (formType.value === 'create') {
      await JobFairManageApi.createJobFair(data)
      message.success(t('common.createSuccess'))
    } else {
      await JobFairManageApi.updateJobFair(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    type: 1,
    title: undefined,
    headImg: [],
    pcHeadImg: [],
    backgroundColour: undefined,
    pcPreviewImg: undefined,
    previewImg: undefined,
    startTime: undefined,
    endTime: undefined,
    shareImg: undefined,
    contentImg: undefined,
    status: '0',
    category: '0',
    tag: []
  }
  formRef.value?.resetFields()
}
</script>

<style>
.el-row {
  width: 100%;
}
</style>