import { ref, shallowRef } from 'vue'
import type { TableColumnCtx } from 'element-plus/es/components/table/src/table-column/defaults'
import { ComposeTableOptions } from './types'

/**
 * 组合表格函数
 * @param rowKey 表格主键key
 */
export function useComposeTable<T>({ rowKey, sumText, summaryFields }: ComposeTableOptions<T>) {
    // 表格选中的行数据
    const selectedRow = ref<T>()

    // 表格展开行，对应 row-key 中的值
    const expandKeys = shallowRef<T[keyof T][]>([])

    // 右键菜单
    const contextmenu = ref({
        show: false,
        clientX: 0,
        clientY: 0,
    })

    // 表格行点击事件
    const rowClick = (row: T) => {
        const keyValue = row[rowKey]
        if (expandKeys.value.includes(keyValue)) {
            expandKeys.value = []
        } else {
            expandKeys.value = [keyValue]
        }
        selectedRow.value = row
    }

    // 表格右键事件
    const rowContextmenu = (row: T, column: TableColumnCtx<T>, event: MouseEvent) => {
        // 阻止浏览器右键
        event.preventDefault()

        // 表格选中的行数据
        selectedRow.value = row

        // 显示表格右键菜单
        contextmenu.value = {
            show: true,
            clientX: event.clientX,
            clientY: event.clientY,
        }
    }

    // 自定义合计行数据
    const getSummaries = ({ columns, data }: { columns: TableColumnCtx<T>[]; data: []; }) => {
        const sums: string[] = []
        columns.forEach((column, index) => {
            if (index === 0) {
                sums[index] = sumText || '合计'
                return
            }

            const fields = summaryFields?.map((field) => typeof field === 'string' ? { fieldName: field } : field)
            const field = fields?.find((field) => field.fieldName === column.property)

            if (field) {
                const total = data.reduce((prev, curr) => prev + curr[column.property], 0)
                sums[index] = total.toFixed(field.decimals ?? 2)
            } else {
                sums[index] = '--'
            }
        })

        return sums
    }

    return {
        rowKey,
        expandKeys,
        selectedRow,
        contextmenu,
        rowClick,
        rowContextmenu,
        getSummaries
    }
}