<style scoped>
</style>

<template>
  <div>
    <Waterfall-flow :list="data" :space-y="spaceY" :selected="selectedItems">
      <template slot="body" slot-scope="{ item }">
        <slot name="list" :item="item"></slot>
      </template>
    </Waterfall-flow>
    <template>
      <div class="el-table__footer-wrapper">
        <div class="el-multi-operate" v-if="selectable && multiOperates.length > 0">
          <el-checkbox @change="selectAllChanged" v-model="selectAllChecked">选择</el-checkbox><el-select v-show="selectedItems.length > 1" value="" @change="selectOperate" placeholder="请选择操作项">
            <el-option
              v-for="item in multiOperates"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </div>
        <el-pagination
          @size-change="sizeChangeHandler"
          @current-change="currentChangeHandler"
          :current-page.sync="tmpCurrentPage"
          :page-size.sync="tmpPageSize"
          :total="total"
          :layout="paginationLayout" v-show="!!pageSize">
        </el-pagination>
      </div>
    </template>
  </div>
</template>

<script>
import { Loading } from 'element-ui'
import WaterfallFlow from './WaterfallFlow.vue'
import _ from 'lodash'
export default {
  name: 'WaterfallFlowList',
  componentName: 'WaterfallFlowList',
  components: {
    'Waterfall-flow': WaterfallFlow
  },
  props: {
    data: {
      type: Array,
      default: function() {
        return []
      }
    },
    dataReadUrl: {
      type: [String, Function],
      default: ''
    },
    autoGetData: {
      type: Boolean,
      default: true
    },
    listKey: {
      type: String,
      default: 'ID'
    },
    pageSize: {
      type: Number,
      default: 0
    },
    paginationLayout: {
      type: String,
      default: 'total, sizes, ->, prev, pager, next, jumper'
    },
    currentPage: {
      type: Number,
      default: 1
    },
    spaceY: {
      type: Number,
      default () {
        return 0
      }
    },
    selectable: {
      type: Boolean,
      default: false
    },
    multiOperates: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data () {
    return {
      total: 0,
      selectedItems: [],
      tmpPageSize: 0,
      tmpCurrentPage: 0,
      checkedFlag: false,
      selectAllChecked: false
    }
  },
  computed: {
    operateFuncs() {
      let obj = {}
      for (let i = 0; i < this.multiOperates.length; i++) {
        let opt = this.multiOperates[i]
        obj[opt.value] = opt.fn
      }
      return obj
    }
  },
  methods: {
    getData (pageIndex) {
      if (!pageIndex) {
        this.tmpCurrentPage = 1
      }

      return new Promise(async (resolve, reject) => {
        const self = this
        let loadingInstance = Loading.service({ target: self.$el })
        let readUrl
        let options
        if (typeof this.dataReadUrl === 'string') {
          readUrl = this.dataReadUrl
          options = {
            params: {
              pageIndex: this.tmpCurrentPage,
              pageSize: this.tmpPageSize
            }
          }
        } else if (typeof this.dataReadUrl === 'function') {
          const result = this.dataReadUrl()
          readUrl = result[0]
          options = result[1]
          options.params = options.params || {}
          options.params.pageIndex = this.tmpCurrentPage
          options.params.pageSize = this.tmpPageSize
        }
        options.params.pageIndex--
        try {
          let res = await axios.get(readUrl, options)
          if (res.data.status === 0) {
            self.total = 0
            this.$emit('update:data', [])
            loadingInstance.close()
            reject(res.data.message || `从接口${this.dataReadUrl}获取数据失败 ！`)
          }
          if (!res.data.total && res.data.data) {
            if (res.data.total === 0) {
              self.total = res.data.total
            } else if (res.data.data.length > 0 && this.pageSize) {
              reject(new Error('接口 ' + this.dataReadUrl + ' 没有返回 total ，无法设置数据表格的总记录数！'))
            }
          } else {
            self.total = res.data.total
          }
          if (!Array.isArray(res.data.data)) {
            self.total = 0
            this.$emit('update:data', [])
            //  self.data.splice.apply(self.data [0, self.data.length])
            reject(new Error('接口 ' + this.dataReadUrl + ' 没有返回 data ，无法设置数据表格的数据！'))
          } else {
            this.$emit('update:data', res.data.data)
          }
        } catch (e) {
          console.error(e)
          loadingInstance.close()
        }
        this.$nextTick(() => {
          loadingInstance.close()
        })
        resolve()
      })
    },
    sizeChangeHandler (val) {
      this.tmpPageSize = val
      if (this.dataReadUrl && this.autoGetData) {
        this.getData(this.tmpCurrentPage)
      }
    },
    currentChangeHandler (val) {
      this.tmpCurrentPage = val
      if (this.dataReadUrl && this.autoGetData) {
        this.getData(this.tmpCurrentPage)
      }
    },
    selectAllChanged(val) {
      if (val) {
        this.selectedItems = _.clone(this.data)
      } else {
        this.selectedItems = []
      }
    },
    selectOperate(e) {
      let fn = this.operateFuncs[e]
      if (typeof fn === 'function') {
        fn(this.selectedItems)
      }
    }
  },
  created () {
    this.tmpPageSize = this.pageSize
    this.tmpCurrentPage = this.currentPage

    this.$on('click-item', (item) => {
      if (!this.selectable) {
        return
      }
      // const _key = item[this.listKey]
      const _index = this.selectedItems.findIndex(val => val === item)

      if (_index === -1) {
        this.selectedItems.push(item)
      } else {
        this.selectedItems.splice(_index, 1)
      }
      if (this.selectedItems.length === this.data.length) {
        this.selectAllChecked = true
      } else {
        this.selectAllChecked = false
      }

      this.$emit('selection-change', this.selectedItems)
    })
  },
  async mounted () {
    await this.$nextTick()

    if (this.dataReadUrl && this.autoGetData) {
      this.getData(this.tmpCurrentPage)
    }
  }
}
</script>
