import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useInfo } from '../InfoContext'
import { Button } from 'antd'
import MyTable from '@/components/MyTable'
import { baseURL } from '@/utils/http'
import { FileListType } from '@/components/Z3upFiles/data'
import MyPopconfirm from '@/components/MyPopconfirm'
import { getTokenInfo } from '@/utils/storage'
import { API_delFiles } from '@/store/action/Cledger/C4file'
import { MessageFu } from '@/utils/message'
import { API_upFile } from '@/store/action/layout'
import { fileDomInitialFu } from '@/utils/domShow'

const userInfo = getTokenInfo().user || {}

type Props = {
  fromData?: any
}

// 附件归档
function FileArchive({ fromData }: Props) {
  const { info } = useInfo()

  const [list, setList] = useState<FileListType[]>([])

  useEffect(() => {
    setList(info.filing || [])
  }, [info.filing])

  // 点击上传附件按钮
  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', `FileArchive_${info.type}`)
        fd.append('moduleId', info.id + '')
        fd.append('moduleName', info.type)
        fd.append('type', 'doc')
        fd.append('isDb', 'true')

        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, 'cms/workVoucher/uploadFiling')

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

  // 点击删除
  const delFu = useCallback(
    async (data: number[]) => {
      const res = await API_delFiles(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 === info.creatorId ? (
              <MyPopconfirm txtK='删除' onConfirm={() => delFu([item.id])} />
            ) : null}
          </>
        )
      }
    ]
  }, [delFu, info.creatorId])

  return info.status === 4 ? (
    <div className={styles.FileArchive}>
      <input id='upInput' type='file' accept='*' ref={myInput} onChange={e => handeUpPhoto(e)} />
      <div className='FAtop'>
        <div>归档附件</div>
        {userInfo.id === info.creatorId ? (
          <Button
            type='primary'
            onClick={() => {
              // MessageFu.warning('开发中')
              myInput.current?.click()
            }}
          >
            上传归档
          </Button>
        ) : (
          <div></div>
        )}
      </div>

      {/* 表格 */}
      <MyTable
        list={list}
        columnsTemp={[
          ['txt', '附件名称', 'fileName'],
          ['txt', '归档人', 'creatorName'],
          ['txt', '归档日期', 'createTime']
        ]}
        lastBtn={tableLastBtn}
        pagingInfo={false}
      />
    </div>
  ) : null
}

const MemoFileArchive = React.memo(FileArchive)

export default MemoFileArchive
