/**
 *  1.简化数据源绑定
 *  2.双向绑定选择行、及交互
 *  3. 插槽规范: 扩展、header content
 *  4. treeTable
 *  5 header 分组
 *  6. 行分组
 *  7.footer 统计
 *  
 *  @author xiufu.wang
 */
import ElTable from 'mars-pro/packages/table';
import ElPagination from 'mars-pro/packages/pagination';
import ELTableColumn from 'mars-pro/packages/table-column';
import { objectProperty, isObject, isArray } from 'mars-pro/src/pro/util';
import omit from 'mars-pro/src/pro/omit';
const sortArray = (order) => {
    return order.indexOf(a.prop) - order.indexOf(b.prop);
}
export default {
    name: 'ProDataTable',
    componentName: 'ProDataTable',
    inheritAttrs: false,
    components: {
        ElTable,
        ElPagination,
        ELTableColumn
    },
    props: {
        data:Array,
        //数据源
        dataSource: [Object, Array],
        //是否启用分页
        enablePagination: {
            type: Boolean,
            default: true
        },
        //列配置
        columns: Array,
        //选择模式 single | multiple
        selectModel: [String, Boolean],
        //行选择,如果要支持跨页选择,请设置{ type:'selection', reserveSelection: true }
        selectRows: [Object, String, Array, Number],
        //指定selectModel时,rowKey必须要配置 
        rowKey: {
            type: String,
            default: 'id'
        },
        //当多选模式下, 是否启用点击行选择
        enableClickRowSelect: {
            type: Boolean,
            default: false
        },
        //显示序号
        enableIndex: {
            type: Boolean,
            default: false
        },
        //显示序号依赖分页信息
        enableStrictIndex: {
            type: Boolean,
            default: false
        },
        // footer统计: 来自与数据源
        summaryData: Object,
        rowColor:{
            type: String,
            default: ''
        },
        //控制select 列是否可选
        selectable: Function,
        selectionConfig: {
            type: Object,
            default: null
        }
    },
    watch: {
        selectRows() {
            this.setRowSelected()
        },
        tableDatas() {
            this.setRowSelected(true)
        }
    },
    
    computed: {
        tableDatas() {
            const dataSource = this.dataSource
            if (dataSource && dataSource.isDataSource == true) {
                return dataSource.formatDatas
            }
            return dataSource || (this.data || [])
        },
        paginationProps() {
            const dataSource = this.dataSource
            if (dataSource && dataSource.isDataSource == true) {
                return dataSource.pagination
            }
            return null
        },
        paginationOn() {
            const dataSource = this.dataSource
            if (dataSource && dataSource.isDataSource == true) {
                return {
                    'size-change': dataSource['size-change'],
                    'current-change': dataSource['current-change'],
                }
            }
            return null
        },
        showLoading() {
            const dataSource = this.dataSource
            if (dataSource && dataSource.isDataSource == true) {
                return dataSource.loading
            }
            return this.$attrs.loading
        }
    },
    methods: {
        renderSlots(){
            const slots = omit(this.$slots || {}, ['default'])
            return Object.keys(slots).map(item => (
                <template slot={item}>{ slots[item] }</template>
            ))
        },
        //渲染列
        renderColumns(childColumns, level) {
            let columns = childColumns
            const scopeSlots = this.$scopedSlots
            if (!columns || columns.length === 0) {
                return null
            }
            columns = [].concat(columns)
            //包含扩展插槽
            if (level === 1 && scopeSlots.expand) {
                const hasExpand = columns.filter(c => c.type === 'expand').length > 0
                if (!hasExpand) {
                    columns.unshift({
                        type: 'expand'
                    })
                }
            }

            //多选
            if (level === 1 && this.selectModel === 'multiple') {
                const hasExpand = columns.filter(c => c.type === 'selection').length > 0
                if (!hasExpand) {
                    columns.unshift({
                        type: 'selection',
                        width: 55,
                        selectable: this.selectable,
                        reserveSelection: !(this.$attrs['tree-props'] || this.$attrs['treeProps']),
                        ...(this.selectionConfig || {})
                    })
                }
            }
            //多选
            if (level === 1 && (this.enableIndex || this.enableStrictIndex)) {
                const hasIndex = columns.filter(c => c.type === 'index').length > 0
                if (!hasIndex) {
                    columns.unshift({
                        type: 'index'
                    })
                }
            }
            return (
                columns.map((col) => (
                    <ELTableColumn key={col.prop || col.type} {...{ props: {'show-overflow-tooltip': true, ...omit(col, 'children')}, attrs: col }} scopedSlots={{
                        ...(scopeSlots[`${col.prop}Header`] ? { header: scopeSlots[`${col.prop}Header`] } : {}),
                        ...(scopeSlots[`${col.prop}Content`] ? { default: scopeSlots[`${col.prop}Content`] } : {}),
                        ...(level === 1 && col.type === 'expand' && scopeSlots.expand ? { default: scopeSlots.expand } : {})
                    }}>
                        {this.renderColumns(col.children, level + 1)}
                    </ELTableColumn>
                ))
            )
        },
        //设置行选择
        setRowSelected() {
            const selectModel = this.selectModel
            let selectRows = this.selectRows
            const rowKey = this.rowKey
            if (!selectModel) {
                return
            }
            //多选
            if (selectModel === 'multiple') {
                selectRows = selectRows || []
                selectRows = isArray(selectRows) ? selectRows : [selectRows]
                const selection = selectRows.map(r => isObject(r) ? r : { [rowKey]: r })
                this.$refs.eltable.store.states.selection = selection;
                this.$refs.eltable.store.updateSelectionByRowKey()
            } else {//单选
                if (selectRows && isArray(selectRows)) {
                    selectRows = selectRows[0]
                }
                const key = isObject(selectRows) ? selectRows[rowKey] : selectRows
                this.$refs.eltable.store.setCurrentRowKey(key);
            }
        },
        //处理选择行
        handleSelectRows(currentRow, oldCurrentRow, isDataChange) {
            this.$emit('tcurrent-change', currentRow, oldCurrentRow, isDataChange)
            //没有启用选择模式
            if (!this.selectModel) {
                return
            }
            if (this.enableClickRowSelect === true && this.selectModel === 'multiple') { 
                this.$refs.eltable.store.toggleRowSelection(currentRow)
                return
            }
            if (this.selectModel !== 'multiple') { 
                this.$emit('update:selectRows', this.$refs.eltable.store.states.currentRow, isDataChange)
                this.$emit('selectRows', this.$refs.eltable.store.states.currentRow, isDataChange)
            }
            
        },
        //处理checkbox选择行
        handleSelectCheckbox(sels) {
            this.$emit('selection-change', sels)
            //没有启用选择模式
            if (!this.selectModel || this.selectModel !== 'multiple') {
                return
            }
            this.$emit('update:selectRows', this.$refs.eltable.store.states.selection)
            this.$emit('selectRows', this.$refs.eltable.store.states.selection)
        }
    },
    render() {
        const _datas = {
            'class': {
                'pro-data-table': true,
                'pro-data-table--pagination': this.enablePagination
            }
        }
        const _tableDatas = {
            props: {
                border: false,
                stripe: false,
                'highlight-current-row': !!this.selectModel,
                data: this.tableDatas || [],
                rowKey: this.rowKey,
                enableStrictIndex: this.enableStrictIndex,
                ...(this.paginationProps || {}),
                load: (this.dataSource || {}).tableAsyncTreeload,
                summaryData: this.dataSource && this.dataSource.isDataSource ? this.dataSource.getSummaryData() : this.summaryData,
                spanMethod:  this.dataSource && this.dataSource.isDataSource ? this.dataSource.getSpanMethod() : null,
                ...this.$attrs
            },
            attrs: {
                'element-loading-spinner': 'el-icon-loading',
                'element-loading-font-size': '30px',
                'element-loading-text': '加载中....',
                'element-loading-custom-class': 'pro-data-table--loading',
                'row-style':({rowIndex})=>{
                    if (rowIndex%2 == 1) {
                        return { backgroundColor: this.rowColor };
                    }else{
                        return {}
                    }
                },
                ...this.$attrs
            },
            on: {
                // 解决分页和表格存在重复事件命名current-change
                ...omit(this.$listeners, ['current-change', 'currentChange']),
                'current-change': this.handleSelectRows,
                'selection-change': this.handleSelectCheckbox,
            },
            directives: [
                {
                    name: 'loading',
                    value: this.showLoading
                }
            ]
        }

        const _paginationDatas = {
            props: {
                layout: 'total, sizes, prev, pager, next, jumper',
                ...(this.paginationProps || {}),
                disabled: this.showLoading,
                ...this.$attrs
            },
            attrs: {
                ...this.$attrs
            },
            on: {
                ...(this.paginationOn || {}),
                ...this.$listeners
            }
        }
        return (
            <div {..._datas}>
                <ElTable {..._tableDatas} ref="eltable">
                    {this.$slots.default}
                    {this.renderColumns(this.columns, 1)}
                    {this.renderSlots()}
                </ElTable>
                {this.enablePagination && (
                    <ElPagination {..._paginationDatas}></ElPagination>
                )}
            </div>
        )
    },
    mounted() {
        this.setRowSelected()
    }
}