import { API_upFile } from '@/store/action/layout'
import { A2AListCamerasType } from '@/types'
import { fileDomInitialFu } from '@/utils/domShow'
import { MessageFu } from '@/utils/message'
import { notification } from 'antd'
import React, { useCallback, useRef } from 'react'
import { forwardRef, useImperativeHandle } from 'react'

type Props = {
  url: string
  xlsxResInfoFu: (arr: A2AListCamerasType[]) => void
  ref: any //当前自己的ref，给父组件调用
  dirCode: string
  existSn: string[] //cameraSn集合，用来过滤表格
}

function UpXlsx({ url, xlsxResInfoFu, dirCode, existSn }: Props, ref: any) {
  const [api, contextHolder] = notification.useNotification()

  // 点击上传附件按钮
  const myInput = useRef<HTMLInputElement>(null)

  // 上传附件的处理函数
  const handeUpPhoto = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.target.files) {
        // 拿到files信息
        const filesInfo = e.target.files[0]

        // 校验格式
        if (!filesInfo.name.endsWith('.xlsx')) return MessageFu.warning('只支持.xlsx格式!')

        // 校验大小
        if (filesInfo.size > 5 * 1024 * 1024) {
          e.target.value = ''
          return MessageFu.warning('最大支持5M!')
        }
        // 创建FormData对象
        const fd = new FormData()
        // 把files添加进FormData对象（‘photo’为后端需要的字段）
        fd.append('type', 'doc')
        fd.append('dirCode', dirCode)
        fd.append('file', filesInfo)
        fd.append('isDb', 'false')

        e.target.value = ''

        const res = await API_upFile(fd, url)

        try {
          if (res.code === 0) {
            // MessageFu.success('上传成功!')
            const { msg, error } = res.data

            const errorTit = error && error.length ? JSON.stringify(error) : ''

            api.info({
              message: msg,
              description: errorTit,
              duration: 0,
              placement: 'topLeft'
            })

            const arr = res.data.camera || []
            const temp: string[] = []
            const arrRes: A2AListCamerasType[] = []

            arr.forEach((v: any, i: number) => {
              if (v.id) v.idxx = v.id
              else v.idxx = Date.now() - i * 200
              if (existSn.includes(v.cameraSn)) {
                temp.push(v.cameraSn)
              } else {
                arrRes.push(v)
              }
            })

            xlsxResInfoFu(arrRes)

            if (temp.length) {
              api.warning({
                message: 'SN码' + JSON.stringify(temp) + '重复，已过滤',
                duration: 0,
                placement: 'bottomLeft'
              })
            }
          }
          fileDomInitialFu()
        } catch (error) {
          fileDomInitialFu()
        }
      }
    },
    [api, dirCode, existSn, url, xlsxResInfoFu]
  )

  const myInputClickFu = useCallback(() => {
    myInput.current?.click()
  }, [])

  // 可以让父组件调用子组件的方法
  useImperativeHandle(ref, () => ({
    myInputClickFu
  }))

  return (
    <>
      {contextHolder}
      <input
        id='upInput'
        type='file'
        accept='.xlsx'
        ref={myInput}
        onChange={e => handeUpPhoto(e)}
      />
    </>
  )
}

export default forwardRef(UpXlsx)
