import React, { useCallback, useEffect, useMemo } from 'react'
import styles from './index.module.scss'
import { Table } from 'antd'
import ImageLazy from '../ImageLazy'
import dayjs from 'dayjs'
import { myTableTransferSize, resJiLianFu } from '@/utils/dataChange'

type Props = {
  yHeight?: number //设置表格的高度
  list: any //表格数据
  columnsTemp: any[][] //表格展示
  total?: number //总数
  pageNum?: number
  pageSize?: number
  pagingInfo?: any | boolean
  onChange?: (pageNum: number, pageSize: number) => void
  staBtn?: any
  lastBtn?: any
  classKey?: string //一个组件多次使用的时候要传递，分别设置style
  // 表格简单的合并
  merge?: { type: string; num: number; loc: 'rowSpan' | 'colSpan' }
  // 定制化表头
  myTitle?: { name: string; Com: React.ReactNode }
  // 为空的定制字段
  isNull?: string
  // 设置宽度
  widthSet?: any
  rowKey?: string
  // antd Table rowSelection 配置，支持跨页多选等
  rowSelection?: any
}

// 表格内容定制化
const tableComObj = (key: string, val: string[]) => {
  const obj = {
    A: (
      <a href={val[1]} target='_blank' title={val[1]} rel='noreferrer'>
        {val[0]}
      </a>
    )
  }
  return Reflect.get(obj, key)
}

function MyTable({
  yHeight,
  list,
  columnsTemp,
  total,
  pageNum = 1,
  pageSize = 10,
  pagingInfo = {
    showQuickJumper: true,
    position: ['bottomCenter'],
    showSizeChanger: true
  },
  onChange,
  lastBtn = [],
  staBtn = [],
  classKey = '',
  merge,
  myTitle,
  isNull = '（空）',
  widthSet,
  rowKey,
  rowSelection
}: Props) {
  useEffect(() => {
    const dom = document.querySelector(`.MyTable${classKey} .ant-table-body`) as HTMLDivElement

    if (dom && yHeight) dom.style.height = yHeight + 'px'
  }, [classKey, yHeight])

  // 页码变化
  const paginationChange = useCallback(
    () => (pageNum: number, pageSize: number) => {
      if (onChange) {
        onChange(pageNum, pageSize)
      }
    },
    [onChange]
  )

  const dataChangeFu = useCallback(
    (v: any) => {
      /**
       * index:序号
       * txt:正常数据
       * img:图片
       * txtChange:判断显示不同字段
       * text:文字比较多的情况
       */

      const obj = {
        index: (_: any, __: any, index: number) => index + 1 + (pageNum - 1) * pageSize,
        txt: (item: any) => item[v[2]] || isNull,
        adiutTxt: (item: any) => {
          let txt1 = item.status === 1 ? '同意' : item.status === 2 ? '不同意' : '待处理'
          if (item.isUse === 0) txt1 = '（空）'
          const txt2 = item.isAuto === 1 ? '（自动）' : ''
          return txt1 + txt2
        },
        // 日期去掉00：00：00
        dateRes: (item: any) => {
          let res = item[v[2]] ? dayjs(item[v[2]]).format('YYYY-MM-DD') : isNull
          return res
        },
        // 多个字段拼接
        ping: (item: any) => (item[v[2]] || '') + (resJiLianFu(item[v[3]]) || '') || isNull,
        // 这个模块特有的级联控制
        txtC: (item: any) => resJiLianFu(item[v[2]]),
        txtCTag: (item: any) => resJiLianFu(item[v[2]], 'tag'),

        // 尺寸
        size: myTableTransferSize,
        img: (item: any) => (
          <div className='tableImgAuto'>
            <ImageLazy
              width={60}
              height={60}
              src={item[v[2]] || item.thumb || item.thumbPc}
              srcBig={item.thumbPc || item.thumb}
            />
          </div>
        ),

        select: (item: any) => {
          let txt = isNull
          const data = v[3]
          const id = item[v[2]]
          const obj = data.find((v: any) => v.value === id)
          if (obj) txt = obj.label
          return txt
        },
        txtChange: (item: any) => Reflect.get(v[3], item[v[2]]) || v[4] || isNull,
        text: (item: any) => {
          let tempCom: any = item[v[2]] || isNull

          if (tempCom.length >= v[3]) {
            tempCom = tempCom.substring(0, v[3]) + '...'
          }

          if (v[4]) {
            tempCom = tableComObj(v[4], [tempCom, item[v[2]]])
          } else if (item[v[2]] && item[v[2]].length >= v[3]) {
            tempCom = (
              <span style={{ cursor: 'pointer' }} title={item[v[2]]}>
                {tempCom}
              </span>
            )
          }

          return tempCom
        },

        custom: (item: any) => v[2]?.(item) || isNull
      }

      return Reflect.get(obj, v[0])
    },
    [isNull, pageNum, pageSize]
  )

  const columns = useMemo(() => {
    const arr: any = columnsTemp.map((v: any) => ({
      title: myTitle && v.includes(myTitle.name) ? myTitle.Com : v[1],
      render: dataChangeFu(v),
      width: widthSet && Reflect.get(widthSet, v[2]) ? Reflect.get(widthSet, v[2]) : 'auto',
      onCell:
        merge && v.includes(merge.type)
          ? // {rowSpan:3}
            (item: any, index: number) => ({
              rowSpan: index === 0 ? merge.num : 0
            })
          : ''
    }))

    return arr
  }, [columnsTemp, dataChangeFu, merge, myTitle, widthSet])

  return (
    <Table
      className={`${styles.MyTable} MyTable${classKey}`}
      scroll={{ y: yHeight ? yHeight : '' }}
      dataSource={list}
      columns={[...staBtn, ...columns, ...lastBtn]}
      rowKey={rowKey ? rowKey : 'id'}
      rowSelection={rowSelection}
      pagination={
        pagingInfo
          ? {
              ...pagingInfo,
              current: pageNum,
              pageSize: pageSize,
              total: total,
              onChange: paginationChange()
            }
          : false
      }
    />
  )
}

const MemoMyTable = React.memo(MyTable)

export default MemoMyTable
