<template>
  <div class="mt-10" 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>
      <template #salary>
        <div>
          <v-checkbox-btn
            v-model="salary"
            color="primary"
            label="薪资面议"
            class="ml-2"
            :disabled="false"
            style="width: 110px;"
            hide-details
            @update:modelValue="handleChangeSalary"
          ></v-checkbox-btn>
        </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 { getTagTreeDataApi } from '@/api/enterprise'
import { getEnterprisePubJobTypePermission } from '@/api/recruit/enterprise/position'

const props = defineProps({
  itemData: Object
})

// 薪酬
const rules = {
  payFrom: [
    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 (!payTo || (Number(value) < payTo ? Number(payTo) : 0)) return true
      return '应低于最高薪资'
    }
  ],
  payTo: [
    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 (!payFrom || (Number(value) > payFrom ? Number(payFrom) : 0)) return true
      return '应高于最低薪资'
    }
  ],
  payUnit: [v => !!v || '请选择计薪时段']
}

const formPageRef = ref()
let query = reactive({})
const items = ref({
  options: [
    {
      type: 'autocomplete',
      key: 'type',
      value: null,
      label: '招聘类型 *',
      itemText: 'key',
      itemValue: 'value',
      col: 4,
      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: 3,
      disabled: false,
      label: '最低薪资 *',
      defaultLabel: '最低薪资',
      suffix: '元',
      rules: rules.payFrom
    },
    {
      type: 'number',
      key: 'payTo',
      value: '',
      col: 3,
      disabled: false,
      label: '最高薪资 *',
      defaultLabel: '最高薪资',
      flexStyle: 'mx-3',
      suffix: '元',
      rules: rules.payTo
    },
    {
      type: 'autocomplete',
      key: 'payUnit',
      value: null,
      disabled: false,
      label: '计薪时段 *',
      defaultLabel: '计薪时段',
      itemText: 'label',
      itemValue: 'value',
      col: 3,
      dictTypeName: 'menduner_pay_unit',
      rules: rules.payUnit,
      items: []
    },
    {
      slotName: 'salary',
      col: 3,
      noParam: true
    },
    {
      type: 'cascade',
      key: 'areaId',
      value: null,
      default: null,
      label: '工作城市 *',
      checkStrictly: true,
      itemText: 'name',
      itemValue: 'id',
      clearable: false,
      items: [],
    },
    {
      type: 'text',
      key: 'address',
      value: '',
      label: '详情地址 *',
      rules: [v => !!v || '请填写详细地址'],
    },
    {
      slotName: 'tagList',
      key: 'tagList',
      value: []
    }
  ]
})

const getItem = (key) => {
  return items.value.options.find(e => e.key === key)
}

// 薪资面议
const salary = ref(false)
const arr = ['payFrom', 'payTo', 'payUnit']
const handleChangeSalary = (bool) => {
  arr.forEach(e => {
    const obj = getItem(e)
    obj.disabled = bool ? true : false
    obj.value = bool ? null : obj.value
    obj.label = bool ? obj.defaultLabel :  `${obj.defaultLabel} *`
    obj.rules = bool ? [] : rules[e]
  })
}

const getJobTypeList = async () => {
  const data = await getEnterprisePubJobTypePermission()
  if (!data || !data.length) return
  const jobTypeItem = items.value.options.find(e => e.key === 'type')
  if (jobTypeItem) jobTypeItem.items = data
  //  Snackbar.warning('没有该操作权限，请联系平台管理员升级后再试')
}
getJobTypeList()

// 招聘职位标签
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 = ['eduType', 'expType'].indexOf(e.key) !== -1 ? [{ label: '不限', value: -1 }, ...data] : data
    }
  })
}

getDict('areaTreeData', null, 'areaTreeData').then(({ data }) => {
  data = data?.length && data || []
  if (!data?.length) return console.error('areaTreeData获取失败！')
  const chinaTreeData = data
  if (!chinaTreeData?.length) return console.error('chinaTreeData获取失败！')
  const item = items.value.options.find(e => e.key === 'areaId')
  item.items = [{ name: '全国', id: -1 }, ...chinaTreeData]
})

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 if (['areaId', 'eduType', 'expType'].includes(e.key) && e.value === -1) obj[e.key] = null
    else obj[e.key] = e.value
  })
  if (obj.areaId === -1) obj.areaId = null
  query = Object.assign(query, obj)
  return query
}

// 编辑回显
watch(
  () => props.itemData,
  async (val) => {
    await getDictData()
    if (!Object.keys(val).length) return
    // 编辑
    items.value.options.forEach(e => {
      if (e.noParam) return
      e.value = 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 (['areaId', 'eduType', 'expType'].includes(e.key) && !val[e.key]) e.value = -1
      if (!val.payFrom && !val.payTo) {
        salary.value = true
        handleChangeSalary(salary.value)
      }
    })
  },
  { 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">
</style>
