<template>
  <div class="table-div">
    <el-table
      row-key="id"
      :scroll="scroll"
      :data="cData"
      :stripe="stripe"
      :border="border"
      :row-class-name="rowClassName.class || function () { return null }"
      @clearSelection="onChange"
      @toggleRowSelection="onChange"
      @toggleAllSelection="onChange"
      @toggleRowExpansion="onChange"
      @setCurrentRow="onChange"
      @clearSort="onChange"
      @clearFilter="onChange"
      @doLayout="onChange"
      @sort="onChange"
    >
      <el-table-column v-for="column in columns" v-bind="column">
        <!-- 多级表头（最多支持三级） -->
        <!-- <el-table-column v-for="column1 in column.children" 
          v-bind="column1">
          <el-table-column v-if="column1.children" v-for="column2 in column1.children" 
            v-bind="column2">
          </el-table-column>
        </el-table-column> -->

        <!-- 操作按钮 -->
        <template v-if="column.type == 'action'" #default="scope">
          <el-button
            v-if="isFlatAction"
            v-for="action in cActions"
            v-bind="getActionProps(action)"
            @click="callback"
          >{{ action.name }}</el-button>

          <!-- TODO: 增加下拉选择的多按钮 -->
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import _ from 'lodash';

export default {
  name: "HmElementTable",
  components: {},
  props: {
    /**
     * 列定义
     */
    columns: {
      type: Array,
      default: function () {
        return [
          {
            type: "selection"
          },
          {
            label: "姓名",
            prop: "name",
            children: [{
              label: "姓",
              prop: "familyName",
              columnKey: "familyName",
              fixed: true
            }, {
              label: "名",
              prop: "givenName",
              columnKey: "givenName",
              fixed: true
            }]
          },
          {
            label: "年龄",
            prop: "age",
            columnKey: "age",
            width: 80,
          },
          {
            label: "地址",
            prop: "address",
            columnKey: "address",
            ellipsis: true,
          },
          {
            label: "性别",
            prop: "sexual",
            columnKey: "sexual",
          },
          {
            label: "毕业院校",
            prop: "school",
            columnKey: "school",
          },
          {
            label: "操作",
            type: 'action',
          },
        ];
      },
    },
    /**
     * 数据
     */
    data: {
      type: Array,
      default: function () {
        return [
          {
            key: "1",
            name: "李四",
            familyName: '李',
            givenName: '四',
            age: 32,
            address: "北京",
            sexual: "男",
            school: "加里敦大学",
          },
          {
            key: "2",
            name: "张三",
            familyName: '张',
            givenName: '三',
            age: 42,
            address: "北京",
            sexual: "男",
            school: "加里敦大学",
          },
          {
            key: "3",
            name: "王五",
            familyName: '王',
            givenName: '五',
            age: 32,
            address: "深圳",
            sexual: "男",
            school: "加里敦大学",
          },
        ];
      },
    },
    /**
     * 是否为斑马纹
     */
    stripe: {
      type: Boolean,
      default: false
    },
    /**
     * 是否纵向边框
     */
    border: {
      type: Boolean,
      default: false
    },
    /**
     * 隐藏翻页控件
     */
    paginationHidden: {
      type: Boolean,
      default: false
    },
    /**
     * 翻页参数
     */
    pagination: {
      type: Object,
      default: function () {
        return {
          current: 1,
          pageSize: 10,
        };
      },
    },
    /**
     * 显示序号列
     */
    showColumnNo: {
      type: Boolean,
      default: false
    },
    /**
     * GET URL
     */
    url: {
      type: String,
    },
    /**
     * GET Params
     */
    params: {
      type: Object,
    },
    /**
     * 可选择行
     */
    rowSelectFlag: {
      type: Boolean,
      default: false,
    },
    /**
     * 带边框
     */
    bordered: {
      type: Boolean,
      default: true,
    },
    /**
     * 操作按钮
     */
    actions: {
      type: Array,
      default: function () {
        return [
          {
            name: "编辑",
            type: 'primary',
            callback: function (item) {
              console.log("点击编辑: ", item);
            },
          },
          {
            name: "删除",
            type: 'danger',
            callback: function (item) {
              console.log("点击删除: ", item);
            },
          },
        ];
      },
    },
    /**
     * 操作按钮展开
     */
    isFlatAction: {
      type: Boolean,
      default: true,
    },
    /**
     * 固定行列
     */
    scroll: {
      type: Object,
      default: function () {
        return {
          x: "100%",
        };
      },
    },
    /**
     * 自动合并单元
     * @description 数据相同的内容自动合并. 形如 ["r1c1:r10c1", "r2c2:r10c2", "r1:r2", "c4"]，这里的r1c1表示的是第1行（row 1），第1列（column 1）。第1列不包含表格，指的是数据行。
     */
    combined: {
      type: Array,
      default: [],
    },
    /**
     * 清空过滤排序
     */
    clearFiltersAndSortersFlag: {
      type: Boolean,
      default: false
    },
    /**
     * 行高
     */
    rowHeight: {
      type: String,
      default: '42'
    },
    /**
     * 表格背景颜色
     * @type Color
     * */
    backgroundColor: {
      type: String,
      default: ""
    },
    /**
     * 行类名
     */
    rowClassName: {
      type: Object,
      default: function () {
        return {
          class: null
        }
      }
    }
  },
  data() {
    return {
      cData: [],
      cColumns: [],
      cActions: [],
      cRowHeight: '42px',
      rowSelection: {},
      cPagination: {
        current: 1,
        pageSize: 10,
      },
      sorter: {},
      filters: {},
      cBackgroundColor: ''
    };
  },
  watch: {
    combined: {
      handler: function (value, oldValue) {
        console.log('watch combined');
        this.hmTable.combined = value;
        this.cColumns = this.hmTable.getCombinedColumns();
        if (this.showColumnNo) {
          this.cColumns.unshift({
            title: "序号",
            dataIndex: "hmNo",
            key: "hmNo",
            width: 60
          })
        }
      },
      deep: true
    },
    clearFiltersAndSortersFlag(value, oldValue) {
      console.log(`清除过滤和排序：`, value, oldValue);
      if (!oldValue && value) {
        this.filters = {};
        this.sorter = {};
        this.getData();
      }
    },
    columns: {
      handler: function (value, oldValue) {
        console.log('watch columns');
        this.hmTable.columns = value;
        this.cColumns = this.hmTable.getCombinedColumns();
        if (this.showColumnNo) {
          this.cColumns.unshift({
            title: "序号",
            dataIndex: "hmNo",
            key: "hmNo",
            width: 60
          })
        }
      },
      deep: true
    },
    data: {
      handler: function (value, oldValue) {
        console.log('watch data');
        this.cData = JSONfn.parse(JSONfn.stringify(value));

        if (this.showColumnNo) {
          _.each(self.cData, (item, index) => {
            item.hmNo = index + 1;
          })
        }

        this.hmTable.data = this.cData;
      },
      deep: true
    },
    actions: {
      handler: function (value, oldValue) {
        console.log('watch actions');
        this.cActions = this.convertActions(value);
      },
      deep: true
    },
    url(value) {
      this.getData(value);
    },
    params: {
      handler: function (value, oldValue) {
        if (JSON.stringify(value) == JSON.stringify(oldValue)) {
          // 修复相等的情况下也调用watch的bug
          return;
        }
        console.log('watch params');
        this.getData(null, value);
      },
      deep: true
    },
    pagination: {
      handler(value) {
        if (Object.keys(value).length === 0) {
          this.cPagination = false;
        } else {
          this.cPagination = Object.assign(this.cPagination, this.pagination);
        }
        console.log(`table watch pagination: `, this.cPagination, this.pagination);
        // this.getData();
      },
      deep: true
    },
    rowHeight(value) {
      this.cRowHeight = this.getCssUnit(value);
    },
    backgroundColor(value) {
      this.cBackgroundColor = value;
    }
  },
  computed: {
  },
  mounted() {
    console.log('mounted');
    this.cData = _.cloneDeep(this.data);
    this.cActions = this.convertActions(this.actions);
  },
  methods: {
    convertActions(actions) {
      let ret = [];
      _.each(actions, (action) => {
        if (
          action.callback &&
          typeof action.callback === "string" &&
          action.callback.indexOf("function") === 0
        ) {
          try {
            action.callback = eval(`(${action.callback})`);
          } catch (error) {
            console.error('action.callback error: ', action);
          }
        }
        ret.push(action);
      });
      console.log(`cActions: `, ret);
      return ret;
    },
    getActionProps(action) {
      let actionProps = _.cloneDeep(action);
      delete actionProps.callback;
      return actionProps;
    }
  },
};
</script>

<style scoped>
.table-div {
  position: relative;
  display: flex;
  align-items: center;
  min-width: 300px;
  width: 100%;
}
</style>