<template>
    <!-- 搜索工作栏 -->
  <ContentWrap>
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入" clearable @keyup.enter="handleQuery" class="!w-160px" />
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入" clearable @keyup.enter="handleQuery" class="!w-160px" />
      </el-form-item>
      <el-form-item label="酒店品牌" prop="brand">
        <el-input v-model="queryParams.brand" placeholder="请输入" clearable @keyup.enter="handleQuery" class="!w-160px" />
      </el-form-item>
      <el-form-item label="最高学历" prop="eduType">
        <el-select
          v-model="queryParams.eduType"
          placeholder="请选择"
          clearable
          class="!w-160px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_EDUCATION_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工作经验" prop="expType">
        <el-select
          v-model="queryParams.expType"
          placeholder="请选择"
          clearable
          class="!w-160px"
        >
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MENDUNER_EXP_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所在城市" prop="areaIds">
        <el-cascader
          v-model="queryParams.areaIds" 
          :options="areaTreeData" 
          :props="{ label: 'name', value: 'id', multiple: true, emitPath: false }"
          collapse-tags
          collapse-tags-tooltip
          class="!w-160px"
        />
      </el-form-item>
      <el-form-item label="意向城市" prop="workAreaIds">
        <el-cascader
          v-model="queryParams.workAreaIds" 
          :options="areaTreeData" 
          :props="{ label: 'name', value: 'id', multiple: true, emitPath: false }"
          collapse-tags
          collapse-tags-tooltip
          class="!w-160px"
        />
      </el-form-item>
      <el-form-item label="意向职位" prop="positionIds">
        <el-cascader
          v-model="queryParams.positionIds"
          :options="positionTreeData"
          :props="{ label: 'nameCn', value: 'id', emitPath: false }"
          class="!w-160px"
          />
      </el-form-item>

      <el-form-item>
        <el-button @click="handleQuery" :loading="loading" type="primary"><Icon icon="ep:search" /> 搜索</el-button>
        <el-button @click="resetQuery" :loading="loading"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap v-if="addList?.length">
    <span style="color: #666;">已选择： </span>
    <el-tag v-for="(i, index) in addList" :key="i.id" closable type="success" style="margin: 5px 10px 5px 0;" @close="delAddTag(index)">
      {{ i.name_zh }}
    </el-tag>
    <div class="mt-10px text-end">
      <el-button type="primary" @click="emit('submit')">提交解析</el-button>
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap v-loading="loading">
    <div class="listBox">
      <div v-if="!loading && !list?.length" class="tip" style="line-height: 200px;">
        <div v-if="paramsBool">未查到任何数据，请更换查询条件后再试！</div>
        <div v-else>请输入查询条件！</div>
      </div>
      <personCard
        v-for="item of list"
        :key="item.id"
        :data="item"
        class="item"
        detailButTxt="+ 添加"
        @detail="detail"
      />
    </div>
    <div v-if="total">
      <Pagination
        :total="total"
        layout="total, prev, pager, next"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </ContentWrap>

</template>

<script setup>
defineOptions({ name: 'TalentMapSearch' })
import { TalentMap } from '@/api/menduner/system/talentMap'
import { PersonInfoApi } from '@/api/menduner/system/person'
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import personCard from './personCard.vue'
import { getDict } from '@/hooks/web/useDictionaries'
import { timesTampChange, timestampToAge } from '@/utils/transform/date'

const emit = defineEmits(['submit'])
const props = defineProps({
  paramsVerify: Boolean, // 查询条件必传
  searchName: String
})
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(false) // 列表的加载中
const list = ref([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 5,
  name: '',
  phone: undefined,
  brand: '',
  eduType: undefined,
  expType: undefined,
  areaIds: [],
  workAreaIds: [],
  positionIds: [],
})
const queryFormRef = ref() // 搜索的表单

// 地区列表
const areaTreeData = ref([])
const getDictData = async () => {
  const { data } = await getDict('areaTreeData', {}, 'areaTreeData')
  const obj = data.find(e => e.name === '中国')
  const list = obj?.children ? obj.children.map(e =>{
    // 市辖区直接显示区
    const municipality = e.children && e.children.length && e.children[0].name === '市辖区'
    if (municipality && e.children[0].children?.length) e.children = e.children[0].children
    return e
  }) : []
  areaTreeData.value = list.length ? list : []
}
getDictData()
const positionTreeData = ref([])
const getPositionTreeData = async () => {
  const { data } = await getDict('positionTreeData', {}, 'positionTreeData')
  positionTreeData.value = data || []
}
getPositionTreeData()

/** 查询列表 */
const getList = async () => {
  // if (loading.value) return message.warning('请勿频繁操作 ！')
  loading.value = true
  try {
    const data = await PersonInfoApi.getPersonInfoPage(queryParams)
    list.value = data?.list.map(e => {
      return {
        ...e.person,
        workExpList: e.work ? [e.work] : []
      }
    }) || []
    total.value = data?.total || 0
  } catch (error) {
    console.log('打印->error', error)
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const paramsBool = ref(false) // 是否存在筛选条件
/** 搜索按钮操作 */
const handleQuery = () => {
  const obj = { pageNo: null, pageSize: null, ...queryParams }
  paramsBool.value = Object.values(obj).some(value => value !== undefined && value !== null && value !== '' && value.length)

  if (props.paramsVerify && !paramsBool.value) return message.warning('请输入查询条件后再查询 ！')

  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

const getTypicalData = (row, expData) => {
  return {
    id: row.id,
    userId: row.userId,
    name_zh: row?.name || '',
    email: row?.email || '',
    mobile: row?.phone || '',
    birthday: row?.birthday ? timesTampChange(row.birthday, 'Y-M-D') : '',
    age: row?.birthday ? timestampToAge(row.birthday) : null,
    created_at: row?.createTime ? timesTampChange(row.createTime, 'Y-M-D') : null,
    updated_at: row?.updateTime ? timesTampChange(row.updateTime, 'Y-M-D') : null,
    career_path: expData ? expData.map(e => {
      return {
        hotel_zh: e?.enterpriseName || null,
        hotel_en: null,
        title_zh: e?.positionName || null,
        title_en: null,
        date: e?.startTime ? timesTampChange(e.startTime, 'Y-M-D') : null,
        source: null,
        image_path: null
      }
    }) : null
  }
}

const addList = ref([])
const detail = (row, expData) => {
  if (!row?.id || !row?.userId) {
    message.warning('添加失败 ！')
    return
  }
  if (addList.value.some(e => e.userId === row.userId)) {
    message.warning('已经被添加，请勿重复添加 ！')
    return
  }

  addList.value.push(getTypicalData(row, expData))
  message.success('已添加到选择列表！')
}
const delAddTag = (index) => {
  addList.value.splice(index, 1)
}

/** 初始化 **/
// onMounted(async () => {
//   if (props.paramsVerify) return
//   setTimeout(() => {
//     if (props.searchName) {
//       queryParams.name = props.searchName
//     }
//   }, 1000)
//   getList()
// })

if (!props.paramsVerify) getList()

defineExpose({
  addList
})
</script>

<style lang="scss" scoped>
.tip {
  text-align: center;
  margin-bottom: 10px;
  color: #e6a23c;
}
.listBox {
  min-height: 200px;
  max-height: calc(100vh - 400px);
  overflow-y: auto;
  padding: 10px;
  .item {
    margin-bottom: 10px;
  }
}
</style>