<template>
  <el-table 
    class="guip-table" 
    ref="guiptable" 
    v-bind="$attrs" 
    :data="tableData"  
    v-on="$listeners" 
    :border="border" 
    @selection-change="handleSelectionChange"
    :style="{ width: width || '100%', height: height || '100%' }" 
    v-loading="loading">
    
    <!-- 多选列 -->
    <el-table-column 
      v-if="multiple"
      type="selection" 
      width="55">
    </el-table-column>
    
    <!-- 优先使用插槽内容 -->
    <slot>
      <!-- 如果没有插槽内容，则使用 columns 渲染 -->
      <template v-if="columns">
        <el-table-column 
          v-for="column in columns" 
          :key="column.prop" 
          :prop="column.prop" 
          :label="column.label"
          :width="column.width">
          
          <template #default="{ row }" v-if="column.popover">
            <el-popover :visible="row[`popoverVisible_${column.prop}`]" placement="top" trigger="click">
              <slot :name="`popover-content-${column.prop}`" :row="row" :column="column">
                <div>
                  <p>默认内容：{{ `popoverVisible_${column.prop}` }}</p>
                  <el-input v-model="row[`edit_${column.prop}`]" :placeholder="`请输入${column.label}`" />
                </div>
              </slot>
              <div class="flex" style="text-align: right; margin-top: 32px;justify-content: flex-end;">
                <GuipButton size="medium" @click="handleCancel(row, column.prop)">取消</GuipButton>
                <GuipButton type="primary" @click="handleConfirm(row, column.prop)" size="medium">确定</GuipButton>
              </div>
              <template #reference>
                <span style="cursor: pointer">{{ row[column.prop] }}</span>
              </template>
            </el-popover>
          </template>
        </el-table-column>
      </template>
    </slot>
    
    <template #empty>
      <el-empty :image="emptyImg"></el-empty>
    </template>
  </el-table>
</template>

<script>
import GuipButton from '../../GuipButton/src/index.vue';

export default {
  name: 'GuipTable',
  props: {
    tableData: Array,
    loading: Boolean,
    width: String,
    height: String,
    columns: Array,
    border: Boolean,
    multiple: Boolean
  },
  components: {
    GuipButton
  },
  data() {
    return {
      emptyImg: require('../../assets/table_empty.png')
    }
  },
  methods: {
    handleSelectionChange(row) {
      this.$emit('selectChange', row)
    },
    handleConfirm(row, prop) {
      row[prop] = row[`edit_${prop}`];
      row[`popoverVisible_${prop}`] = false;
      this.$emit('confirm', row, prop);
    },
    handleCancel(row, prop) {
      row[`edit_${prop}`] = row[prop];
      row[`popoverVisible_${prop}`] = false;
      this.$emit('cancel', row, prop);
    }
  }
}
</script>