<template>
  <span v-if="isLook">{{ select_look || '-' }}</span>
  <el-cascader
    v-else
    ref="tree"
    v-model="select"
    :options="district"
    :props="treeProps"
    :disabled="disabled"
    :show-all-levels="false"
    filterable
    clearable
  >
    <template #default="{ node, data }">
      <span>{{ data[field.label] }}</span>
      <!-- 需要拼装子级的处理 -->
      <span v-if="node.isLeaf && data.remark"> ({{ data.remark }}) </span>
    </template>
  </el-cascader>
</template>

<script setup lang="ts">
import { useOptions } from '../hooks/useOptions'
import { getDistrictTree } from '../../../../api'
import { findNodeNameById } from '../../../../utils/tree'
import { ref } from 'vue'

import { computed } from 'vue'

const props = defineProps({
  modelValue: {
    type: [String, Number, Array],
    default: () => ''
  },
  mode: {
    type: String,
    default: 'add'
  },
  formItem: {
    type: Object,
    default: () => {}
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

const district = ref([])
const getDict = async () => {
  const res = await getDistrictTree()
  district.value = res.data
}
getDict()

const emits = defineEmits(['update:modelValue'])

// 双向绑定 选中项
const select: any = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emits('update:modelValue', val)
  }
})

// 查看状态时 需要展示的值
const select_look = computed(() => {
  if (!isLook) return
  const val = props.modelValue
    ? props.formItem.isMultiple
      ? props.modelValue
      : [props.modelValue]
    : ''

  if (val) {
    return (val as any[])
      .map((i) => {
        return findNodeNameById(district.value, 'id', i, 'name')
      })
      .join('，')
  } else return '-'
})

const { isLook, field } = useOptions(props, emits)

const treeProps = {
  emitPath: false,
  multiple: props.formItem.isMultiple,
  value: 'id',
  label: 'name'
}
</script>
