<template>
  <div v-if="show">
    <div v-for="(list, levelIndex) in treeList" :key="`select${levelIndex}`">
      <!-- 单选级别 -->
      <div v-if="levelIndex < props.multipleLevel">
        <span class="mr-1" @click="clear(list, levelIndex)">{{ $t('common.Unrestricted') }}</span>
        <span v-for="(item, itemIndex) in list" :key="item.id">
          <span
            v-if="itemIndex + 1 <= num"
            class="mx-3"
            :class="{'act': calcAct(item.id, levelIndex)}"
            style="line-height: 32px;"
            @click="handleNext({ item, index: levelIndex })"
          >{{ item.name }}</span>
        </span>
        <!-- 其他 -->
        <span v-if="list?.length > num" class="mx-3" style="line-height: 32px;" @click="handleShowOther({ list, index: levelIndex })">{{ $t('common.other') }}</span>
      </div>
      <!-- 多选级别 -->
      <div v-else class="embedded">
        <div
          v-for="item in list" :key="item.id"
          class="mx-3"
          :class="{'act': calcAct(item.id, levelIndex)}"
          style="line-height: 32px;"
          @click="handleNext({ item, index: levelIndex })"
        >{{ item.name }}</div>
      </div>
    </div>
  </div>
  <!-- 其他-弹窗 -->
  <CtDialog :visible="showDialog" :footer="false" :widthType="0" :title="$t('common.pleaseSelect')" @close="showDialog = false">
    <div style="min-height: 450px;overflow: auto;">
      <textUI
        :modelValue="areaSearch.value"
        :item="areaSearch"
        v-bind="props"
        class="mt-3"
        style="position: relative;"
        @change="areaSearchChange"
      ></textUI>
      <div class="otherAreaBox d-flex flex-wrap">
        <div v-for="item in otherAreaList" :key="item.id" @click="handleOtherClick(item)">{{ item.name }}</div>
      </div>
    </div>
  </CtDialog>
</template>
<script setup>
import CtDialog from '@/components/CtDialog'
import textUI from '@/components/FormUI/TextInput'
import { getDict } from '@/hooks/web/useDictionaries'
import { inject, reactive, ref } from 'vue'
defineOptions({ name:'common-components-areaTree'})
const emits = defineEmits(['checkedInput'])

const props = defineProps({
  // items: Object,
  defaultOpen: {
    type: Number,
    default: 2
  },
  multipleLevel: {
    type: Number,
    default: 3
  },
  parentId: {
    type: [Number, String],
    default: -1
  }
})
const num = 10

let treeList = ref() 
const show = ref(false) 
const query = inject('routeQuery')
// 获取区域数据
getDict('areaTreeData', {}, 'areaTreeData').then(({ data }) => {
  const arr = data?.length && data || []
  treeList.value = [arr]
  if (query && query.city) { // 刷新回显
    const city = query.city
    const levelCountArr = city.split('__')
    levelCountArr?.forEach((areaIds, levelIndex) => {
      const idArr = areaIds.split('_')
      if (idArr?.length) {
        idArr.forEach(idItem => {
          const dataItem = treeList.value[levelIndex].find(findItem => (findItem.id - 0) === (idItem - 0))
          const params = {
            item: dataItem,
            index: levelIndex,
            expand: true,
            updateSearch: false
          }
          if (dataItem) handleNext(params)
        })
      }
    })
  } else {
    // 默认展开城市到defaultOpen级
    if (props.defaultOpen > 0) {
      for (let index = 0; index < props.defaultOpen; index++) {
        if (treeList.value?.length && treeList.value[index]?.length && treeList.value[index][0]) {
          const params = {
            item: treeList.value[index][0],
            index,
            expand: (index + 1) < props.defaultOpen,
            updateSearch: (index + 1) === props.defaultOpen // 最后一次才请求
          }
          handleNext(params)
        }
      }
    }
  }
  show.value = true
})

// 设置选中ids
const idChecked = reactive([])
const getIdChecked = (item, levelIndex) => {
  if (!idChecked[levelIndex]) idChecked[levelIndex] = [] // 不存在初始化为空
  if (levelIndex < props.multipleLevel) {
    idChecked[levelIndex] = [ item.id ]
  } else {
    const findIndex = idChecked[levelIndex]?.length ? idChecked[levelIndex].findIndex(j => j === item.id) : -1
    if (findIndex !== -1) {  
      idChecked[levelIndex].splice(findIndex, 1) // 删除  
    } else {  
      idChecked[levelIndex].push(item.id) // 添加  
    }
  }
  idChecked.splice(levelIndex + 1, idChecked.length) // 取消其下级数据
}

// 展开下一级
// item: 当前操作数据（被点击的数据本身）
// index: 当前操作数据的层级
// expand: 展开下级
// updateSearch: 是否刷新数据(职位列表)：刷新页面回显选中不需要刷新 使用的是路由中的参数
const handleNext = ({ item, index, expand = true, updateSearch = true }) => {
  if (expand) getIdChecked(item, index) // 设置默认选中第一个并展开
  if (updateSearch) emits('checkedInput', idChecked)
  if (expand && item.children && item.children.length) {
    treeList.value[index + 1] = item.children
    treeList.value.splice(index + 2, treeList.value.length)
  } else {
    treeList.value.splice(index + 1, treeList.value.length)
  }
}

// 选中样式判断
const calcAct = (id, levelIndex) => {
  if (!id) return false
  if (Array.isArray(idChecked) && Array.isArray(idChecked[levelIndex])) {
    const index = idChecked[levelIndex].findIndex(itemToCheck => itemToCheck=== id)
    const bool = index !== -1
    return bool ? true : false; // 如果找到返回索引，否则返回 false
  }
  else return false
}
// 不限
const clear = (list, levelIndex) => {
  treeList.value.splice(levelIndex + 1, treeList.value.length)
  idChecked.splice(levelIndex, idChecked.length) // 清除本级选中及其下级选中
  emits('checkedInput', idChecked)
}

// 弹窗
const showDialog = ref(false)
const dialogData = ref({})
const otherAreaList = ref([])
// const keyWord = ref('')
const handleShowOther = ({ list, index }) => {
  dialogData.value = { list, index }
  otherAreaList.value = [...dialogData.value.list]
  showDialog.value = true
}
const areaSearchChange = (val) => {
  if (val) otherAreaList.value = dialogData.value.list.filter(e => e.name.includes(val))
  else otherAreaList.value = [...dialogData.value.list]
}
const handleOtherClick = (item) => {
  handleNext({ item, index: dialogData.value.index })
  showDialog.value = false
}
const areaSearch = ref({
  type: 'text',
  key: 'name',
  value: '',
  label: '请输入关键字',
})
</script>
<style lang="scss" scoped>
.text666 {
  border-right: 1px solid var(--color-666);
}
.text333 {
  color: var(--color-333);
}
.act {
  color: var(--v-primary-base);
}
span {
  span { cursor: pointer; }
  cursor: pointer;
  &:hover {
    color: var(--v-primary-lighten2);
  }
}
.embedded {
  padding: 4px;
  background-color: var(--color-f8);
  border-radius: 5px;
  display: flex;
  flex-wrap: wrap;
  width: 100%; /* 设置容器宽度 */
  div {
    span { cursor: pointer; }
    cursor: pointer;
    &:hover {
      color: var(--v-primary-lighten2);
    }
  }
}
.otherAreaBox {
  padding: 4px;
  // background-color: var(--color-f8);
  border-radius: 5px;
  width: 100%; /* 设置容器宽度 */
  div {
    cursor: pointer;
    // line-height: 40px;
    margin: 0 16px 12px;
    font-size: 14px;
    &:hover {
      color: var(--v-primary-lighten2);
    }
  }
}
</style>
