import { computed, defineComponent, onMounted, PropType, ref } from 'vue';
import {
  IPSDETBGroupItem,
  IPSDETBUIActionItem,
  IPSDEToolbarItem,
  ToolbarModel,
} from '@ibiz-template/model';
import {
  IButtonContainerState,
  ToolbarNeuron,
} from '@ibiz-template/controller';
import { useNamespace } from '@ibiz-template/vue-util';
import '@ibiz-template/theme/style/components/common/view-toolbar/view-toolbar.scss';

const btnContent = (item: IPSDEToolbarItem, viewMode: string) => {
  const image = item.getPSSysImage();
  const showIcon = item.showIcon;
  if (viewMode === 'EMBED') {
    if (image) {
      return [showIcon ? <app-icon icon={image} /> : null, item.caption];
    }
    return [showIcon ? <img src='undefined' /> : null, item.caption];
  }
  return [showIcon ? <app-icon icon={image} /> : null, item.caption];
};

export const ViewToolbar = defineComponent({
  name: 'ViewToolbar',
  props: {
    modelData: {
      type: ToolbarModel,
      required: true,
    },
    toolbarState: {
      type: Object as PropType<IButtonContainerState>,
      required: true,
    },
    viewMode: {
      type: String,
      required: true,
    },
  },
  setup(props, { emit }) {
    const ns = useNamespace('view-toolbar');
    const neuron = new ToolbarNeuron({});
    emit('neuronInit', neuron);
    // 正在执行的工具栏项
    const doingToolbarItem = ref<string>('');

    onMounted(async () => {
      await neuron.evt.asyncEmit('mounted');
    });

    const btnSize = computed(() => {
      return props.viewMode === 'EMBED' ? 'small' : 'default';
    });

    // 点击事件
    const _handleClick = async (item: IPSDEToolbarItem, _event: MouseEvent) => {
      props.toolbarState.setLoading(item.id);
      try {
        await neuron.evt.asyncEmit(
          'itemClick',
          item as IPSDETBUIActionItem,
          _event,
        );
      } finally {
        props.toolbarState.setLoading('');
      }
    };

    // 按钮点击加延时。解决子界面行编辑没有失焦的情况下先触发了按钮的行为。
    const handleClick = async (item: IPSDEToolbarItem, event: MouseEvent) => {
      setTimeout(() => {
        _handleClick(item, event);
      }, 30);
    };

    return { ns, doingToolbarItem, handleClick, btnSize };
  },
  render() {
    return (
      <div class={[this.ns.b(), this.ns.m(this.viewMode.toLowerCase())]}>
        {this.modelData!.source.getPSDEToolbarItems()?.map(item => {
          if (item.itemType === 'SEPERATOR') {
            return (
              <div
                key={item.id}
                class={[this.ns.e('item'), this.ns.e('item-separator')]}
              >
                |
              </div>
            );
          }
          if (item.itemType === 'RAWITEM') {
            return (
              <div
                key={item.id}
                class={[this.ns.e('item'), this.ns.e('item-rawitem')]}
              >
                {btnContent(item, this.viewMode)}
              </div>
            );
          }
          if (
            item.itemType === 'DEUIACTION' &&
            this.toolbarState[item.id].visible
          ) {
            return (
              <div
                key={item.id}
                class={[this.ns.e('item'), this.ns.e('item-deuiaction')]}
              >
                <i-button
                  title={item.tooltip}
                  size={this.btnSize}
                  loading={this.toolbarState[item.id].loading}
                  disabled={this.toolbarState[item.id].disabled}
                  on-click={(e: MouseEvent) => this.handleClick(item, e)}
                >
                  {btnContent(item, this.viewMode)}
                </i-button>
              </div>
            );
          }
          if (item.itemType === 'ITEMS') {
            return (
              <div
                key={item.id}
                class={[this.ns.e('item'), this.ns.e('item-items')]}
              >
                <i-dropdown trigger='click' placement='bottom-start'>
                  <i-button title={item.tooltip} size={this.btnSize}>
                    {btnContent(item, this.viewMode)}
                  </i-button>
                  <i-dropdown-menu slot='list'>
                    {(item as IPSDETBGroupItem)
                      .getPSDEToolbarItems()!
                      .map(item2 => {
                        return (
                          <i-dropdown-item
                            key={item2.id}
                            nativeOn-click={(e: MouseEvent) =>
                              this.handleClick(item2, e)
                            }
                          >
                            {btnContent(item2, this.viewMode)}
                          </i-dropdown-item>
                        );
                      })}
                  </i-dropdown-menu>
                </i-dropdown>
              </div>
            );
          }
          return null;
        })}
      </div>
    );
  },
});
