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;
  const showCaption = item.showCaption;
  const caption = showCaption ? item.caption : '';
  if (viewMode === 'EMBED') {
    if (image) {
      return [showIcon ? <app-icon icon={image} /> : null, caption];
    }
    return [null, caption];
  }
  return [showIcon ? <app-icon icon={image} /> : null, 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
          ) {
            // 特殊处理，工具栏关闭按钮在非顶级容器分页模式打开时(即页面本身有X按钮)的场景，自动去掉工具栏中的关闭按钮
            const notShowCloseBtnViewMode = ['MODAL', 'DRAWER', 'POPOVER'];
            if (notShowCloseBtnViewMode.includes(this.viewMode)) {
              const uiAction = (item as IPSDETBUIActionItem).getPSUIAction();
              if (uiAction?.codeName === 'Exit') {
                return;
              }
            }
            return (
              <div
                key={item.id}
                class={[
                  this.ns.e('item'),
                  this.ns.e('item-deuiaction'),
                  this.ns.is('loading', this.toolbarState[item.id].loading),
                  this.ns.is('caption', !!(item.showCaption && item.caption)),
                ]}
              >
                <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>
    );
  },
});
