<template>
  <div>
    <component
      :is="isGroup?'kyb-group-item':'div'"
      :name="group.name"
      v-for="(group,index) in groupList"
      :key="index"
      :size="size || group.items.length"
      v-model="group.extend"
      :class="itemClass"
      @input="$forceUpdate()"
    >
      <template #header>
        <slot name="header" v-bind="{group,index}" />
      </template>
      <template v-if="group.extend">
        <slot v-bind="{group,index}" />
      </template>
    </component>
  </div>
</template>
<style>
</style>
<script>
import _ from 'underscore'

export default {
  name: 'k-group-show',
  props: {
    isGroup: Boolean,
    itemClass: String,
    itemKey: { type: String, default: '_id' }, // 唯一Id字段
    titleKey: { type: String, default: 'name' }, // 显示字段
    valueKey: { type: String, default: '_id' }, // 值的字段
    groupKey: { type: String, default: 'group' }, // 分组的字段

    items: {
      type: Array,
      default: function() {
        return []
      }
    },
    size: Number,
    isExtendAll: {
      type: Boolean,
      default: true
    }
  },
  data: function() {
    return {}
  },
  watch: {
  },
  computed: {
    groupList() {
      if (!this.isGroup) {
        return [
          {
            extend: this.isExtendAll,
            type: 'default',
            inputType: 'default',
            items: this.items
          }
        ]
      }
      // let groups = []
      let groupMap = {}
      this.items.forEach(item => {
        let groupName = item[this.groupKey] ? item[this.groupKey] : '默认'
        if (!groupMap[groupName]) {
          let v = {
            name: groupName,
            key: item.groupName || groupName,
            extend: item.extend === undefined ? this.isExtendAll : item.extend,
            hide: false,
            type: item.groupType || 'default',
            inputType: item.groupInputType || 'default',
            items: []
          }
          groupMap[groupName] = v
        }
        let v = groupMap[groupName]
        if (!v.sortNo && v.sortNo !== 0) {
          v.sortNo = groupName === '默认' ? 0 : 1
        }
        v.items.push(item)
      })
      let re = _.values(groupMap)
      // console.log('sort', re)
      re.sort((a, b) => a.sortNo - b.sortNo)
      // console.log('sorted', re)
      return re
    }
  },
  methods: {
    extendAll() {
      this.groupList.forEach(item => {
        item.extend = true
      })
      this.$forceUpdate()
    }
  }
}
</script>
