/**
 * el-table 操作区域，宽度自适应
 * 使用：
 *      1.el-table-column 上添加 :width="fitWidth"；
 *      2.原template中子集的el-button，使用 <div class="operation-box"> 包裹
 *      3.el-button 添加 class="operate-btn-item"
 *      4.import useFitColumn from '@/hooks/useFitColumn'
 *      5.const { fitWidth } = useFitColumn()
 */

import { onUpdated, nextTick, ref } from 'vue'
import _ from 'lodash'

const useFitColumn = () => {
    const fitWidth = ref(0)
    onUpdated(() => {
        nextTick(() => {
            const operationBoxPadding = 0
            const outerCellPadding = 24
            const columnBox = document.querySelectorAll('.operation-box')
            
            if (columnBox.length) {
                const columnBoxNumList = []
                columnBox.forEach((item, index) => {
                    columnBoxNumList.push({
                        index,
                        num: [...item.querySelectorAll('.operate-btn-item')].length
                    })
                })

                const fitColumnMax = columnBox[_.maxBy(columnBoxNumList, 'num').index]
                const btns = [...fitColumnMax.querySelectorAll('.operate-btn-item')]

                let widthCalc = 0
                if (btns.length) {
                    btns.map((el) => {
                        widthCalc += el.offsetWidth || 0
                    })
                    let marginWidth = (btns.length - 1) * 12
                    widthCalc += marginWidth
                    widthCalc += outerCellPadding
                    widthCalc += operationBoxPadding

                    fitWidth.value = widthCalc
                }
            }
        })
    })
    return { fitWidth }
}

export default useFitColumn;