<template>
  <div :style="{width}">
    <el-cascader
      v-model="proxyValue"
      ref="cascader"
      :placeholder="placeholder"
      :options="options"
      :show-all-levels="showAllLevels"
      :props="optionProps"
      :disabled="disabled"
      :filterable="filterable"
      :style="{width}"
      popper-class="cip-popper-class"
      :clearable="clearable" />
  </div>
</template>
<script>
import { ElCascader } from 'element-plus'
import { useFormInput, useOptions } from '@cip/components/hooks/form-input'
import { formInputProps, fromInputEmits } from '../../form-input-props'
import { computed, ref } from 'vue'
export default {
  components: { ElCascader },
  props: formInputProps,
  emits: [...fromInputEmits],
  setup (props, context) {
    const cascader = ref()
    const { securityConfig, proxyValue, updateStream, ...formInput } = useFormInput(props, context, {
      fromModelValue: (modelValue) => getValue(modelValue),
      toModelValue: (value) => {
        const modelValue = getModelValue(value)
        if (otherKey.value) {
          const node = cascader.value.getCheckedNodes()
          const otherValue = node.map(i => i[optionProps.value.label]).join(splitKey.value)
          updateStream.appendOtherValue(otherValue)
          updateStream.appendOtherValue(node, 2)
        }
        return modelValue
      },
      maxOtherKey: 2
    })
    // 是否多选,ElCascader的多选比较特殊,multiple是在props里面,所以特殊处理
    const multiple = computed(() => {
      return securityConfig.value.multiple ?? false
    })
    const { options, getValue, getModelValue } = useOptions(props, multiple, updateStream)
    const showAllLevels = computed(() => {
      return securityConfig.value.showAllLevels
    })
    const splitKey = computed(() => {
      return props.config?.splitKey ?? ','
    })
    // 另一个键
    const otherKey = computed(() => {
      return securityConfig.value.otherKey ?? ''
    })
    // 过滤
    const filterable = computed(() => {
      return securityConfig.value.filterable ?? false
    })
    // 懒加载在optionProps中配置
    const optionProps = computed(() => {
      return {
        value: 'value',
        label: 'label',
        children: 'children',
        multiple: multiple.value,
        ...securityConfig.value.optionProps
      }
    })

    return {
      ...formInput,
      proxyValue,
      options,
      filterable,
      optionProps,
      showAllLevels,
      cascader
    }
  }
}
</script>

<style lang="less">
.el-cascader-panel{
  max-height: 50vh;
  overflow-y: scroll;
}
</style>
