import {
  useCallback,
  useEffect,
  useMemo,
  useRef,
  useState,
  forwardRef,
  useImperativeHandle
} from 'react'
import styles from './index.module.scss'
import { useDispatch } from 'react-redux'
import history from '@/utils/history'
import { Button, DatePicker, Input, Select, Cascader } from 'antd'
import { tableListAuditBtnFu } from '@/utils/authority'
import MyTable from '@/components/MyTable'
import dayjs from 'dayjs'
const { RangePicker } = DatePicker

type Props = {
  baseFormData: any
  getListAPI: (data: any) => any
  pageKey: string
  tableInfo: any
  columnsTemp: any
  yHeight: number
  searchDom: any[]
  // 右侧按钮的宽度
  rightBtnWidth?: number | string
  // 左侧每个输入框盒子的宽度
  leftRowWidth?: string
  // 故事管理/藏品总账定制右侧内容
  storyTableListToprr?: (props: any) => React.ReactNode
  // 故事管理/藏品总账定制操作栏
  storyTableLastBtn?: any
  // 额外查询参数（不会影响顶部表单状态），在发请求时合并
  extraParams?: any
  // antd Table rowSelection 配置（例如跨页多选）
  rowSelection?: any
  staBtn?: any
  // 藏品修改特有的字段
  isEdit?: () => void
}

const TableList = forwardRef<any, Props>(function TableList(props, ref) {
  const {
    baseFormData,
    getListAPI,
    pageKey,
    tableInfo,
    columnsTemp,
    yHeight,
    searchDom,
    rightBtnWidth = 250,
    leftRowWidth = '25%',
    storyTableLastBtn,
    storyTableListToprr,
    extraParams,
    rowSelection,
    staBtn,
    isEdit
  } = props
  const dispatch = useDispatch()
  const _searchDom = useRef(searchDom)

  const [formData, setFormData] = useState({ ...baseFormData })

  const formDataRef = useRef({ ...baseFormData })

  useEffect(() => {
    formDataRef.current = formData
  }, [formData])

  // 点击搜索的 时间戳
  const [timeKey, setTimeKey] = useState(0)

  // 点击搜索
  const clickSearch = useCallback(() => {
    setFormData({ ...formData, pageNum: 1 })
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [formData])

  // 时间选择器改变
  const timeChange = useCallback(
    (dateString: any, key: any) => {
      let startTime = ''
      let endTime = ''
      if (dateString[0] && dateString[1]) {
        startTime = dateString[0] + ' 00:00:00'
        endTime = dateString[1] + ' 23:59:59'
      }

      setFormData({ ...formData, [key[0]]: startTime, [key[1]]: endTime })
    },
    [formData]
  )

  // 封装发送请求的函数（级联字段传数组中最后一个值）
  const getListFu = useCallback(() => {
    const params = {
      ...formDataRef.current,
      ...(extraParams || {})
    }
    _searchDom.current.forEach((item: any) => {
      if (item.type === 'cascader' && item.key && Array.isArray(params[item.key])) {
        params[item.key] = params[item.key][params[item.key].length - 1]
      }
    })
    dispatch(getListAPI(params))
  }, [dispatch, getListAPI, extraParams])

  useEffect(() => {
    getListFu()
  }, [getListFu, timeKey])

  // 输入框的改变
  const txtChangeFu = useCallback(
    (txt: string, key: any) => {
      setFormData({
        ...formData,
        [key]: txt
      })
    },
    [formData]
  )
  // 点击重置
  const resetSelectFu = useCallback(() => {
    setFormData({ ...baseFormData })
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [baseFormData])

  // 页码变化
  const paginationChange = useCallback(
    (pageNum: number, pageSize: number) => {
      setFormData({ ...formData, pageNum, pageSize })
      setTimeout(() => {
        setTimeKey(Date.now())
      }, 50)
    },
    [formData]
  )

  // 点击各种操作按钮
  const tableBtnFu = useCallback(
    (id: number, key: string) => {
      history.push(`/${pageKey}_edit/${key}/${id}`)
    },
    [pageKey]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => (
          <>
            <Button size='small' type='text' onClick={() => tableBtnFu(item.id, '4')}>
              查看
            </Button>
            {tableListAuditBtnFu(item) ? (
              <Button size='small' type='text' onClick={() => tableBtnFu(item.id, '3')}>
                审批
              </Button>
            ) : null}
          </>
        )
      }
    ]
  }, [tableBtnFu])

  useImperativeHandle(ref, () => ({
    getListFu,
    txtChangeFu
  }))

  return (
    <>
      <div className={styles.TableListTop}>
        <div
          className='TableListTopll'
          style={{
            width: `calc(100% - ${
              typeof rightBtnWidth === 'string' ? rightBtnWidth : `${rightBtnWidth + 20}px`
            })`
          }}
        >
          {searchDom.map((item, index) => (
            <div key={index} style={{ width: leftRowWidth }}>
              {item.type === 'time' ? (
                <RangePicker
                  value={
                    formData[item.key[0]]
                      ? [dayjs(formData[item.key[0]]), dayjs(formData[item.key[1]])]
                      : null
                  }
                  onChange={(_, dateString) => timeChange(dateString, item.key)}
                  placeholder={item.placeholder}
                />
              ) : item.type === 'input' ? (
                <Input
                  style={item.style || ''}
                  placeholder={item.placeholder}
                  maxLength={item.maxLength || 30}
                  value={formData[item.key]}
                  onChange={e => txtChangeFu(e.target.value, item.key)}
                />
              ) : item.type === 'select' ? (
                <Select
                  allowClear={true}
                  placeholder={item.placeholder}
                  style={item.style || ''}
                  value={formData[item.key] ? formData[item.key] : null}
                  onChange={e => setFormData({ ...formData, [item.key]: e })}
                  options={item.options}
                />
              ) : item.type === 'cascader' ? (
                <Cascader
                  allowClear={true}
                  placeholder={item.placeholder}
                  style={item.style || ''}
                  value={formData[item.key] ?? null}
                  fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                  onChange={e => setFormData({ ...formData, [item.key]: e })}
                  options={item.options}
                />
              ) : null}
            </div>
          ))}
        </div>
        <div
          className='TableListToprr'
          style={{ width: typeof rightBtnWidth === 'string' ? rightBtnWidth : `${rightBtnWidth}px` }}
        >
          {storyTableListToprr ? (
            storyTableListToprr({ clickSearch, resetSelectFu })
          ) : (
            <>
              <Button
                type='primary'
                onClick={() => {
                  if (isEdit) isEdit()
                  else history.push(`/${pageKey}_edit/1/null`)
                }}
              >
                发起申请
              </Button>
              <Button type='primary' onClick={clickSearch}>
                查询
              </Button>
              <Button onClick={resetSelectFu}>重置</Button>
            </>
          )}
        </div>
      </div>
      <div className={`${styles.TableListTable} table-list-table`}>
        <MyTable
          yHeight={yHeight}
          list={tableInfo.list}
          columnsTemp={columnsTemp}
          staBtn={staBtn || []}
          lastBtn={storyTableLastBtn ? storyTableLastBtn : tableLastBtn}
          pageNum={formData.pageNum}
          pageSize={formData.pageSize}
          total={tableInfo.total}
          onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
          rowSelection={rowSelection}
        />
      </div>
    </>
  )
})

export default TableList
