import { DropDownListEditorController } from '@ibiz-template/controller';
import { ref, Ref, defineComponent, PropType, computed } from 'vue';
import { useNamespace } from '@ibiz-template/vue-util';
import '@ibiz-template/theme/style/components/editor/ibiz-dropdown-list/ibiz-dropdown-list.scss';

export const IBizDropDownList = defineComponent({
  name: 'IBizDropDownList',
  props: {
    value: {
      type: String,
    },
    controller: {
      type: DropDownListEditorController,
    },
    data: {
      type: Object as PropType<IData>,
    },
    disabled: {
      type: Boolean,
    },
  },
  emits: {
    change: (_value: string | Array<string> | null) => true,
  },
  setup(props, { emit }) {
    const ns = useNamespace('dropdown-list');
    const c = props.controller;

    // 是否是树形
    const hasChildren = ref(false);

    // 代码表
    const items: Ref<readonly IData[]> = ref([]);

    c!.loadCodeList(props.data!).then((codeList: readonly IData[]) => {
      items.value = codeList;
      for (let i = 0; i < codeList.length; i++) {
        const _item = codeList[i];
        if (_item.children) {
          hasChildren.value = true;
          break;
        }
      }
    });

    // 当前值
    const curValue: Ref<Array<string> | string | undefined> = computed({
      get() {
        if (props.value) {
          return c!.multiple ? props.value?.split(',') : props.value;
        }
        return '';
      },
      set(select: string | Array<string>) {
        const value =
          Object.prototype.toString.call(select) === '[object Array]'
            ? (select as Array<string>).join(',')
            : select;
        if (value) {
          emit('change', value);
        } else {
          emit('change', null);
        }
      },
    });

    return { ns, c, curValue, items, hasChildren };
  },

  render() {
    return (
      <div class={this.ns.b()}>
        {this.hasChildren ? (
          <div class={this.ns.e('tree-select')}>
            <app-select-tree
              value={this.curValue}
              nodes-data={this.items}
              multiple={this.c!.multiple}
            ></app-select-tree>
          </div>
        ) : (
          <div class={this.ns.e('select')}>
            <i-select
              v-model={this.curValue}
              allow-clear
              clearable
              class={this.ns.e('dropdown-list')}
              multiple={this.c!.multiple}
              placeholder={this.c!.placeHolder}
              disabled={this.disabled}
            >
              {this.items.map(item => {
                return <i-option value={item.value}>{item.text}</i-option>;
              })}
            </i-select>
          </div>
        )}
      </div>
    );
  },
});
