import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { GoodsType } from '@/pages/Zother/SonGoodsList/data'
import { FileListType } from '@/components/Z3upFiles/data'
import { API_downloadFiles, API_getFileListByIds } from '@/store/action/Cledger/C4file'
import { Button } from 'antd'
import { selectObj } from '@/utils/dataChange'
import { MessageFu } from '@/utils/message'
import { downloadFileByUrl, fileImgArr } from '@/utils'
import MyTable from '@/components/MyTable'
import ImageLazy from '@/components/ImageLazy'
import store from '@/store'
import { EyeOutlined } from '@ant-design/icons'
import { baseURL } from '@/utils/http'
import { GI3tableC } from '@/utils/tableData'
import DownLog from '@/pages/Zother/DownLog'
import SetFileType from '@/pages/Zother/SetFileType'

type Props = {
  info: GoodsType
  fileList: FileListType[]
}

function GItab3({ info, fileList }: Props) {
  const [list, setList] = useState<FileListType[]>([])

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

  // 获取附件详情列表
  const getFileListFu = useCallback(async () => {
    const res = await API_getFileListByIds(info.fileIds.split(','))
    if (res.code === 0) {
      setList(res.data)
    }
  }, [info.fileIds])

  // 附件表格对象
  const tableObj = useMemo(() => {
    let obj: any = {
      all: list
    }
    list.forEach(v => {
      if (obj[v.type]) obj[v.type].push(v)
      else obj[v.type] = [v]
    })

    return obj
  }, [list])

  const [btnAc, setBtnAc] = useState('all')
  // 多选
  const [checkArr, setCheckArr] = useState<React.Key[]>([])

  // 多选
  const rowSelection = useMemo(
    () => ({
      selectedRowKeys: checkArr,
      onChange: (selectedRowKeys: React.Key[]) => {
        setCheckArr(selectedRowKeys)
      }
    }),
    [checkArr]
  )

  // 点击批量下载
  const downsFu = useCallback(async () => {
    if (checkArr.length === 1) {
      const obj = list.find(v => v.id === checkArr[0])!
      if (obj) {
        const res = await API_downloadFiles([obj.id])
        if (res.code === 0) {
          downloadFileByUrl(obj.filePath, obj.fileName, () => {
            setCheckArr([])
          })
        }
      } else {
        MessageFu.warning('找不到文件或已被删除')
        getFileListFu()
      }
    } else {
      const res: any = await API_downloadFiles(checkArr as number[])
      if (res && res.code === 0 && res.data) {
        const path = res.data as string
        const fullUrl = path.startsWith('http') ? path : `${baseURL}${path}`
        window.open(fullUrl)
        setCheckArr([])
      }
    }
  }, [checkArr, getFileListFu, list])

  const staBtn = useMemo(() => {
    let arr: any[] = []

    arr.push({
      title: '缩略图/查看',
      render: (item: FileListType) => {
        const lastNameArr = item.fileName.split('.')
        let lastName = lastNameArr[lastNameArr.length - 1]
        lastName = lastName.toLocaleLowerCase()

        if (fileImgArr.includes(lastName)) {
          return (
            <div className='tableImgAuto'>
              <ImageLazy
                width={60}
                height={60}
                src={item.thumb || item.filePath}
                srcBig={item.filePath || item.thumb}
              />
            </div>
          )
        } else if (item.type === 'video') {
          return (
            <div className='tablelookVideo'>
              <div
                className='tablelookBox'
                onClick={() =>
                  store.dispatch({
                    type: 'layout/lookDom',
                    payload: { src: item.filePath, type: 'video' }
                  })
                }
              >
                <EyeOutlined rev={undefined} />
                &nbsp;
                <div>预览</div>
              </div>
              <video src={baseURL + item.filePath} />
            </div>
          )
        } else {
          const lastNameArr = item.fileName.split('.')
          let laseName = lastNameArr[lastNameArr.length - 1]
          laseName = laseName.toLocaleLowerCase()
          if (['pdf', 'txt'].includes(laseName)) {
            return (
              <Button
                size='small'
                type='text'
                onClick={() => {
                  window.open(baseURL + item.filePath)
                }}
              >
                查看
              </Button>
            )
          } else return <div className='tableImgAuto'>-</div>
        }
      }
    })

    if (['all', 'img'].includes(btnAc)) {
      arr.push({
        title: '图片类型',
        render: (item: FileListType) => {
          let txt = '/'
          if (item.type === 'img') txt = item.effect || '（空）'
          return txt
        }
      })
    }

    return arr
  }, [btnAc])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: FileListType) => (
          <>
            <Button
              size='small'
              type='text'
              onClick={async () => {
                const res = await API_downloadFiles([item.id])
                if (res.code === 0) downloadFileByUrl(item.filePath, item.fileName)
              }}
            >
              下载
            </Button>
            <Button size='small' type='text' onClick={() => setFileType(item)}>
              设置
            </Button>
            <Button size='small' type='text' onClick={() => setDownLogId(item.id)}>
              下载记录
            </Button>
          </>
        )
      }
    ]
  }, [])

  // 下载记录参数
  const [downLogId, setDownLogId] = useState(0)

  // 设置附件
  const [fileType, setFileType] = useState({} as FileListType)

  return (
    <div className={styles.GItab3}>
      <div className='GI3top'>
        <div>
          {[{ label: '全部', value: 'all' }, ...selectObj['附件类型']].map(v => (
            <Button
              key={v.value}
              onClick={() => {
                setBtnAc(v.value)
                setCheckArr([])
              }}
              type={btnAc === v.value ? 'primary' : 'default'}
            >
              {v.label}
            </Button>
          ))}
        </div>
        <Button type='primary' disabled={checkArr.length === 0} onClick={downsFu}>
          批量下载
        </Button>
      </div>

      {/* 表格 */}
      <MyTable
        classKey='GItab3'
        yHeight={550}
        list={tableObj[btnAc] || []}
        columnsTemp={GI3tableC}
        lastBtn={tableLastBtn}
        staBtn={staBtn}
        pagingInfo={false}
        rowSelection={rowSelection}
      />

      {/* 下载记录 */}
      {downLogId ? <DownLog id={downLogId} closeFu={() => setDownLogId(0)} /> : null}

      {/* 设置附件类型 */}
      {fileType.id ? (
        <SetFileType
          infoTemp={fileType}
          succFu={getFileListFu}
          closeFu={() => setFileType({} as FileListType)}
        />
      ) : null}
    </div>
  )
}

const MemoGItab3 = React.memo(GItab3)

export default MemoGItab3
