import { defineComponent, PropType } from 'vue';
import { IPSUIActionGroup, IPSUIActionGroupDetail } from '@ibiz-template/model';
import { useNamespace } from '@ibiz-template/vue-util';
import { IButtonContainerState } from '@ibiz-template/controller';
import '@ibiz-template/theme/style/components/common/action-toolbar/action-toolbar.scss';

export const ActionToolbar = defineComponent({
  name: 'ActionToolbar',
  props: {
    actionGroup: {
      type: Object as PropType<IPSUIActionGroup>,
      required: true,
    },
    actionsState: {
      type: Object as PropType<IButtonContainerState>,
      required: true,
    },
  },
  setup(props, { emit }) {
    const ns = useNamespace('action-toolbar');

    // 点击事件抛给表格执行
    const handleClick = async (
      detail: IPSUIActionGroupDetail,
      event: MouseEvent,
    ) => {
      emit('action-click', detail, event);
    };

    return { ns, handleClick };
  },
  render() {
    const details = this.actionGroup.getPSUIActionGroupDetails() || [];
    return (
      <div class={`${this.ns.b()}`}>
        {details.length > 0 &&
          details.map(detail => {
            const action = detail.getPSUIAction();
            const btnClass = [this.ns.e('item'), this.ns.is('disabled', false)];
            // 接口没有，临时先用IData过校验
            const cssName = (detail as IData)?.getPSSysCss()?.cssName;
            if (cssName) {
              btnClass.push(cssName);
            }
            if (action && this.actionsState[detail.name].visible) {
              return [
                detail.addSeparator && (
                  <div class={this.ns.e('separator')}></div>
                ),
                <i-button
                  type='text'
                  size='small'
                  on-click={(e: MouseEvent) => this.handleClick(detail, e)}
                  disabled={this.actionsState[detail.name].disabled}
                  class={btnClass}
                >
                  {detail.showIcon && action.getPSSysImage() && (
                    <app-icon icon={action.getPSSysImage()}></app-icon>
                  )}
                  {detail.showCaption ? action!.caption : ''}
                </i-button>,
              ];
            }
            return null;
          })}
      </div>
    );
  },
});
