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

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

export const AppCol = defineComponent({
  name: 'AppCol',
  props: {
    layoutPos: Object as PropType<IPSLayoutPos>,
    modelData: {
      type: Object as PropType<IData>,
      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 {
        xs: { span: colXS * multiplier, offset: colXSOffset * multiplier },
        sm: { span: colSM * multiplier, offset: colSMOffset * multiplier },
        md: { span: colMD * multiplier, offset: colMDOffset * multiplier },
        lg: { span: colLG * multiplier, offset: colLGOffset * multiplier },
      };
    });

    const cssVars = computed(() => {
      const styles = {};
      Object.assign(styles, {
        width: props.modelData.width ? props.modelData.width : '100%',
        height: props.modelData.height ? props.modelData.height : '100%',
      });

      // 关系界面额外样式
      if (props.modelData.source?.detailType === 'DRUIPART') {
        Object.assign(styles, {
          overflow: 'auto',
        });
      }
      return styles;
    });

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