import React, { useCallback, useRef, useState } from 'react'
import styles from './index.module.scss'
import { forwardRef, useImperativeHandle } from 'react'
import { FileListType } from '../ZupTypes'
import { MessageFu } from '@/utils/message'
import { API_upFile } from '@/store/action/layout'
import { fileDomInitialFu } from '@/utils/domShow'
import { PlusOutlined, EyeOutlined, CloseOutlined, DownloadOutlined } from '@ant-design/icons'
import classNames from 'classnames'
import { baseURL } from '@/utils/http'
import store from '@/store'
import MyPopconfirm from '../MyPopconfirm'

type Props = {
  size: number //视频大小
  fileNum: number //数量限制
  dirCode: string //文件的code码
  myUrl: string //请求地址
  fileCheck?: boolean //是否检验
  typeArr?: string[] //上传格式 ['mp4','mov','avi','wmv']
  checkTxt?: string
  upTxt?: string
  isLook?: boolean //是不是查看
  fromData?: any
  ref: any //当前自己的ref，给父组件调用
}

function ZupVideos(
  {
    size,
    fileNum,
    dirCode,
    myUrl,
    fileCheck = false,
    typeArr = ['mp4', 'mov', 'avi', 'wmv'],
    checkTxt = '请上传视频!',
    upTxt = '',
    isLook = false,
    fromData
  }: Props,
  ref: any
) {
  const [fileList, setFileList] = useState<FileListType[]>([])

  // 上传
  const handeUpPhoto = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.target.files) {
        // 拿到files信息
        const filesInfo = e.target.files[0]
        // console.log('-----', filesInfo.name)

        const fileNameArr = filesInfo.name.split('.')
        const fileNameLast = fileNameArr[fileNameArr.length - 1]

        // 校验格式
        if (!typeArr.includes(fileNameLast.toLowerCase())) {
          e.target.value = ''
          return MessageFu.warning(`只支持${typeArr.join('/')}格式`)
        }

        // 校验大小
        if (filesInfo.size > size * 1024 * 1024) {
          e.target.value = ''
          return MessageFu.warning(`最大支持${size}M!`)
        }
        // 创建FormData对象
        const fd = new FormData()

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

        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])
            // console.log(res);
          }
          fileDomInitialFu()
        } catch (error) {
          fileDomInitialFu()
        }
      }
    },
    [dirCode, fileList, fromData, myUrl, size, typeArr]
  )

  // 让父组件调用的 回显 附件 地址
  const setFileComFileFu = useCallback((valList: FileListType[]) => {
    setFileList(valList)
  }, [])

  // 让父组件调用的返回 附件 名字和路径
  const fileComFileResFu = useCallback(() => {
    return fileList
  }, [fileList])

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

  const myInput = useRef<HTMLInputElement>(null)

  // 点击预览
  const lookFileFu = useCallback((file: string) => {
    store.dispatch({
      type: 'layout/lookDom',
      payload: { src: file, type: 'video' }
    })
  }, [])

  return (
    <div className={styles.ZupVideos}>
      <input
        id='upInput'
        type='file'
        accept={typeArr.map(v => `.${v}`).join(',')}
        ref={myInput}
        onChange={e => handeUpPhoto(e)}
      />

      <div hidden={!(isLook && fileList.length <= 0)}>（空）</div>

      <div className='zVmain'>
        <div
          hidden={fileList.length >= fileNum || isLook}
          className='file_upIcon'
          onClick={() => myInput.current?.click()}
        >
          <PlusOutlined />
        </div>

        {fileList.map(v => (
          <div className='zVRow' key={v.id}>
            <div className='zVRow1'>
              <div className='zVRow1V' title={v.fileName}>
                <video src={baseURL + v.filePath}></video>
              </div>
              <div className='zVRow1I'>
                {/* 视频预览 */}
                <EyeOutlined onClick={() => lookFileFu(v.filePath)} />
                {/* 视频下载 */}
                <a href={baseURL + v.filePath} download target='_blank' rel='noreferrer'>
                  <DownloadOutlined />
                </a>
                {/* 视频删除 */}

                {isLook ? null : (
                  <MyPopconfirm
                    txtK='删除'
                    onConfirm={() => setFileList(fileList.filter(c => c.id !== v.id))}
                    Dom={<CloseOutlined />}
                  />
                )}
              </div>
            </div>
            <div className='zVRow2' title={v.fileName}>
              {v.fileName}
            </div>
          </div>
        ))}
      </div>

      <div className='fileBoxRow_r_tit' hidden={isLook}>
        格式要求：支持{typeArr.join('/')}格式，最大支持{size}M{upTxt}
        <br />
        <div
          className={classNames(
            'noUpThumb',
            fileList.length <= 0 && fileCheck ? 'noUpThumbAc' : ''
          )}
        >
          {checkTxt}
        </div>
      </div>
    </div>
  )
}

export default forwardRef(ZupVideos)
