<template>
  <div>
    <EasyTable
      ref="EasyTable"
      v-model="tableData"
      v-loading="tableLoading"
      :fields="fields"
      :row-key="editTableConfig.rowKey"
      :table-config="tableConfig"
      :buttons="tableButtons"
      :total="total"
      @current-change="$emit('current-change',$event)"
      @current-size="$emit('size-change',$event)"
    />
    <el-dialog
      :visible.sync="dialogVisible"
      :title="getPropValue(editTableConfig.dialogTitle,editRowClone)"
      v-bind="editTableConfig.dialogProps"
    >
      <EasyForm
        ref="EasyForm"
        v-model="editRowClone"
        v-loading="formLoading"
        :fields="fields"
        :form-config="formConfig"
        :buttons="formButtons"
        @cancel="dialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script>
import EasyTable from '../EasyTable'
import EasyForm from '../EasyForm'
export default {
  name: 'EditTable',
  components: {
    EasyTable,
    EasyForm
  },
  props: {
    fields: {
      type: Array,
      default: () => {
        return []
      }
    },
    value: {
      type: Array,
      required: true
    },
    formConfig: {
      type: Object,
      default: () => {
        return {}
      }
    },
    tableConfig: {
      type: Object,
      default: () => {
        return {}
      }
    },
    formButtons: {
      type: Array,
      default: () => {
        return []
      }
    },
    tableButtons: {
      type: Array,
      default: () => {
        return []
      }
    },
    editTableConfig: {
      type: Object,
      default: () => {
        return {}
      }
    },
    total: {
      type: Number,
      default: () => {
        return 0
      }
    }
  },
  data() {
    return {
      dialogVisible: false,
      editRowClone: {},
      formLoading: false,
      tableLoading: false
    }
  },
  computed: {
    tableData() {
      return this.value
    },
    pageParam() {
      return this.$refs.EasyTable.pageParam
    }
  },
  watch: {
    dialogVisible(newValue, oldValue) {
      if (!newValue && oldValue) {
        this.editRowClone = {}
      }
    }
  },
  methods: {
    getPropValue(prop, ...args) {
      return typeof prop === 'function' ? prop(...args) : prop
    },
    editRow(row) {
      this.editRowClone = JSON.parse(JSON.stringify(row))
      this.dialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.EasyForm) {
          this.$refs.EasyForm.clearValidate()
        }
      })
    }
  }
}
export const template = {
  data() {
    return {
      editTableConfig: {
        dialogProps: {},
        rowKey: 'id'
      }
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
