import { Ref, ref, watch, defineComponent, PropType } from 'vue';
import { useNamespace } from '@ibiz-template/vue-util';

export const AppSelectTree = defineComponent({
  name: 'AppSelectTree',
  props: {
    value: {
      type: String as PropType<Array<string> | string>,
    },
    multiple: {
      type: Boolean,
    },
    nodesData: {
      type: Array as PropType<IData[]>,
    },
  },
  setup(props) {
    const ns = useNamespace('app-select-tree');
    const visible = ref(false);

    const treeNodes: Ref<IData[]> = ref([]);

    const handletreeNodes = (nodes: readonly IData[]) => {
      if (nodes.length === 0) {
        return [];
      }
      const list: IData[] = [];
      nodes.forEach((codeItem: IData) => {
        const tempObj: IData = {
          title: codeItem.text,
          value: codeItem.value,
          children: [],
        };
        if (codeItem.children && codeItem.children.length > 0) {
          tempObj.children = handletreeNodes(codeItem.children);
        }
        list.push(tempObj);
      });
      return list;
    };

    watch(
      () => props.nodesData,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          treeNodes.value = handletreeNodes(newVal!);
        }
      },
      { immediate: true },
    );

    const triggerMenu = (_visible: boolean) => {
      if (!_visible) {
        visible.value = !visible.value;
      } else {
        visible.value = _visible;
      }
    };
    return { ns, visible, treeNodes, triggerMenu };
  },
  render() {
    return (
      <div class={this.ns.b()}>
        <i-dropdown
          visible={this.visible}
          trigger='custom'
          transfer-class-name={this.ns.e('dropdown')}
          transfer
          on-on-clickoutside={() => {
            this.triggerMenu(false);
          }}
        >
          <div
            on-click={() => {
              this.triggerMenu(true);
            }}
          >
            打开下拉树
          </div>
          <i-dropdownMenu slot='list'>
            <i-tree data={this.treeNodes} show-checkbox></i-tree>
          </i-dropdownMenu>
        </i-dropdown>
      </div>
    );
  },
});
