import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { FileImgListType } from '@/types'
import { API_upFile, fileTypeRes } from '@/store/action/layout'
import { MessageFu } from '@/utils/message'
import { fileDomInitialFu } from '@/utils/domShow'
import { forwardRef, useImperativeHandle } from 'react'
import { Button, Popconfirm } from 'antd'
import { EyeOutlined, UploadOutlined, CloseOutlined, DownloadOutlined } from '@ant-design/icons'
import classNames from 'classnames'
import { baseURL } from '@/utils/http'
import { authFilesLookFu } from './data'

export type GoodFileType = {
  createTime: string
  creatorId: number
  creatorName: string
  description: string
  display?: any
  effect: string | null
  fileName: string
  filePath: string
  fileSize: string
  goodName: string
  goodNum: string
  goodNumName: string
  id: number
  moduleId?: any
  moduleName: string
  parentId?: any
  thumb: string
  type: string
  updateTime: string
}

type Props = {
  max: number //最多传多少个文件
  isLook: boolean //是否是查看
  ref: any //当前自己的ref，给父组件调用
  fileCheck: boolean
  dirCode: string //文件的code码
  myUrl: string
  fromData?: any
  lookData: FileImgListType[] //编辑或者 查看 回显
  accept?: string
  // result:成果 | list:清单
  tips?: string
  // 文件大小
  size?: number
  noShowList?: boolean //不回显列表
  fileRes?: (obj: GoodFileType) => void
}

function Z3upFiles(
  {
    max,
    isLook,
    fileCheck,
    dirCode,
    myUrl,
    fromData,
    lookData,
    accept = '*',
    tips = '最多支持10个附件；单个附件不得超过500M',
    size,
    noShowList = false,
    fileRes
  }: Props,
  ref: any
) {
  const [fileList, setFileList] = useState<FileImgListType[]>([])

  useEffect(() => {
    if (lookData && lookData.length > 0) setFileList(lookData)
  }, [lookData])

  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.includes('.zip') && accept !== '*') {
          e.target.value = ''
          return MessageFu.warning(`只支持zip格式!`)
        }

        // 校验大小
        if (size && filesInfo.size > size * 1024 * 1024) {
          e.target.value = ''
          return MessageFu.warning(`最大支持${size}M!`)
        }

        // 创建FormData对象
        const fd = new FormData()
        // 把files添加进FormData对象（‘photo’为后端需要的字段）

        const typeRes = fileTypeRes(filesInfo.name)

        fd.append('file', filesInfo)
        fd.append('type', typeRes)
        fd.append('dirCode', dirCode)
        fd.append('isDb', 'true')

        // 开启压缩图片
        fd.append('isCompress', 'true')

        if (fromData) {
          for (const k in fromData) {
            if (fromData[k]) fd.append(k, fromData[k])
          }
        }

        e.target.value = ''

        try {
          const res = await API_upFile(fd, myUrl)
          if (res.code === 0) {
            MessageFu.success('上传成功!')
            setFileList([...fileList, res.data])

            if (fileRes) {
              fileRes(res.data)
            }
          }
          fileDomInitialFu()
        } catch (error) {
          fileDomInitialFu()
        }
      }
    },
    [accept, dirCode, fileList, fileRes, fromData, myUrl, size]
  )

  // 列表删除某一个文件
  const delImgListFu = useCallback(
    async (id: number) => {
      setFileList(fileList.filter(v => v.id !== id))
    },
    [fileList]
  )

  // 让父组件调用，拿到 附件信息
  const filesIdRes = useCallback(() => {
    return fileList.map(v => v.id)
  }, [fileList])

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

  return (
    <div className={styles.Z3upFiles} id='Z3upFiles'>
      <input
        id='upInput'
        type='file'
        accept={accept}
        ref={myInput}
        onChange={e => handeUpPhoto(e)}
      />
      <div className='Z3Btn'>
        {fileList.length < max && !isLook ? (
          <Button
            onClick={() => myInput.current?.click()}
            icon={<UploadOutlined rev={undefined} />}
            type={noShowList ? 'primary' : 'default'}
          >
            上传
          </Button>
        ) : null}

        {noShowList ? null : (
          <div className='Z3files'>
            {fileList.map(v => (
              <div className='Z3filesRow' key={v.id}>
                <div className='Z3files1' title={v.fileName}>
                  {v.fileName}
                </div>
                <div className='Z3files2'>
                  {authFilesLookFu(v.fileName, '') ? (
                    <>
                      <EyeOutlined
                        rev={undefined}
                        title='查看'
                        onClick={() => authFilesLookFu(v.fileName, v.filePath)}
                      />
                      &emsp;
                    </>
                  ) : null}
                  <a
                    title='下载'
                    href={baseURL + v.filePath}
                    download={v.fileName}
                    target='_blank'
                    rel='noreferrer'
                  >
                    <DownloadOutlined rev={undefined} />
                  </a>
                  &emsp;
                  <Popconfirm
                    title='删除后无法恢复，是否删除?'
                    okText='删除'
                    cancelText='取消'
                    onConfirm={() => delImgListFu(v.id)}
                    okButtonProps={{ loading: false }}
                  >
                    <CloseOutlined rev={undefined} title='删除' hidden={isLook} />
                  </Popconfirm>
                </div>
              </div>
            ))}
          </div>
        )}

        <div className='fileTit' hidden={isLook || noShowList}>
          {tips}
          <br />
          <div
            className={classNames(
              'noUpThumb',
              fileList.length <= 0 && fileCheck ? 'noUpThumbAc' : ''
            )}
          >
            请上传视频!
          </div>
        </div>
      </div>
      {isLook && fileList.length <= 0 ? <div className='lookNone'>（空）</div> : null}
    </div>
  )
}

export default forwardRef(Z3upFiles)
