Newer
Older
xc-business-system / src / commonMethods / useMergeCells.ts
/**
 * 合并单元格
 * @param list 要操作的表格
 * @param props 合并的字段列表【Array】
 * @param rowIndex 表格数据行下标
 * @param colIndex 表格数据列下标
 * @returns
 */
export function useMergeCells(list: any, props: any, rowIndex: number, colIndex: number) {
  if (colIndex >= props.length || !props[colIndex]) {
    // 根据传入的字段列表,判断不需要合并的列
    return [1, 1]
  }
  else {
    // 使用try-catch,如果方法错误返回错误信息
    try {
      const _props = props.slice(0, colIndex + 1)// 截取需要用到判断的字段名
      // 判断是否从本行开始合并
      const merge = _props.some((item: any) => {
        // 如果当前行所需要判断合并的字段中有一个跟前一条数据不一样,本条数据即为合并的起点,第一条数据直接为合并起点
        return (
          rowIndex == 0 || (item && list[rowIndex][item] != list[rowIndex - 1][item])
        )
      })
      // 如果本条数据是合并起点,获取需要合并的数据条数
      if (merge) {
        const _list = list.slice(rowIndex)// 截取从本条数据开始的列表
        // 获取合并行数
        const _lineNum = _list.findIndex((item: any, ind: number) => {
          // 同merge判断,找到合并的终点
          return (
            ind
            && _props.some((item1: any) => {
              return (item1 && item[item1] != _list[0][item1])
            })
          )
        })
        // 合并行数为-1时,输出_list的长度,否则输出_lineNum
        return [_lineNum === -1 ? _list.length : _lineNum, 1]
      }
      else {
        // 否则,返回[0,0],即本条数据被合并
        return [0, 0]
      }
    }
    catch (err) {
      // 打印报错
      console.error('spanMethodFunc error:', err)
    }
  }
}