<template>
  <div id="data-table">
    <el-table :data="data" border stripe size="small">
      <template v-for="(item, index) in fields">
        <el-table-column :key="index" align="center" :label="item.label" :prop="item.prop" :formatter="toFormatter"></el-table-column>
      </template>
      <template v-if="opera.length > 0">
        <el-table-column label="操作" align="center">
          <template v-slot="{ row, $index }">
            <template v-for="(item, index) in opera">
              <el-tooltip :key="index" effect="dark" :content="item.label" placement="bottom">
                <el-button :key="index" type="text" :icon="item.icon || ''" size="mini" @click="handleOpera(row, item.method)"></el-button>
              </el-tooltip>
            </template>
          </template>
        </el-table-column>
      </template>
    </el-table>
  </div>
</template>

<script>
import _ from 'lodash';
export default {
  name: 'data-table',
  props: {
    fields: { type: Array, required: true },
    data: { type: Array, required: true },
    opera: { type: Array, default: () => [] },
  },
  components: {},
  data: () => ({}),
  created() {},
  computed: {},
  methods: {
    toFormatter(row, column, cellValue, index) {
      let this_fields = this.fields.filter(fil => fil.prop === column.property);
      if (this_fields.length > 0) {
        let format = _.get(this_fields[0], `format`, false);
        if (format) {
          let res = format(cellValue);
          return res;
        } else return cellValue;
      }
    },
    handleOpera(data, method) {
      this.$emit(method, data);
    },
  },
};
</script>

<style lang="less" scoped></style>
