import React, { useCallback, useEffect, useMemo, useState } from 'react'
import { Button, Checkbox } 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 { GoodFileType } from '@/pages/B_enterTibet/B3goodsTable/B3GaddNew/type'
import { selectObj } from '@/utils/select'
import { fileImgArr, fileVideoArr } from '@/store/action/layout'
import { resJiLianFu } from '@/utils/history'
import { baseURL } from '@/utils/http'
import { API_C2dels, API_C2downS, API_goodFileList } from '@/store/action/C2files'
import { MessageFu } from '@/utils/message'

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 tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: GoodFileType) => {
          return (
            <>
              <Button size='small' type='text'>
                <a href={baseURL + item.filePath} download target='_blank' rel='noreferrer'>
                  下载
                </a>
              </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, isLook])

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

  // 点击批量下载
  const downsFu = useCallback(async () => {
    const res = await API_C2downS(checkArr)
    if (res.code === 0) {
      MessageFu.success('下载成功')
      // 动态创建 a 标签
      const link = document.createElement('a')
      link.href = baseURL + res.data
      link.style.display = 'none'

      // 插入 DOM 并触发点击
      document.body.appendChild(link)
      link.click()

      // 清理
      document.body.removeChild(link)
      setCheckArr([])
    }
  }, [checkArr])

  return (
    <div className='Y33com'>
      <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'>
            <Button type='primary' disabled={checkArr.length === 0} onClick={downsFu}>
              批量下载
            </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>
  )
}

const MemoY33com = React.memo(Y33com)

export default MemoY33com
