<template>
  <div style="width: 100%;">
    <CtForm ref="formPageRef" :items="items"></CtForm>
  </div>
</template>

<script setup>
import { getDict } from '@/hooks/web/useDictionaries'
defineOptions({name: 'necessaryInfo-InfoForm'})
import { reactive, ref } from 'vue'
import { checkEmail } from '@/utils/validate'
import { enterpriseSearchByName } from '@/api/recruit/personal/resume'

const props = defineProps({
  option: {
    type: Object,
    default: () => {}
  }
})
const setInfo = ref(props.option?.setInfo ? props.option.setInfo : {})
// console.log(1, 'setInfo', setInfo)
const formPageRef = ref()
let query = reactive({})

// 企业名称下拉列表
let enterpriseName = null
// const enterpriseNameInput = ref('')
const getEnterpriseData = async (name) => {
  const item = items.value.options.find(e => e.key === 'enterpriseId')
  if (!item) return
  if (item.items?.length && (enterpriseName === name)) return // 防抖
  // item[item.itemTextName] = 
  enterpriseName = name
  if (name === null || name === '') { item.items = [] }
  else {
    const data = await enterpriseSearchByName({ name })
    item.items = data
  }
}

let positionName = null
const items = ref({
  options: [
    {
      type: 'text',
      key: 'name',
      value: '',
      default: null,
      label: '姓名 *',
      outlined: true,
      rules: [v => !!v || '请输入姓名']
    },
    {
      type: 'autocomplete',
      key: 'sex',
      value: '1', // '1' ? '男' : '女'
      default: '1',
      label: '性别 *',
      outlined: true,
      dictTypeName: 'menduner_sex',
      rules: [v => !!v || '请选择性别'],
      items: []
    },
    {
      type: 'phoneNumber',
      key: 'phone',
      value: '',
      clearable: true,
      label: '联系手机号 *',
      rules: [v => !!v || '请填写联系手机号']
    },
    {
      type: 'text',
      key: 'email',
      value: null,
      default: null,
      label: '常用邮箱',
      outlined: true,
      rules: [
        value => {
          if (value) return true
          return '请输入联系邮箱'
        },
        value => {
          if (value && !checkEmail(value)) return '请输入正确的电子邮箱'
          return true
        }
      ]
    },
    {
      type: 'datePicker',
      mode: 'date',
      labelWidth: 80,
      key: 'birthday',
      value: '1990-01-01',
      defaultValue: new Date(1990, 1, 1),
      label: '出生日期 *',
      disabledFutureDates: true,
      format: 'YYYY/MM/DD',
      flexStyle: 'mb-7',
      outlined: true,
      rules: [v => !!v || '请选择出生日期']
    },
    {
      type: 'combobox',
      key: 'enterpriseId',
      value: null,
      default: null,
      label: '任职企业名称（可填暂无）',
      outlined: true,
      clearable: true,
      canBeInputted: true, //
      itemTextName: 'enterpriseName',
      itemText: 'value',
      itemValue: 'key',
      // rules: [v => !!v || '任职企业名称（可填“暂无”）'],
      search: getEnterpriseData,
      items: []
    },
    {
      type: 'combobox',
      key: 'positionId',
      value: null,
      default: null,
      label: '任职职位名称（可填暂无）',
      outlined: true,
      clearable: true,
      canBeInputted: true, //
      itemTextName: 'positionName',
      itemText: 'nameCn',
      itemValue: 'id',
      dictTypeName: 'positionSecondData',
      // rules: [v => !!v || '任职职位名称（没有可填“暂无”）'],
      search: val => positionName = val,
      items: []
    },
    {
      type: 'autocomplete',
      key: 'interestedPositionList',
      value: null,
      default: null,
      label: '意向职位 *',
      outlined: true,
      itemText: 'nameCn',
      itemValue: 'id',
      multiple: true,
      dictTypeName: 'positionSecondData',
      rules: [v => !!v || '请选择意向职位'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'jobStatus',
      value: '',
      default: null,
      label: '求职状态 *',
      outlined: true,
      itemText: 'label',
      itemValue: 'value',
      dictTypeName: 'menduner_job_seek_status',
      rules: [v => !!v || '请选择求职状态'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'expType',
      value: '',
      default: null,
      label: '工作经验 *',
      outlined: true,
      itemText: 'label',
      itemValue: 'value',
      dictTypeName: 'menduner_exp_type',
      rules: [v => !!v || '请选择工作经验'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'eduType',
      value: '',
      default: null,
      label: '最高学历 *',
      outlined: true,
      itemText: 'label',
      itemValue: 'value',
      dictTypeName: 'menduner_education_type',
      rules: [v => !!v || '请选择最高学历'],
      items: []
    },
    //   label: '学制类型 *', menduner_education_system_type
  ]
})

// 获取字典内容
const getDictData = async (dictTypeName, key) => {
  const item = items.value.options.find(e => e.key === key)
  if (item) {
    const apiType = dictTypeName === 'positionSecondData' ? 'positionSecondData' : 'dict'
    const { data } = await getDict(dictTypeName, apiType === 'dict' ? null : {}, apiType)
    item.items = data
    // console.log(dictTypeName, '字典内容', data)
  }
}

const userInfo = ref(localStorage.getItem('userInfo') ? JSON.parse(localStorage.getItem('userInfo')) : {})
const baseInfo = ref(localStorage.getItem('baseInfo') ? JSON.parse(localStorage.getItem('baseInfo')) : {})
items.value.options.forEach((e) => {
  if (e.dictTypeName) getDictData(e.dictTypeName, e.key) // 查字典set options
  if (baseInfo.value && baseInfo.value[e.key]) e.value = baseInfo.value[e.key] // 人才信息回显
  if (userInfo.value && userInfo.value[e.key]) e.value = userInfo.value[e.key] // 人才信息回显
  if (e.key === 'sex' && e.value === '0') e.value = e.default
  if (setInfo.value[e.key]) e.value = setInfo.value[e.key]
})

// const getName = (obj, key) => {
//   const item = items.value.options.find(e => e.key === key)
//   if (!item && !item.value) return
//   const select = item.items.find(e => item.value === e[item.itemValue || 'value'])
//   if (select) {
//     obj[item.itemTextName] = select[item.itemText || 'label']
//   }
// }

const dealQuery = () => {
  query.positionName = positionName || null
  if (query.positionId === positionName) delete query.positionId  // 有选中id传id和name，否者只传name
  query.enterpriseName = enterpriseName || null
  if (query.enterpriseId === enterpriseName) delete query.enterpriseId  // 有选中id传id和name，否者只传name
  //
  if (query.interestedPositionList?.length) {
    query.interestedList = query.interestedPositionList.map(e => { return {positionId: e} })
  }
  query.workExpList = [{
    enterpriseId: query.enterpriseId,
    enterpriseName: query.enterpriseName || null,
    positionId: query.positionId,
    positionName: query.positionName || null,
  }]
}

const getQuery = async () => {
  const { valid } = await formPageRef.value.formRef.validate()
  if (!valid) return false
  const obj = {}
  items.value.options.forEach(e => {
    if (Object.prototype.hasOwnProperty.call(e, 'data')) return obj[e.key] = e.data
    obj[e.key] = e.value === '' ? null : e.value
  })
  query = Object.assign(query, obj)
  dealQuery()
  return query
}

defineExpose({
  getQuery
})
</script>