<template>
  <div style="width: 100%;">
    <CtForm ref="formPageRef" :items="items" style="width: 600px;">
      <template #tagList>
        <div>
          <span style="color: #797474;">职位关键字：</span>
          <v-chip class="cursor-pointer mr-2 mb-3" color="primary" variant="outlined" @click="show = true; select = tag">
            <v-icon>mdi-plus</v-icon>
          </v-chip>
          <v-chip v-for="(val, index) in tag" :key="index" class="mr-2 mb-3" color="primary">
            {{ val }}
          </v-chip>
        </div>
      </template>
    </CtForm>
  </div>

  <CtDialog :visible="show" :widthType="3" titleClass="text-h6" title="职位关键字选择" :footer="true" @close="show = false" @submit="handleSubmit">
    <div>已选中关键字：</div>
    <div v-if="select.length">
      <v-chip
        v-for="(item, index) in select" :key="index"
        class="chip mr-2 mt-4"
        label color="#ea8d03"
      >
        {{ item }}
        <v-icon size="18" color="#ea8d03" style="margin-left: 6px;" @click="handleCancelSelect(item)">mdi-close-circle</v-icon>
      </v-chip>
    </div>
    <v-divider class="my-5"></v-divider>
    <div v-for="val in tagList" :key="val.id" class="mb-8">
      <span style="font-size: 16px;">{{ val?.nameCn || '--' }}</span>
      <div v-if="val?.children?.length">
        <v-chip 
          v-for="k in val.children" 
          :key="k.id"
          class="mx-2 mt-4 cursor-pointer"
          :text="k.nameCn"
          variant="outlined"
          color="primary"
          :value="k.id"
          label
          :disabled="select.includes(k.nameCn)"
          @click="handleSelect(k.nameCn)"
        >
          <v-icon icon="mdi-plus" start></v-icon>
          {{ k?.nameCn || '--' }}
        </v-chip>
      </div>
    </div>
  </CtDialog>
</template>

<script setup>
defineOptions({ name: 'position-add-job-requirements'})
import CtForm from '@/components/CtForm'
import { reactive, ref, watch } from 'vue'
import { getDict } from '@/hooks/web/useDictionaries'
import { cityToProvince } from '@/utils/areaDeal'
import { getTagTreeDataApi } from '@/api/enterprise'

const props = defineProps({
  itemData: Object
})

const formPageRef = ref()
let query = reactive({})
const items = ref({
  options: [
    {
      type: 'autocomplete',
      key: 'type',
      value: null,
      label: '招聘类型 *',
      itemText: 'label',
      itemValue: 'value',
      col: 4,
      dictTypeName: 'menduner_job_type',
      rules: [v => !!v || '招聘类型'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'eduType',
      value: null,
      label: '学历要求 *',
      itemText: 'label',
      itemValue: 'value',
      col: 4,
      flexStyle: 'mx-3',
      dictTypeName: 'menduner_education_type',
      rules: [v => !!v || '请选择学历要求'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'expType',
      value: null,
      label: '工作经验 *',
      itemText: 'label',
      itemValue: 'value',
      col: 4,
      dictTypeName: 'menduner_exp_type',
      rules: [v => !!v || '请选择工作经验'],
      items: []
    },
    {
      type: 'number',
      key: 'payFrom',
      value: '',
      col: 4,
      label: '最低薪资 *',
      suffix: '元',
      rules: [
        value => {
          if (value) return true
          return '请填写最低薪资'
        },
        value => {
          if (value >= 1) return true
          return '数额不得小于1'
        },
        value => {
          const payTo = items.value.options.find(e => e.key === 'payTo').value
          if (Number(value) < payTo ? Number(payTo) : 0) return true
          return '应低于最高薪资'
        }
      ]
    },
    {
      type: 'number',
      key: 'payTo',
      value: '',
      col: 4,
      label: '最高薪资 *',
      flexStyle: 'mx-3',
      suffix: '元',
      rules: [
        value => {
          if (value) return true
          return '请填写最高薪资'
        },
        value => {
          if (value >= 1) return true
          return '数额不得小于1'
        },
        value => {
          const payFrom = items.value.options.find(e => e.key === 'payFrom').value
          if (Number(value) > payFrom ? Number(payFrom) : 0) return true
          return '应高于最低薪资'
        }
      ]
    },
    {
      type: 'autocomplete',
      key: 'payUnit',
      value: null,
      label: '计薪时段 *',
      itemText: 'label',
      itemValue: 'value',
      col: 4,
      dictTypeName: 'menduner_pay_unit',
      rules: [v => !!v || '请选择计薪时段'],
      items: []
    },
    {
      type: 'autocomplete',
      key: 'workAreaProvinceId',
      value: null,
      label: '工作城市：省 *',
      outlined: true,
      itemText: 'name',
      itemValue: 'id',
      returnSelect: true,
      noParam: true,
      col: 6,
      flexStyle: 'mr-3',
      rules: [v => !!v || '请选择工作城市：省'],
      items: [],
      change: null
    },
    {
      type: 'autocomplete',
      key: 'areaId',
      value: null,
      label: '工作城市：市 *',
      outlined: true,
      itemText: 'name',
      itemValue: 'id',
      col: 6,
      rules: [v => !!v || '请选择工作城市：市'],
      items: [],
      change: null
    },
    {
      type: 'text',
      key: 'address',
      value: '',
      label: '详情地址 *',
      rules: [v => !!v || '请填写详细地址'],
    },
    {
      slotName: 'tagList',
      key: 'tagList',
      value: []
    }
  ]
})

// 招聘职位标签
const tagList = ref([])
const getTagList = async () => {
  const data = await getTagTreeDataApi({ type: 2 })
  tagList.value = data
}
getTagList()

// 获取字典内容
const getDictData = async () => {
  items.value.options.forEach(async (e) => {
    if (e.dictTypeName) {
      const { data } = await getDict(e.dictTypeName)
      e.items = data
    }
  })
}

const provinceChange = (value, val, obj) => {
  const item = items.value.options.find(e => e.key === 'areaId')
  if (!item) return
  item.items = obj.children || []
  item.value = null
}
getDict('areaTreeData', null, 'areaTreeData').then(({ data }) => {
  data = data?.length && data || []
  if (!data?.length) return console.error('areaTreeData获取失败！')
  // const china = data.find(e => e.id === '1')
  // const chinaTreeData = china?.children?.length ? china.children : []
  const chinaTreeData = data
  //
  if (!chinaTreeData?.length) return console.error('chinaTreeData获取失败！')
  const item = items.value.options.find(e => e.key === 'workAreaProvinceId')
  if (item?.items) {
    item.items = chinaTreeData
    item.change = provinceChange
  }
})

const getQuery = async () => {
  const { valid } = await formPageRef.value.formRef.validate()
  if (!valid) return
  const obj = {}
  items.value.options.forEach(e => {
    if (e.noParam) return
    if (e.key === 'tagList') {
      obj[e.key] = tag.value.length ? tag.value : []
    }
    else obj[e.key] = e.value
  })
  query = Object.assign(query, obj)
  return query
}

// 编辑回显
watch(
  () => props.itemData,
  async (val) => {
    await getDictData()
    if (!Object.keys(val).length) return
    // 编辑
    let workAreaId = ''
    items.value.options.forEach(e => {
      if (e.labelKey) {
        query[e.key] = val[e.key]
        e.value = val[e.labelKey]
        return
      }
      if (e.noParam) return
      e.value = val[e.key]
      if (e.key === 'areaId' && val[e.key]) workAreaId = val[e.key]
      if (e.key === 'tagList' && val[e.key] && val[e.key].length) {
        tag.value = val[e.key] && val[e.key].length ? val[e.key] : []
      }
    })
    if (workAreaId) { // 省份回显
      const province = items.value.options.find(pv => pv.key === 'workAreaProvinceId')
      if (province) {
        const dealReturnObj = await cityToProvince(workAreaId, {}, province.items || [])
        const city = items.value.options.find(pv => pv.key === 'areaId')
        if (city) city.items = dealReturnObj.cityList || []
        province.value = dealReturnObj.pid || ''
      }
    }
  },
  { immediate: true },
  { deep: true }
)


// 标签选择
const show = ref(false)
const select = ref([])
const tag = ref([])

// 选择
const handleSelect = (nameCn) => {
  const result = select.value.includes(nameCn)
  if (!result) return select.value.push(nameCn)
  else select.value = select.value.filter(e => e !== nameCn)
}

const handleSubmit = () => {
  tag.value = select.value
  show.value = false
}

// 取消选中
const handleCancelSelect = (nameCn) => {
  select.value = select.value.filter(e => e !== nameCn)
}

defineExpose({
  formPageRef,
  getQuery
})
</script>

<style scoped lang="scss">
.jobTypeCardBox {
  position: absolute;
  top: -22px;
  left: 0;
}
</style>
