<template>
  <div class="mch-file-list">
    <div class="file-item flex-between" style="font-weight: bold;">
      <div>文件名</div>
      <div>操作</div>
    </div>
    <div class="file-list">
      <Tree :data="treeData" class="demo-tree-render"></Tree>
    </div>
    <div class="footer flex-between" style="font-weight: bold;padding: 10px 0;">
      <div>共{{ fileList.length }}张图片</div>
      <div>
        <Icon class="cursor" custom="iconfont icon-delete" @click="clearPhotos" />
      </div>
    </div>
  </div>
</template>

<script>
import { resolveComponent } from 'vue'
export default {
  props: {
    fileList: {
      type: Array,
      default: []
    }
  },
  methods: {
    clearPhotos() {
      this.$emit('on-clear')
    }
  },
  computed: {
    treeData() {
      let list = []
      this.fileList.forEach((item, index) => {
        let {name, group} = item
        let fileItem = {
          title: name,
          expand: true,
          render: (h, { root, node, data }) => {
            return h('div', {
              class: "file-item flex-between"
            }, [
              h('div', data.title),
              h(resolveComponent('Icon'), {
                class: 'cursor',
                custom: 'iconfont icon-delete',
                style: {
                  marginRight: '8px'
                },
                onClick: () => {
                  this.$emit('on-remove', {
                    type: 'file',
                    index: index
                  })
                }
              })
            ])
          }
        }
        if (group) {
          let groupItem = list.find(d => d.title === group)
          if (!groupItem) {
            groupItem = {
              title: group,
              expand: true,
              children: [],
              render: (h, { root, node, data }) => {
                return h('div', {
                  class: "file-item flex-between"
                }, [
                  h('div', data.title),
                  h(resolveComponent('Icon'), {
                    class: 'cursor',
                    custom: 'iconfont icon-delete',
                    style: {
                      marginRight: '8px'
                    },
                    onClick: () => {
                      this.$emit('on-remove', {
                        type: 'group',
                        group
                      })
                    }
                  })
                ])
              }
            }
            list.push(groupItem)
          }
          groupItem.children.push(fileItem)
        } else {
          list.push(fileItem)
        }
      })
      return list
    }
  }
}
</script>