<template>
  <div class="d-flex font-size-14 flex-wrap">
    <div v-for="val in items" :key="val.id" class="mr-5 cursor-pointer mb-3" :class="{'active': val.active}" @click="handleFirst(val)">{{ val.nameCn }}</div>
  </div>
  <div class="mt-3 font-size-14 mb-3">
    <span 
      v-for="k in children" 
      :key="k.id" 
      class="d-inline-block mr-10 cursor-pointer color-666 mb-2" 
      :class="{'active': select.findIndex(e => e.id === k.id) !== -1}"
      @click="handleSecond(k)"
    >{{ k.nameCn }}</span>
  </div>
</template>

<script setup>
defineOptions({ name: 'search-screen-industry'})
import { ref, watch } from 'vue'
import { getDict } from '@/hooks/web/useDictionaries'

const emit = defineEmits(['select', 'clear'])
const props = defineProps({
  selectData: {
    type: Array,
    default: () => []
  },
  isClear: Boolean
})

const items = ref([])
const select = ref([])
const children = ref([])
getDict('positionTreeData', {}, 'positionTreeData').then(({ data }) => {
  if (!data) return
  items.value = data.map(e => {
    e.active = false
    return e
  })
})

watch(
  () => props.selectData,
  (val) => {
    select.value = val
  },
  { deep: true }
)

const handleFirst = (val) => {
  items.value.forEach(e => e.active = false)
  val.active = !val.active
  children.value = val.children || []
}

const handleSecond = (val) => {
  const index = select.value.findIndex(e => e.id === val.id)
  if (index !== -1) {
    select.value.splice(index, 1)
  } else select.value.push(val)
  emit('select', select.value)
}

watch(
  () => props.isClear,
  (val) => {
    if (!val) return
    select.value = []
    children.value = []
    items.value.forEach(e => e.active = false)
    emit('clear')
  }
)
</script>

<style scoped lang="scss">
.active {
  color: var(--v-primary-base);
  font-family: 'MiSans-Bold';
}
</style>
