<template>
    <div>
        <div class="x-editor" ref="editor"></div>
        <SetRowHeightDialog></SetRowHeightDialog>
        <SetColumnWidthDialog></SetColumnWidthDialog>
    </div>
</template>
<script>
import { afterRenderer } from './CellRenderer'
import { afterRowResize } from './AfterRowResize'
import { afterColumnResize } from './AfterColumnResize'
import { contextMenuConfigure } from '../table/ContextMenu'
import { getParameters, pointToPixel } from '../utils/Utils'
import { renderRowHeader } from '../table/HeaderUtils.js'
import DesignApi from '@/api/designer'

import Handsontable from 'handsontable'
import Context from './Context'
import Hub from '../../Hub'
import { mapState, mapActions } from 'vuex'

import SetRowHeightDialog from '../table/operation/SetRowHeight'
import SetColumnWidthDialog from '../table/operation/SetColumnWidth'

export default {
    name: 'Editor',
    data() {
        return {
            hot: null,
            cellsMap: new Map(),
            reportDef: null,
            displayFileName: '',
        }
    },
    computed: {
        ...mapState([
            'context',
            'reportGuid',
            'currRowHeight',
            'showSetRowHeightDialog',
        ]),
    },
    components: {
        SetRowHeightDialog,
        SetColumnWidthDialog,
    },
    methods: {
        ...mapActions([
            'setContext',
            'setCurrRowHeight',
            'setShowSetRowHeightDialog',
            'setCurrCellDef',
            'setCurrRowIndex',
            'setCurrColIndex',
            'setReportGuid',
        ]),
        buildContextMenu() {
            this.hot.updateSettings({
                contextMenu: contextMenuConfigure,
            })
        },
        buildReportData(data) {
            this.cellsMap.clear()

            const rows = data.rows
            const rowHeights = []

            for (let row of rows) {
                const height = row.height
                rowHeights.push(pointToPixel(height))
            }

            const columns = data.columns
            const colWidths = []
            for (let col of columns) {
                const width = col.width
                colWidths.push(pointToPixel(width))
            }

            const cellsMap = data.cellsMap
            const dataArray = [],
                mergeCells = []
            for (let row of rows) {
                const rowData = []
                for (let col of columns) {
                    let key = row.rowNumber + ',' + col.columnNumber
                    let cell = cellsMap[key]
                    if (cell) {
                        this.cellsMap.set(key, cell)
                        rowData.push(cell.value.value || '')
                        let rowspan = cell.rowSpan,
                            colspan = cell.colSpan
                        if (rowspan > 0 || colspan > 0) {
                            if (rowspan === 0) rowspan = 1
                            if (colspan === 0) colspan = 1
                            mergeCells.push({
                                rowspan,
                                colspan,
                                row: row.rowNumber - 1,
                                col: col.columnNumber - 1,
                            })
                        }
                    } else {
                        rowData.push('')
                    }
                }
                dataArray.push(rowData)
            }
            this.hot.loadData(dataArray)
            this.hot.updateSettings({
                colWidths,
                rowHeights,
                mergeCells,
                readOnly: true,
            })
        },
        hookTable() {
            this.hot.addHook('afterRenderer', afterRenderer)
            this.hot.addHook('afterRowResize', afterRowResize)
            this.hot.addHook('afterColumnResize', afterColumnResize)
        },

        buildContext() {
            this.setContext(new Context(this))
        },

        loadReportFile(callback) {
            DesignApi.loadReport(this.reportGuid).then((reportDef) => {
                this.reportDef = reportDef
                this.buildReportData(reportDef)
                if (callback) {
                    callback.call(this, reportDef)
                }
                this.hot.render()
                renderRowHeader(this.hot, this.context)
                //处理报表背景
                // if (reportDef.paper.bgImage) {
                //     $('.ht_master').css('background', `url(${reportDef.paper.bgImage}) 50px 26px no-repeat`);
                // } else {
                //     $('.ht_master').css('background', 'transparent');
                // }
            })
        },
        parseParams() {
            const p = getParameters() || {}

            this.setReportGuid(p._g)
        },
        bindCellSelectEvent() {
            var that = this
            Handsontable.hooks.add(
                'afterSelectionEnd',
                function (rowIndex, colIndex, row2Index, col2Index) {
                    let cellDef = this.context.getCell(rowIndex, colIndex)
                    if (!cellDef) {
                        return
                    }

                    that.setCurrCellDef(cellDef)
                    that.setCurrRowIndex(rowIndex)
                    that.setCurrColIndex(colIndex)

                    Hub.$emit('after-selection-end', [
                        cellDef,
                        rowIndex,
                        colIndex,
                        row2Index,
                        col2Index,
                    ])
                },
                this.hot
            )

            Handsontable.hooks.add('afterOnCellMouseDown', function () {
                Hub.$emit('cell-click')
            })
        },
    },
    mounted() {
        this.hot = new Handsontable(this.$refs.editor, {
            startCols: 1,
            startRows: 1,
            fillHandle: {
                autoInsertRow: false,
            },
            colHeaders: true,
            rowHeaders: true,
            autoColumnSize: false,
            autoRowSize: false,
            manualColumnResize: true,
            manualRowResize: true,
            maxColsNumber: 700,
            outsideClickDeselects: false,
            licenseKey: 'non-commercial-and-evaluation',
        })

        this.buildContextMenu()
        this.parseParams()
        this.loadReportFile(function () {
            this.buildContext()
            Hub.$emit('context_inited', this.context)
        })
        this.hookTable()
        this.bindCellSelectEvent()
    },
}
</script>
<style>
@import '../../../../../node_modules/handsontable/dist/handsontable.full.css';

.x-editor {
}
</style>