<template>
  <div>
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <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">
        <!-- 职位类型 -->
        <div v-if="formData.category === '1'" class="!w-100%">
          <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 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>
        <!-- 企业 -->
        <div v-if="formData.category === '0'" class="!w-100%">
          <div v-for="(val, index) in formData.tag" :key="index" class="mb-10px pa-20px" style="border: 1px solid #ccc;">
            <div style="display: flex; justify-content: space-between; align-items: center">
              <el-input v-model="val.title" clearable placeholder="请输入类别名称" class="!w-240px" />
              <div class="text-right">
                <el-button type="primary" class="mr-10px" @click="handleAddEnterprise(val, index)">添加企业</el-button>
                <el-button type="danger" @click="handleDelete(index)">删除</el-button>
              </div>
            </div>

            <el-table :data="val.value" :stripe="true">
              <el-table-column label="企业logo" align="center" prop="name">
                <template #default="scope">
                  <el-image v-if="scope.row?.logoUrl" :src="scope.row?.logoUrl" class="!w-50px !h-50px" />
                  <span v-else style="line-height: 70px; color: #999;">未上传</span>
                </template>
              </el-table-column>
              <el-table-column label="企业全称" align="center" prop="name">
                <template #default="scope">{{ formatName(scope.row?.name) }}</template>
              </el-table-column>
              <el-table-column label="企业别名" align="center" prop="anotherName">
                <template #default="scope">{{ formatName(scope.row?.anotherName) }}</template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button link type="danger" @click="handleDeleteTagItem(index, scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>

        <div>
          <el-button type="primary" @click="handleAdd"><Icon class="mr-5px" icon="ep:plus" />添加类别</el-button>
          <div class="color-red-400 mt-5px">若填写了类别，请最少填写两项</div>
        </div>
      </el-form-item>
    </el-form>
    
		<div class="text-right">
			<el-button @click="emit('close')">返回</el-button>
			<el-button @click="submitForm" type="primary" :disabled="formLoading">保存</el-button>
		</div>
  </div>

  <Dialog title="添加企业" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="addFormData"
      :rules="addFormRules"
      label-width="100px"
    >
      <el-form-item label="企业别名" prop="select">
        <el-select v-model="addFormData.select" value-key="id" multiple filterable clearable remote :remote-method="remoteMethod" :loading="loading" placeholder="请输入企业别称进行查找">
          <el-option v-for="(item, index) in enterpriseList" :key="index" :value="item" :label="formatName(item.anotherName || item.name)">
            <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="handleSubmitEnterprise" type="primary">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
/** 招聘会管理 信息设置 */
defineOptions({ name: 'JobFairManageInfoSettings' })
import { JobFairManageApi } from '@/api/menduner/system/jobFair/manage'
import { PositionApi } from '@/api/menduner/system/position'
import { cloneDeep } from 'lodash-es'
import { formatName } from '@/utils'
import { EnterpriseApi } from '@/api/menduner/system/enterprise/message'

const props = defineProps({ formType: String, info: Object })

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

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
  id: undefined,
  category: '0',
  tag: []
})
const formRules = reactive({
  category: [{ required: true, message: '展示类别不能为空', trigger: 'blur' }]
})
const categoryList = [
  { label: '企业', value: '0' },
  { label: '招聘职位', value: '1' }
]
const formRef = ref() // 表单 Ref

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

const queryParams = reactive({
  pageNo: 1,
  pageSize: 20
})
const addFormData = ref({
  select: [],
  index: 0
})
const addFormRules = reactive({
  // select: [{ required: true, message: '请选择企业', trigger: 'blur' }]
})
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
}


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 handleAddEnterprise = (val, index) => {
  console.log(val, index, 'add')
  addFormData.value = {
    select: val.value,
    index
  }
  getEnterpriseList()
  dialogVisible.value = true
}
// 添加企业-submit
const handleSubmitEnterprise = () => {
  const { select, index } = addFormData.value
  formData.value.tag[index].value = select
  dialogVisible.value = false
  addFormData.value = {}
}

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


onMounted(() => {
  getPositionList()
  if (props.info && Object.keys(props.info).length > 0) {
		formLoading.value = true
    formData.value.id = props.info.id
		if (!props.info.tag || !props.info.tag.length) {
			formData.value.tag = []
		} else {
      formData.value.tag = cloneDeep(props.info.tag)
    }
		formLoading.value = false
  }
})

// 切换类别时需将数据清空
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 handleDeleteTagItem = (index, tagItemIndex) => {
  formData.value.tag[index].value.splice(tagItemIndex, 1)
}

// 效验内容是否填写完整
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(['close'])
const submitForm = async () => {
  // 校验表单
  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' ? 'enterpriseId' : 'positionId')
  }

  // 提交请求
  formLoading.value = true
  try {
		await JobFairManageApi.updateJobFairCategory(formData.value)
		message.success(t('common.updateSuccess'))
  } finally {
    formLoading.value = false
  }
}

</script>

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