import { computed, defineComponent, PropType } from 'vue';

import {
  IPSFlexLayoutPos,
  IPSGridLayoutPos,
  IPSLayoutPos,
} from '@ibiz-template/model';
import { useNamespace } from '@ibiz-template/vue-util';
import { ILayoutController } from '@ibiz-template/controller';

export const AppCol = defineComponent({
  name: 'AppCol',
  props: {
    layoutPos: Object as PropType<IPSLayoutPos>,
    controller: {
      type: Object as PropType<ILayoutController>,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('col');
    // 计算栅格布局的属性
    const gridAttrs = computed(() => {
      const gridLayoutPos = props.layoutPos as IPSGridLayoutPos;
      // FLEX布局时不计算
      if (gridLayoutPos.layout === 'FLEX') {
        return {};
      }
      // 计算倍率，12列栅格为2
      const {
        colXS,
        colXSOffset,
        colSM,
        colSMOffset,
        colMD,
        colMDOffset,
        colLG,
        colLGOffset,
      } = gridLayoutPos;
      const multiplier = gridLayoutPos.layout === 'TABLE_24COL' ? 1 : 2;
      return {
        md: { span: colXS * multiplier, offset: colXSOffset * multiplier },
        lg: { span: colSM * multiplier, offset: colSMOffset * multiplier },
        xl: { span: colMD * multiplier, offset: colMDOffset * multiplier },
        xxl: { span: colLG * multiplier, offset: colLGOffset * multiplier },
      };
    });

    const cssVars = computed(() => {
      const styles = {
        width: props.controller.width,
        height: props.controller.height,
      };
      Object.assign(styles, props.controller.extraStyle);
      return styles;
    });

    return { ns, gridAttrs, cssVars };
  },
  render(h) {
    if (this.controller.visible === false) {
      return null;
    }
    if (this.layoutPos?.layout === 'FLEX') {
      return (
        <div
          class={[this.ns.b(), this.ns.m('flex'), this.controller.extraClass]}
          style={{
            flexGrow: (this.layoutPos as IPSFlexLayoutPos).grow,
            flexShrink: (this.layoutPos as IPSFlexLayoutPos).shrink,
            flexBasis: (this.layoutPos as IPSFlexLayoutPos).basis,
            ...this.cssVars,
          }}
        >
          {this.$slots.default}
        </div>
      );
    }
    return h(
      'i-col',
      {
        class: [this.ns.b(), this.ns.m('grid'), this.controller.extraClass],
        props: this.gridAttrs,
        style: this.cssVars,
      },
      this.$slots.default,
    );
  },
});
