<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">
              <template v-if="display(item, row)">
                <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, item.confirm, item.methodZh, item.label, $index)"
                  ></el-button>
                </el-tooltip>
              </template>
            </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: () => [] },
    toFormat: null,
  },
  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;
          if (_.isFunction(format)) {
            res = format(cellValue);
          } else {
            res = this.toFormat({
              model: this_fields[0].prop,
              value: cellValue,
            });
          }
          return res;
        } else return cellValue;
      }
    },
    handleOpera(data, method, confirm = false, methodZh, label, index) {
      if (!methodZh) {
        methodZh = label;
      }
      if (confirm) {
        this.$confirm(`您确认${methodZh}该数据?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            this.$emit(method, { data, index });
          })
          .catch(() => {});
      } else {
        this.$emit(method, { data, index });
      }
    },
    display(item, row) {
      let display = _.get(item, `display`, true);
      if (display === true) return true;
      else {
        let res = display(row);
        return res;
      }
    },
  },
};
</script>

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