<template>
  <div
    class="k-grid"
    :class="gridClass"
    :style="gridStyle"
  >
    <slot />
  </div>
</template>

<script lang="ts">
import { computed, defineComponent } from 'vue';
import { GridProps } from './types';

export default defineComponent({
  name: 'KGrid',
  props: {
    columns: {
      type: [Number, Array],
      default: 12
    },
    gap: {
      type: [Number, String],
      default: ''
    },
    rowGap: {
      type: [Number, String],
      default: ''
    },
    columnGap: {
      type: [Number, String],
      default: ''
    },
    align: {
      type: String as () => 'start' | 'center' | 'end' | 'stretch',
      default: 'stretch'
    },
    justify: {
      type: String as () => 'start' | 'center' | 'end' | 'space-between' | 'space-around' | 'space-evenly',
      default: 'start'
    },
    responsive: {
      type: Boolean,
      default: false
    },
    xs: {
      type: Number,
      default: 0
    },
    sm: {
      type: Number,
      default: 0
    },
    md: {
      type: Number,
      default: 0
    },
    lg: {
      type: Number,
      default: 0
    },
    xl: {
      type: Number,
      default: 0
    }
  },
  setup(props: GridProps) {
    const gridClass = computed(() => {
      const classes = [];

      if (props.responsive) {
        if (props.xs) classes.push(`k-grid--xs-${props.xs}`);
        if (props.sm) classes.push(`k-grid--sm-${props.sm}`);
        if (props.md) classes.push(`k-grid--md-${props.md}`);
        if (props.lg) classes.push(`k-grid--lg-${props.lg}`);
        if (props.xl) classes.push(`k-grid--xl-${props.xl}`);
      }

      return classes;
    });

    const gridStyle = computed(() => {
      const style: Record<string, string> = {};

      // 设置列数
      if (typeof props.columns === 'number') {
        style.gridTemplateColumns = `repeat(${props.columns}, 1fr)`;
      } else if (Array.isArray(props.columns)) {
        style.gridTemplateColumns = props.columns.join(' ');
      }

      // 设置间距
      if (props.gap !== '') {
        if (typeof props.gap === 'number') {
          style.gap = `${props.gap}px`;
        } else {
          style.gap = props.gap || '';
        }
      }

      if (props.rowGap !== '') {
        if (typeof props.rowGap === 'number') {
          style.rowGap = `${props.rowGap}px`;
        } else {
          style.rowGap = props.rowGap || '';
        }
      }

      if (props.columnGap !== '') {
        if (typeof props.columnGap === 'number') {
          style.columnGap = `${props.columnGap}px`;
        } else {
          style.columnGap = props.columnGap || '';
        }
      }

      // 设置对齐方式
      style.alignItems = props.align || '';
      style.justifyItems = props.justify || '';

      return style;
    });

    return {
      gridClass,
      gridStyle
    };
  }
});
</script>

<style lang="scss">
@use './index.scss' as *;
</style>
