import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { FileListType } from '../ZupTypes'
import { Button } from 'antd'
import { MessageFu } from '@/utils/message'
import { API_upFile } from '@/store/action/layout'
import { fileDomInitialFu } from '@/utils/domShow'
import MyTable from '../MyTable'
import MyPopconfirm from '../MyPopconfirm'
import { ZypFileTable } from '@/utils/tableData'
import { baseURL } from '@/utils/http'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import { API_C2dels } from '@/store/action/C2files'

type Props = {
  listTemp: FileListType[]
  dirCode: string //文件的code码
  myUrl: string //请求地址
  size?: number
  fromData?: any
}

function ZupFileTable({ listTemp, dirCode, myUrl, size = 500, fromData }: Props) {
  const [list, setList] = useState<FileListType[]>([])

  useEffect(() => {
    setList(listTemp)
  }, [listTemp])

  // 点击上传附件按钮
  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.size > size * 1024 * 1024) {
          e.target.value = ''
          return MessageFu.warning(`最大支持${size}M!`)
        }
        // 创建FormData对象
        const fd = new FormData()
        // 把files添加进FormData对象（‘photo’为后端需要的字段）
        fd.append('dirCode', dirCode)
        fd.append('isDb', 'true')
        fd.append('type', 'doc')
        fd.append('binding', '1')
        fd.append('file', filesInfo)

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

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

        e.target.value = ''

        const res = await API_upFile(fd, myUrl)

        try {
          if (res.code === 0) {
            MessageFu.success('上传成功!')
            setList([...list, res.data])
          }
          fileDomInitialFu()
        } catch (error) {
          fileDomInitialFu()
        }
      }
    },
    [dirCode, fromData, list, myUrl, size]
  )

  const userInfo = useSelector((state: RootState) => state.A0Layout.userInfo)

  // 点击删除
  const delFu = useCallback(
    async (data: number[]) => {
      const res = await API_C2dels(data)
      if (res.code === 0) {
        MessageFu.success('删除成功')
        setList(list.filter(v => v.id !== data[0]))
      }
    },
    [list]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: FileListType) => (
          <>
            <Button size='small' type='text'>
              <a href={baseURL + item.filePath} download target='_blank' rel='noreferrer'>
                下载
              </a>
            </Button>
            {userInfo.id === item.creatorId ? (
              <MyPopconfirm txtK='删除' onConfirm={() => delFu([item.id])} />
            ) : null}
          </>
        )
      }
    ]
  }, [delFu, userInfo.id])

  return (
    <div className={styles.ZupFileTable}>
      <input id='upInput' type='file' accept='*' ref={myInput} onChange={e => handeUpPhoto(e)} />
      <div className='ZZtop'>
        <h3>归档附件</h3>
        <Button type='primary' onClick={() => myInput.current?.click()}>
          上传归档
        </Button>
      </div>

      {/* 表格 */}
      <MyTable list={list} columnsTemp={ZypFileTable} lastBtn={tableLastBtn} pagingInfo={false} />
    </div>
  )
}

const MemoZupFileTable = React.memo(ZupFileTable)

export default MemoZupFileTable
