import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { Button, Checkbox, Popconfirm } from 'antd'
import MyTable from '@/components/MyTable'
import { Y33tableC } from '@/utils/tableData'
import ImageLazy from '@/components/ImageLazy'
import MyPopconfirm from '@/components/MyPopconfirm'
import Y33setType, { infoType } from '../Y2look/Y33setType'
import YtableVideo from '@/components/YtableVideo'
import { selectObj } from '@/utils/select'
import { fileImgArr, fileVideoArr } from '@/store/action/layout'
import { downFileFu, resJiLianFu } from '@/utils/history'
import { API_C2dels, API_C2downS, API_goodFileList } from '@/store/action/C2files'
import { MessageFu } from '@/utils/message'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import { GoodFileType } from '@/components/Z3upFiles'

type Props = {
  isLook?: boolean
  sId: number
}

function Y33com({ isLook, sId }: Props) {
  const [fileList, setFileList] = useState<GoodFileType[]>([])

  const getListFu = useCallback(async () => {
    const res = await API_goodFileList(sId)
    if (res.code === 0) {
      setFileList(res.data || [])
      setCheckArr([])
    }
  }, [sId])

  useEffect(() => {
    getListFu()
  }, [getListFu])

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

  const [btnAc, setBtnAc] = useState('')

  // 多选
  const [checkArr, setCheckArr] = useState<number[]>([])

  const checkFu = useCallback(
    (id: number) => {
      if (checkArr.includes(id)) setCheckArr(checkArr.filter(v => v !== id))
      else setCheckArr([...checkArr, id])
    },
    [checkArr]
  )

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

    if (isLook)
      arr.push({
        title: '选择',
        width: 50,
        render: (item: any) => (
          <Checkbox checked={checkArr.includes(item.id)} onChange={() => checkFu(item.id)} />
        )
      })

    return [
      ...arr,
      {
        width: 100,
        title: '缩略图/视频',
        render: (item: GoodFileType) => {
          const fileNameArr = item.fileName.split('.')
          const fileNameLast = fileNameArr[fileNameArr.length - 1]

          return fileImgArr.includes(fileNameLast) ? (
            <div className='tableImgAuto'>
              <ImageLazy width={60} height={60} srcBig={item.filePath} src={item.thumb} />
            </div>
          ) : fileVideoArr.includes(fileNameLast) ? (
            <YtableVideo src={item.filePath} />
          ) : (
            ' - '
          )
        }
      },
      {
        title: '附件类型',
        render: (item: GoodFileType) =>
          selectObj['附件类型'].find(v => v.value === item.type)?.label
      },
      {
        title: '附件用途',
        render: (item: GoodFileType) => (item.effect ? resJiLianFu(item.effect) : '（空）')
      }
    ]
  }, [checkArr, checkFu, isLook])

  // 点击删除
  const delFu = useCallback(
    async (data: number[]) => {
      const res = await API_C2dels(data)
      if (res.code === 0) {
        MessageFu.success('删除成功')
        getListFu()
      }
    },
    [getListFu]
  )
  // 获取下载权限
  const downImg = useSelector((state: RootState) => state.A0Layout.downImg)

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: GoodFileType) => {
          const fileNameArr = item.fileName.split('.')
          const fileNameLast = fileNameArr[fileNameArr.length - 1]
          return (
            <>
              {downImg['图片'] === '原图和缩略图' && fileImgArr.includes(fileNameLast) ? (
                <Popconfirm
                  title='请选择图片规格'
                  onConfirm={() => downFileFu(item.filePath)}
                  onCancel={() => downFileFu(item.thumb)}
                  okText='原图'
                  cancelText='缩略图'
                >
                  <Button size='small' type='text'>
                    下载
                  </Button>
                </Popconfirm>
              ) : (
                <Button
                  size='small'
                  type='text'
                  onClick={() => downFileFu(item.thumb || item.filePath)}
                >
                  下载
                </Button>
              )}
              {isLook ? (
                <>
                  <Button
                    size='small'
                    type='text'
                    onClick={() =>
                      setTypeMo({
                        ids: [item.id],
                        type: item.type,
                        effect: item.effect,
                        flag: '单个'
                      })
                    }
                  >
                    设置
                  </Button>
                  <MyPopconfirm txtK='删除' onConfirm={() => delFu([item.id])} />
                </>
              ) : null}
            </>
          )
        }
      }
    ]
  }, [delFu, downImg, isLook])

  const [typeMo, setTypeMo] = useState({} as infoType)

  // 点击批量下载
  const downsFu = useCallback(
    async (type: 1 | 2) => {
      const res = await API_C2downS(checkArr, type)
      if (res.code === 0) {
        MessageFu.success('下载成功')
        downFileFu(res.data, () => {
          setCheckArr([])
        })
      }
    },
    [checkArr]
  )

  return (
    <div className='Y33com'>
      {downImg['可见'] === '可见' ? (
        <>
          <div className='Y33top'>
            <div className='Y33topll'>
              {[{ label: '全部', value: '' }, ...selectObj['附件类型']].map(v => (
                <Button
                  key={v.value}
                  onClick={() => {
                    setBtnAc(v.value)
                    setCheckArr([])
                  }}
                  type={btnAc === v.value ? 'primary' : 'default'}
                >
                  {v.label}
                </Button>
              ))}
            </div>
            {isLook ? (
              <div className='Y33toprr'>
                {downImg['图片'] === '原图和缩略图' ? (
                  <Popconfirm
                    title='请选择图片规格'
                    onConfirm={() => downsFu(1)}
                    onCancel={() => downsFu(2)}
                    okText='原图'
                    cancelText='缩略图'
                  >
                    <Button type='primary' disabled={checkArr.length === 0}>
                      批量下载
                    </Button>
                  </Popconfirm>
                ) : (
                  <Button
                    type='primary'
                    disabled={checkArr.length === 0}
                    onClick={() => downsFu(2)}
                  >
                    批量下载
                  </Button>
                )}
                &emsp;
                <Button
                  type='primary'
                  disabled={checkArr.length === 0}
                  onClick={() =>
                    setTypeMo({
                      ids: checkArr,
                      type: '',
                      effect: '',
                      flag: '多个'
                    })
                  }
                >
                  批量设置
                </Button>
              </div>
            ) : null}
          </div>

          {/* 表格 */}
          <MyTable
            classKey='Y33comTable'
            yHeight={isLook ? 640 : 666}
            list={tableObj[btnAc] || []}
            columnsTemp={Y33tableC}
            lastBtn={tableLastBtn}
            startBtn={startBtn}
            pagingInfo={false}
          />

          {typeMo.flag ? (
            <Y33setType
              succFu={getListFu}
              info={typeMo}
              closeFu={() => setTypeMo({} as infoType)}
            />
          ) : null}
        </>
      ) : (
        <div className='Y33no'>没有权限</div>
      )}
    </div>
  )
}

const MemoY33com = React.memo(Y33com)

export default MemoY33com
