/**
 * 明细表格
 * @author xiufu.wang
 */
import { getAllChildren, getAllProps, cloneElement } from 'mars-pro/src/pro/vue-util';
import { objectProperty } from 'mars-pro/src/pro/util'
import ProDataTable from 'mars-pro/packages/pro-data-table';
import ProDetail from 'mars-pro/packages/pro-detail';
import { renderVnodeTemplate } from '../util'
import omit from 'mars-pro/src/pro/omit';
import { noop } from 'mars-pro/src/utils/util';
let customer_prop = 0;

export default {
    name: 'TablesRegion',
    componentName: 'TablesRegion',
    components: {
        ProDataTable,
        ProDetail
    },
    props: {
        // 数据
        datas: Array,
        prop: String,
        model: Object,
        dataKey: String,
        //用于注入渲染控制逻辑
        renderItem: {
            type: Function,
            default: noop
        },
        //编辑模式: row | cell | all
        editType: {
            type: String,
            default: 'row'
        },
        //编辑触发方式: dblclick | click
        editTigger: {
            type: String,
            default: 'click'
        },
        //禁用操作列
        disableActionCol: {}
    },

    data() {
        return {
            //当前编辑行
            editRowIndex: -1,
            //当前编辑单元格
            editRowCell: []
        }
    },
    watch: {
        '$parent.enableDetail': function () {
            this.forceChange = 1
            if (this.$parent.enableDetail) { 
                this.editRowCell = []
                this.editRowIndex = -1
            }
        }
    },
    methods: {
        handleCellClick({ tigger, rowIndex, colIndex }) {
            if (this.$parent.enableDetail) { 
                return
            }
            if (tigger === this.editTigger) { 
                if (this.editType === 'cell' && (this.editRowCell[0] !== rowIndex || this.editRowCell[1] !== colIndex)) { 
                    this.editRowCell = [rowIndex, colIndex]
                }
                if (this.editType === 'row' && this.editRowIndex !== rowIndex) { 
                    this.editRowIndex = rowIndex
                }
            }
        },
        renderSlots() {
            const slots = omit(this.$slots || {}, ['default'])
            return Object.keys(slots).map(item => (
                <template slot={item}>{slots[item]}</template>
            ))
        },
        isUseAction(useColumns) {
            return (useColumns || this.useColumns).filter(r => {
                const c = r.useVnode
                if (objectProperty(c, 'data.attrs.use-def') === 'action') {
                    return true
                }
                return false
            }).length > 0
        },
        updateCols(useColumns) {
            //如果用户自定义use-def='action' 则忽略
            //const useDef = objectProperty(c, 'data.attrs.use-def')
            const hasUseAction = this.isUseAction(useColumns)
            if (this.disableActionCol === true || hasUseAction || this.$parent.enableDetail === true) {
                this.useColumns = useColumns
                return
            }
            this.useColumns = useColumns.concat([{
                width: '80px',
                label: '操作',
                prop: 'action'
            }])
        },
        resolveUseColumns() {
            const childrens = getAllChildren(this).filter(r => !!(r.tag))
            let useColumns = childrens.map((c, index) => {
                const childAttrs = getAllProps(c)
                if (!childAttrs.label) {
                    return null
                } 
                return {
                    ...childAttrs,
                    prop: childAttrs.prop || 'customer-' + (customer_prop++),
                    useVnode: c,
                    colIndex: index
                }
            })
            return useColumns.filter(r => !!r)
        },
        resolveTableCols() {
            let useColumns = this.resolveUseColumns()
            if (!this.useColumns) {
                this.updateCols(useColumns)
            } else {
                const a = (this.isUseAction() ? this.useColumns : this.useColumns.slice(0, this.useColumns.length - 1)).map(r => `${r.label}|${r.prop}|${r.width}}`).join(',')
                const b = useColumns.map(r => `${r.label}|${r.prop}|${r.width}}`).join(',')
                if (a !== b || this.forceChange > 0) {
                    this.updateCols(useColumns)
                    this.forceChange = 0
                }
            }
            return this.useColumns
        },
        // 如果标记为is-text 者代表普通的col定义,否者为静态文本或者控件
        createRenderScopedSlots() {
            let useColumns = this.resolveUseColumns()
            const that = this
            const defs = useColumns.filter(r => {
                const attrs = objectProperty(r.useVnode, 'data.attrs')
                return !('is-text' in attrs)
            })
            const scopedSlots = defs.reduce((m, col, index, arrs) => {
                // row 数据 $index 行号
                let currentRowComponentInstances = {}
                m[`${col.prop}Content`] = function ({ row, $index }) {
                    let vnode = null
                    // 处理编辑交互
                    if (that.$parent.enableDetail !== true && that.editType !== 'all') {
                        const editType = that.editType
                        const editTigger = that.editTigger
                        const editRowIndex = that.editRowIndex
                        const editRowCell = that.editRowCell

                        // 航模式
                        if (editType === 'row') {
                            vnode = renderVnodeTemplate(that, col.useVnode, $index, index, currentRowComponentInstances, true, false, $index !== editRowIndex)
                            const vnodeAttrs = objectProperty(col.useVnode, 'data.attrs')
                            const editable = ('is-edit' in vnodeAttrs)
                            const _datas = {
                                'class': {
                                    'editing': ('is-edit' in vnodeAttrs && $index == editRowIndex),
                                    'editable': editable
                                },
                                on: {
                                    dblclick: function () {
                                        if (!editable) {
                                            return
                                        }
                                        that.handleCellClick({
                                            tigger: 'dblclick',
                                            rowIndex: $index,
                                            colIndex: index
                                        })
                                    },
                                    click: function () {
                                        if (!editable) {
                                            return
                                        }
                                        that.handleCellClick({
                                            tigger: 'click',
                                            rowIndex: $index,
                                            colIndex: index
                                        })
                                    }
                                }
                            }
                            vnode = <div {..._datas}>{vnode}</div>
                        }
                        // 单元格模式
                        if (editType === 'cell') {
                            vnode = renderVnodeTemplate(that, col.useVnode, $index, index, currentRowComponentInstances, true, false, !($index === editRowCell[0] && index === editRowCell[1]))
                            const vnodeAttrs = objectProperty(col.useVnode, 'data.attrs')
                            const editable = ('is-edit' in vnodeAttrs)
                            const _datas = {
                                'class': {
                                    'editing': ('is-edit' in vnodeAttrs && ($index === editRowCell[0] && index === editRowCell[1])),
                                    'editable': editable
                                },
                                on: {
                                    dblclick: function () {
                                        if (!editable) {
                                            return
                                        }
                                        that.handleCellClick({
                                            tigger: 'dblclick',
                                            rowIndex: $index,
                                            colIndex: index
                                        })
                                    },
                                    click: function () {
                                        if (!editable) {
                                            return
                                        }
                                        that.handleCellClick({
                                            tigger: 'click',
                                            rowIndex: $index,
                                            colIndex: index
                                        })
                                    }
                                }
                            }
                            vnode = <div {..._datas}>{vnode}</div>
                        }
                    } else {
                        vnode = renderVnodeTemplate(that, col.useVnode, $index, index, currentRowComponentInstances, true)
                    }
                    return vnode
                }
                return m
            }, {})

            // 处理默认操作列
            if (!that.isUseAction()) {
                if(!that.$scopedSlots.actionContent){
                    scopedSlots['actionContent'] = function ({ row, $index }) {
                        if (that.$parent.enableDetail === true) {
                            return null
                        }
                        return (
                            <div class="files-region-list-item--action form-region-list-item--action"  {...{ attrs: { 'data-index': $index } }} on-click={that.$parent.removeItem}>
                                <i class="close el-icon-close"></i>
                            </div>
                        )
                    }
                }else{
                    scopedSlots['actionContent'] = function ({ row, $index }) {
                        if (that.$parent.enableDetail === true) {
                            return null
                        }
                        return that.$scopedSlots.actionContent({removeItem:that.$parent.removeItem,index:$index})
                    }
                }
                
            }
            return scopedSlots
        }
    },
    render() {
        const useColumns = this.resolveTableCols();
        const _datas = {
            props: {
                border: true,
                emptyText: '暂无任何附件',
                ...this.$attrs,
                columns: useColumns,
                dataSource: this.datas,
                rowKey: this.dataKey,
                enablePagination: false,
                enableIndex: true
            },
            ref: 'proDataTable',
            attrs: {
                emptyText: '暂无任何附件',
                border: true,
                ...this.$attrs
            },
            'class': {
                'files-region-list--table': true
            },
            scopedSlots: Object.assign({}, this.$scopedSlots, this.createRenderScopedSlots())
        }
        return (
            <div class="tables-region-list">
                <pro-data-table {..._datas}>
                    {this.renderSlots()}
                </pro-data-table>
            </div>
        )
    }
}