<template>
  <div class="my-form" :style="{ fontSize: `${size}rem` }">
    <a-row v-for="(row, rowIndex) in layout" :key="rowIndex" class="row">
      <a-col
        v-for="(col, key) in row"
        :key="key"
        class="col"
        :span="col.width"
        :offset="col.offset || 0"
      >
        <div
          :style="`text-align: ${
            col.align || 'right'
          }; width:${labelWidth}rem;`"
        >
          {{ col.label }}：
        </div>
        <template v-if="col.type == 'img'">
          <img
            v-for="img in model[key] && model[key].split(',')"
            :key="img"
            :src="img"
            @click="handleView(img)"
          />
        </template>
        <div v-else class="content">
          {{ col.format ? col.format(model[key]) : model[key] || ' ' }}
        </div>
      </a-col>
    </a-row>
  </div>
  <MyModal v-model="showImg" title="图片">
    <img v-if="showImg" style="max-height: 45vh; width: 100%" :src="curImg" />
  </MyModal>
</template>

<script lang="ts">
import { defineComponent, PropType, ref } from 'vue'
import MyModal from '../MyModal/my-modal.vue'

interface ModelProp {
  [key: string]: any
}

interface LayoutItemProp {
  label: string | number
  width: number
  offset?: number
  align?: 'left' | 'center' | 'right'
  type?: 'img'
  format?: (arg: any) => any
}
export interface LayoutProp {
  [key: string]: LayoutItemProp
}

export default defineComponent({
  name: 'MyForm',
  displayName: 'm-form',
  components: {
    MyModal,
  },
  props: {
    size: {
      type: Number as PropType<number>,
      default: 0.1,
    },
    labelWidth: {
      type: Number as PropType<number>,
      default: 1,
    },
    layout: {
      type: Array as PropType<LayoutProp[]>,
      required: true,
    },
    model: {
      type: Object as PropType<ModelProp>,
      default() {
        return {}
      },
    },
  },
  setup() {
    const showImg = ref(false)
    const curImg = ref(null)
    const handleView = (img: any) => {
      curImg.value = img
      showImg.value = true
    }
    return {
      showImg,
      curImg,
      handleView,
    }
  },
})
</script>

<style lang="stylus" scoped>
.my-form
  .row
    line-height 2
    &:nth-child(odd)
      background rgba(51,145,255,.2)
  .col
    display flex
    align-items center
    padding 0 .05rem
    .content
      flex 1
    img
      width 19%
      height .5rem
      margin .05rem .03rem .05rem 0
      cursor pointer
</style>
