import {
  CreateElement,
  defineComponent,
  getCurrentInstance,
  PropType,
  reactive,
  ref,
  VNode,
} from 'vue';
import { useNamespace } from '@ibiz-template/vue-util';
import { isNumber } from 'lodash-es';
import { IDrawerOptions, IOverlayContainer } from '@ibiz-template/runtime';
import { useUIStore } from '@/store';
import '@ibiz-template/theme/style/components/util/drawer/drawer.scss';
import { OverlayContainer } from '../overlay-container/overlay-container';

export const AppDrawerComponent = defineComponent({
  props: {
    opts: {
      type: Object as PropType<IDrawerOptions>,
      default: () => ({}),
    },
  },
  setup(props, ctx) {
    const ns = useNamespace('drawer');
    const { proxy } = getCurrentInstance()!;

    const isShow = ref(false);

    const { zIndex } = useUIStore();
    const drawerZIndex = zIndex.increment();

    // 处理自定义样式
    const customStyle = reactive<IData>({});
    const { width, height } = props.opts;
    if (width) {
      customStyle.width = isNumber(width) ? `${width}px` : width;
    }
    if (height) {
      customStyle.height = isNumber(height) ? `${height}px` : height;
    }

    // 所有关闭方式最终都走这个
    const onVisibleChange = (state: boolean) => {
      if (!state) {
        zIndex.decrement();
        ctx.emit('dismiss');
        document.body.removeChild(proxy.$el);
      }
    };

    const dismiss = () => {
      isShow.value = false;
    };

    const present = () => {
      isShow.value = true;
    };

    return {
      ns,
      isShow,
      drawerZIndex,
      customStyle,
      dismiss,
      present,
      onVisibleChange,
    };
  },
  render() {
    return (
      <i-drawer
        value={this.isShow}
        on-input={(val: boolean) => {
          this.isShow = val;
        }}
        width={this.opts.width}
        height={this.opts.height}
        class={[this.ns.b()]}
        style={{ [this.ns.cssVarBlockName('z-index')]: this.drawerZIndex }}
        styles={this.customStyle}
        placement={this.opts.placement || 'right'}
        on-on-visible-change={this.onVisibleChange}
      >
        {this.$slots.default}
      </i-drawer>
    );
  },
});

/**
 * 创建抽屉
 *
 * @author lxm
 * @date 2022-11-09 18:11:57
 * @export
 * @param {(_h: CreateElement) => VNode} render
 * @param {(IDrawerOptions | undefined)} [opts]
 * @returns {*}  {IOverlayContainer}
 */
export function createDrawer(
  render: (_h: CreateElement) => VNode,
  opts?: IDrawerOptions | undefined,
): IOverlayContainer {
  return new OverlayContainer(AppDrawerComponent, render, opts);
}
