<template>
    <table
        border="0"
        cellpadding="0"
        cellspacing="0"
        :style="{
            width: width,
            tableLayout: 'fixed',
            borderCollapse: 'separate',
        }">
        <colgroup>
            <col v-for="(size, idx) in firstLineList" :key="idx" :width="size" />
        </colgroup>
        <thead>
            <template v-if="rows.length">
                <tr v-for="(items, rowIndex) in rows" :key="rowIndex">
                    <!-- checkbox -->
                    <th :class="[
                        'mc-table__th',
                        'mc-table-column__checkbox',
                        {
                            'mc-table--fixed-left-last': fixedLeftCount === 0,
                            'mc-table--cell-shadow-left': fixedLeftCount === 0 && showLeftShadow,
                        }
                    ]"
                    v-if="rowIndex === 0 && checkbox"
                    :rowspan="rows.length"
                    :style="{
                        width: checkboxWidth + 'px',
                    }">
                        <McCheckbox
                            v-model="selectAll"
                            :include="subCheckboxSomeSelected"
                            name="selectAll"
                            @change="handleSelectAllChange"
                            :style="checkboxStyle" />
                    </th>

                    <!-- 新版mopai规范列表表头全部居左 不可设置 -->
                    <th
                        v-for="(col, colIndex) in items"
                        :key="colIndex"
                        :class="[
                            'mc-table__th',
                            rowIndex > 0? getGroupClassName(col.parentIndex) : '',
                            rowIndex === 0?
                            {
                                'mc-table__th--fixed': col.fixedLeft || col.fixedRight,
                                'mc-table--fixed-left-last': fixedLeftCount === colIndex + 1,
                                'mc-table--fixed-right-last': fixedRightCount === items.length - colIndex,
                                'mc-table--cell-shadow-left': fixedLeftCount === colIndex + 1 && showLeftShadow,
                                'mc-table--cell-shadow-right': fixedRightCount === items.length - colIndex && showRightShadow,
                            } : {}
                        ]"
                        :colspan="col.colspan"
                        :rowspan="col.rowspan"
                        :style="{
                            left: col.fixedLeft && getColFixedLeftPosition(colIndex, colWidthList),
                            right: col.fixedRight && getColFixedRightPosition(colIndex, colWidthList),
                        }">
                        <component :is="col.children.header" v-if="col.children?.header"></component>
                        <template v-else>
                            <div v-tooltip="col.props?.headerTip || ''" :style="[
                                {
                                    display: 'flex',
                                    alignItems: 'center',
                                    textAlign: col.props.align,
                                    justifyContent: translateTextAlign(col.props.align)
                                }
                            ]">
                                {{col.props?.label || ''}}
                                <img v-if="col.props?.headerTip" :src="EXPLAIN_ICON" style="margin-left:8px;vertical-align:middle;" />
                            </div>
                        </template>
                    </th>
                </tr>
            </template>
        </thead>
    </table>
</template>

<script>
import { ref, inject, computed } from 'vue'
import McCheckbox from '../checkbox'
import { getGroupClassName, isFixedColumn, getColFixedLeftPosition, getColFixedRightPosition, formatSizeValueToNumber, formatterProps } from './util'
import EXPLAIN_ICON from '../../img/icon_explain.svg'

/**
 * 列表表头 列元素控件
 */
export default {
    props: {
        column: {
            type: Array,
            default: () => []
        },
        checkbox: Boolean,
        width: String,
        checkboxWidth: Number,
        subCheckboxSomeSelected: Boolean,
    },
    emits: ['select', 'render-done'],
    components: {
        McCheckbox
    },
    setup(props, { emit }){

        const { handleSelectAll, checkboxStyle, showLeftShadow, showRightShadow, totalLevel, selectAll } = inject('McTableRootOpts')

        const fixedLeftCount = ref(0)
        const fixedRightCount = ref(0)

        const rows = computed(() => props.column?.length? analysisHeaderColumns(props.column) : [])

        const colWidthList = computed(() => {
            return [
                props.checkbox ** props.checkboxWidth? formatSizeValueToNumber(props.checkboxWidth) : 0,
                ...(rows.value?.[0] || []).map((col) => col.cellWidth || 0)
            ]
        })

        const firstLineList = ref([])

        if(props.checkbox) {
            firstLineList.value.push(props.checkboxWidth || 0)
        }

        const analysisHeaderColumns = (columns) => {
            const analysisColumnsResult = []
            // 清空‘firstLineList’避免缓存
            firstLineList.value = []
            mapSubRow(columns)
            return analysisColumnsResult

            function mapSubRow(
                list,
                index = 0,
                colCount,
                parentIndex
            ) {
                const rowList = []
                let callbackColLength = 0

                list.forEach((col, idx) => {
                    if(typeof col.type === 'object' && (col.type).name === 'McTableV2Column'){
                        callbackColLength = colCount || 0

                        // 初始化数组
                        analysisColumnsResult[index] = analysisColumnsResult[index] || []

                        // 初始化属性
                        col.colspan = 1
                        col.rowspan = totalLevel.value - index
                        col.parentIndex = index > 0? parentIndex : null
                        col.props = formatterProps(col.props)

                        // 解析子表头
                        if(Array.isArray(col.childrenVNode) && col.childrenVNode.length){
                            const currentRowLength = col.childrenVNode.length
                            const {sub, subColLength} = mapSubRow(col.childrenVNode, index + 1, callbackColLength + 1, parentIndex || idx)
                            const subRow = sub.filter(n => n)
                            if(subRow?.length){
                                // 如果有子表头，rowspan设置为1
                                col.rowspan = 1
                                col.colspan = currentRowLength
                                col.cellWidth = subRow.reduce((t, c) => t + c.cellWidth, 0)

                                // 当前row数量-当前列+子表头列数  返回给上一级表头
                                callbackColLength = subColLength + (currentRowLength - 1)

                            }
                        }

                        if(isFixedColumn(col.props, 'left')) {
                            col.fixedLeft = true
                            fixedLeftCount.value++
                        }
                        if(isFixedColumn(col.props, 'right')) {
                            col.fixedRight = true
                            fixedRightCount.value++
                        }

                        analysisColumnsResult[index].push(col)
                        rowList.push(col)

                        if(((col.level || 0) + col.rowspan) === totalLevel.value + 1){
                            firstLineList.value.push(col.cellWidth)
                        }
                    }
                })
                return { sub: rowList, subColLength: callbackColLength }
            }
        }

        const handleSelectAllChange = () => handleSelectAll(selectAll.value)

        const translateTextAlign = (align = 'left') => ({
            left: 'flex-start',
            center: 'center',
            right: 'flex-end',
        }[align])

        return {
            rows,
            selectAll,
            checkboxStyle,
            EXPLAIN_ICON,
            getGroupClassName,
            handleSelectAllChange,
            translateTextAlign,
            totalLevel,
            firstLineList,
            fixedLeftCount,
            fixedRightCount,
            colWidthList,
            getColFixedLeftPosition,
            getColFixedRightPosition,
            showLeftShadow,
            showRightShadow,
        }
    }
}
</script>
