<!--
 * @Descripttion:
 * @Version: 1.0
 * @Author: +C
 * @Date: 2022-02-15 08:47:06
 * @LastEditors: wufz
 * @LastEditTime: 2022-02-24 10:59:51
-->
<script>
import formComponents from "./formComponents"
export default {
  name: `DxxCascader`,
  //继承表单父组件
  extends: formComponents,
  /* 这里的v-model的值将会传入这个名为 value的prop。同时当组件触发一个 change事件并附带一个新的值的时候，这个 value的 property将会被更新。 */
  model: {
    prop: 'value',
    event: 'change'
  },
  // functional: true, //函数式组件
  props: {
    value: { // v-model绑定的值
      type: Array,
      required: false
    },
    fieldNames: {
      type: Object,
      required: false,
      default: () => { return { label: 'label', value: 'value', children: 'children' } }
    }
  },
  methods: {
    /**
     * @description: 让下拉框相对定位到表单组件而不是body
     * @author: wufz
     * @return {*}
     */
    getPopupContainer() {
      return this.$parent.$el
    },
    /**
     * @description: 获取对应路径
     * @author: wufz
     * @param {*} node
     * @param {*} str
     * @param {*} val
     * @param {*} index 当前层数
     * @return {*}
     */
    getPath(node, str = '', val = '', index = 0) {
      str += node[0][this._props.fieldNames.label] + '/';
      val += node[0][this._props.fieldNames.value] + ',';
      if (index == this._props.value.length - 1) {
        return { label: str, value: val }
      }
      return this.getPath(node[0].children, str, val, index + 1)
    }
  },
  //建立虚拟 DOM
  render: function (createElement) {
    /* let _this = Object.entries(this)
    console.log(_this); */

    //处理详细内容
    let showStr = ''
    let node = this.XEUtils.searchTree(this.$attrs.options, (item) => item[this._props.fieldNames.value] === this._props.value[this._props.value.length - 1], { children: this._props.fieldNames.children })
    for (let i = 0; i < node.length; i++) {
      let res = this.getPath([node[i]], '', '', 0)
      if (res.value.substr(0, res.value.length - 1) === this._props.value.toString()) {
        showStr = res.label.substr(0, res.label.length - 1)
        break
      }
    }
    let drawText = createElement(`span`, {}, [showStr])
    this.$attrs.getPopupContainer = this.getPopupContainer

    //编辑：dom表单元素
    let drawFromComponents = createElement(
      // 标签名称
      `a-cascader`,
      // 传递数据
      {
        attrs: {
          ...this.$attrs
        },
        props: {
          ...this._props
        },
        on: {
          ...this.$listeners
        },
        scopedSlots: {
          ...this.$scopedSlots
        }
      },
      // 子节点数组，createElement...
      [
        this.$slots.default
      ]
    );

    return this.isDetail ? drawText : drawFromComponents;
  }
};
</script>

<style scoped>
</style>