<template>
  <div class="table-page-template" ref="tablePageTemplate">
      <div class="table-page-wrapper">
          <!-- 右侧表格结构 -->
          <div class="table-page-right">
            <div class="wrapper" :style="{padding: currentTableConfig.padding}">
                <div class="title" v-if="currentTableConfig.title!==''">{{ currentTableConfig.title }}</div>
                <div class="filter-bar">
                    <!-- toolBar -->
                <mu-tool-bar v-model="searchParams" :config="toolbarConfig"
                                @on-search-change="onSearchChange" :extension="extensionFilter">
                </mu-tool-bar>
                </div>
                <mu-table-simple ref="tableWrapper" class="tableWrapper" v-model="tableListEdit" :config="tableConfig" :extension="extensionTable">
                    <mu-table-column :config="{ type:'operation', 
                                    label: tableConfig.operates.label ? tableConfig.operates.label : '操作', 
                                    fixed: tableConfig.operates.fixed ? tableConfig.operates.fixed : 'right', 
                                    width: tableConfig.operates.operateWidth ? tableConfig.operates.operateWidth : '200', 
                                    align: tableConfig.operates.align ? tableConfig.operates.align : 'center'}">
                        <template slot-scope="{row, column, $index}">
                            <!-- 行内编辑事件 -->
                            <mu-tool-bar v-model="searchParamsOperates" :config="getTableOperatesConfig(tableConfig.operates, {row, column, $index} )">
                            </mu-tool-bar>
                        </template>
                    </mu-table-column>
                </mu-table-simple>

                <mu-pagination :page.sync="searchParams.page"
                           :page-size.sync="searchParams.limit" :total="PaginationConfig.total"
                           :config="PaginationConfig" @on-change="pageChange"/>
            </div>
          </div>
          <!-- 右侧表格结构 -->
      </div>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch, Emit } from 'vue-property-decorator';

interface TableConfig {
    name?: string,
    rowKey: string | number,
    size?: string,
    height?: string | number,
    maxHeight?: string | number,
    showIndex?: boolean,
    showSelection?: boolean,
    selectFixed?: boolean,
    indexFixed?: boolean,
    disabled?: boolean,
    sourceConfigs?: any,
    selection?: any,
    tabChildren?: any,
    isLazy?: boolean,
    cellStyle?: any,
    tabChildrenIndex?: any,
    load?: Function,
    currentChange?: Function,
    isCurrentChange?: Function,
    highlightCurrentRow?: boolean,
    defaultExpandAll?: boolean,
    expandRowKeys?: any,
    currentRowKey: string | number,
    showSummary?: boolean,
    sumText?: string,
    summaryMethod?: Function,
    spanMethod?: Function,
    onSelect?: Function,
    onSelectAll?: Function,
    rowClick?: Function
    border?: boolean,
    stripe?: boolean,
    columns?: any,
    operates?: any
}

@Component({
    name: 'muTablePageTemplate'
})

export default class extends Vue { 
    @Prop({ default: () => [] }) private tableData: any;
    @Prop({ default: () => {} }) private searchParams: any;
    @Prop({ default: () => {} }) private toolbarConfig: any;
    @Prop({ default: () => {} }) private PaginationConfig: any;
    @Prop({ default: () => {} }) private tableConfig!: TableConfig;
    private handleSource: any = undefined;
    private handleEdit: any = undefined;
    private tableListEdit: any = [];
    private addStatus: boolean = false;
    private editStatus: boolean = false;
    private setNodeLevel: any = undefined;
    private setDisabled: any = undefined;
    private handleTable: any = {};
    private defaultConfig: any = {
        width: "200px",
        title: '',
        padding: 0,
        autoSize: false
    };
    private searchParamsOperates:any = {}

    // 合并默认数据
    get currentTableConfig() {
      const result = this.tableConfig;
      Object.keys(this.defaultConfig).forEach((key: string) => {
        if (this.tableConfig[key] === undefined) result[key] = this.defaultConfig[key];
      });
      return result;
    }


    mounted() {
      this.tableListEdit = JSON.parse(JSON.stringify(this.tableData));
      this.handleSource && this.handleSource('load', {}, () => {
      });
      this.handleTable.onHandleData && this.handleTable.onHandleData('load', this.searchParams, () => {
      });
      
      if(this.currentTableConfig.autoSize) {
        let top: number = 0, bottom: number = 0, tableContainer: any, min: number = 250, tableHeight: any;
        this.$nextTick(() => {
            const template: any = this.$refs.tablePageTemplate;
            tableContainer = template.getElementsByClassName("tableWrapper")[0];
            const height = template.offsetHeight;
            const clientHeight = document.documentElement.clientHeight;
            top = tableContainer.getBoundingClientRect().top;
            bottom = clientHeight - tableContainer.getBoundingClientRect().bottom;
            tableHeight = tableContainer.offsetHeight;
            // console.log(top, bottom, height)
        })
        window.onresize = () => {
            const currentClientHeight = document.documentElement.clientHeight;
            let currentTableHeight = currentClientHeight - top - bottom;
            if (currentTableHeight < min || tableHeight < min) {
                // 缩放高度 或者 当前表格高度小于最小高度时
                currentTableHeight = min
            }
            tableContainer.getElementsByClassName("el-table")[0].style.height = currentTableHeight + "px";
            tableContainer.getElementsByClassName("el-table")[0].style.overflow = "auto";
        }  
      }
      
      
    }

    @Watch('tableData')
    onTableDataChange(val: any) {
        this.tableListEdit = JSON.parse(JSON.stringify(val));
    }

    getTableOperatesConfig(config, scoped) {
        let currentConfig = Object.assign({}, config);
        currentConfig['scoped'] = scoped;
        return currentConfig;
    }
    onSearchChange(params, key) {
        if (key === 'searchInput') {
        this.tableListEdit = JSON.parse(JSON.stringify(this.tableData.filter((item) => item.name && item.name.indexOf(this.searchParams.searchInput) > -1)));
        console.log('查询数据', this.searchParams);
        }
    }
    /**
     * 扩展的table函数
     * @param table
     * @param value
     */
    extensionTable(table, value) {
        this.$emit("get-table-node", table)
        this.handleTable = value;
    }
    
    pageChange(value: any) {
        this.$emit('page-change', value)
    }
    handleData(type, data, callback) {
        this.handleTable.onHandleData(type, data, () => {
        this.addStatus = this.handleTable.getAddStatus();
        this.editStatus = this.handleTable.getEditStatus();
        this.setDisabled({
            add: !!this.addStatus || !!this.addStatus,
            reload: !!this.addStatus || !!this.addStatus
        });
        });
    }
    extensionFilter(val) {
        this.setFieldsValue = val.setFieldsValue;
        this.setReset = val.setReset;
        this.reinitialize = val.reinitialize;
        this.setDisabled = val.setDisabled;
    }
    /**
     * 展开编辑
     * @params type 编辑类型
     */
    showEdit(type, data) {
        this.handleTable.onHandleEdit(type, data);
        this.editStatus = this.handleTable.getEditStatus();
        this.setDisabled({
        add: !!this.addStatus || !!this.editStatus,
        reload: !!this.addStatus || !!this.editStatus
        });
    }
    showAdd(type, data) {
        this.handleTable.onHandleAdd(type, data);
        this.addStatus = this.handleTable.getAddStatus();
        this.setDisabled({
        add: !!this.addStatus || !!this.editStatus,
        reload: !!this.addStatus || !!this.editStatus
        });
    }
}

</script>
<style>
    .el-button.mu-button-text{
        padding: 3px 3px;
    }
    .btn-start, .btn-end {
        width: auto!important;
        height: auto!important;
    }
</style>

<style lang="scss" scoped>
    .table-page-template{
        width: 100%;
        .table-page-wrapper {
            .table-page-right{
                width: 100%;
                .wrapper {
                    // padding: 15px;
                    >.title {
                        width: 100%;
                        padding: 5px 0;
                        font-size: 18px;
                        text-align: left;
                    }
                    .tableWrapper {
                        margin-bottom: 20px;
                    }
                }
            }
        }
    }
</style>