import React, { useMemo, useState } from 'react'
import styles from './index.module.scss'
import { useSelector } from 'react-redux'
import store, { RootState } from '@/store'
import { openLink } from '@/utils/history'
import TableList from '@/pages/Zother/TableList'
import { API_getFileList, API_downloadFiles } from '@/store/action/Cledger/C4file'
import { goodsFileTableC } from '@/utils/tableData'
import { Button, message } from 'antd'
import { baseURL } from '@/utils/http'
import { FileListType } from '@/components/Z3upFiles/data'
import ImageLazy from '@/components/ImageLazy'
import { EyeOutlined } from '@ant-design/icons'
import DownLog from '@/pages/Zother/DownLog'
import { fileImgArr } from '@/utils'

const C4search = [
  {
    type: 'input',
    key: 'searchKey',
    placeholder: `搜索附件名称、藏品登记号、藏品名称`
  }
]

const C4baseFormData = {
  pageSize: 10,
  pageNum: 1,
  searchKey: '',
  type: ''
}

function C4file() {
  // 从仓库拿数据
  const tableInfo = useSelector((state: RootState) => state.C4file.tableInfo)
  const [fileType, setFileType] = useState<string>('')
  const currentTypeValue = fileType
  // 跨页参数
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([])
  // 下载记录参数
  const [downLogId, setDownLogId] = useState(0)
  // 额外参数
  const extraParams = useMemo(
    () => ({
      type: currentTypeValue
    }),
    [currentTypeValue]
  )

  // 跨页多选
  const rowSelection = useMemo(
    () => ({
      selectedRowKeys,
      // 这里不直接用 onChange 的 keys 覆盖，避免翻页时丢失其他页勾选
      onChange: () => {},
      // 单行勾选/取消
      onSelect: (record: any, selected: boolean) => {
        const id = record.id as React.Key
        setSelectedRowKeys(prev => {
          if (selected) {
            if (prev.includes(id)) return prev
            return [...prev, id]
          } else {
            return prev.filter(k => k !== id)
          }
        })
      },
      // 全选/全不选当前页
      onSelectAll: (selected: boolean, _selectedRows: any[], changeRows: any[]) => {
        const changeIds = changeRows.map(r => r.id as React.Key)
        setSelectedRowKeys(prev => {
          if (selected) {
            const set = new Set<React.Key>(prev)
            changeIds.forEach(id => set.add(id))
            return Array.from(set)
          } else {
            return prev.filter(k => !changeIds.includes(k))
          }
        })
      },
      preserveSelectedRowKeys: true
    }),
    [selectedRowKeys]
  )

  // 下载方法
  const downloadFn = async (ids: number | number[]) => {
    const idArr = Array.isArray(ids) ? ids : [ids]
    if (!idArr.length) return

    const res: any = await API_downloadFiles(idArr)
    if (res && res.code === 0 && res.data) {
      const path = res.data as string
      const fullUrl = path.startsWith('http') ? path : `${baseURL}${path}`
      window.open(fullUrl)
    }
  }

  // 故事管理/藏品总账定制右侧内容
  const storyTableListToprr = ({
    clickSearch,
    resetSelectFu
  }: {
    clickSearch: () => void
    resetSelectFu: () => void
  }) => {
    const toggleType = (key: string) => {
      setFileType(prev => (prev === key ? '' : key))
    }

    const handleReset = () => {
      setFileType('')
      setSelectedRowKeys([])
      resetSelectFu()
    }

    return (
      <>
        <Button type={fileType === '' ? 'primary' : 'default'} onClick={() => setFileType('')}>
          全部
        </Button>
        <Button type={fileType === 'img' ? 'primary' : 'default'} onClick={() => toggleType('img')}>
          图像
        </Button>
        <Button
          type={fileType === 'model' ? 'primary' : 'default'}
          onClick={() => toggleType('model')}
        >
          3D
        </Button>
        <Button
          type={fileType === 'audio' ? 'primary' : 'default'}
          onClick={() => toggleType('audio')}
        >
          音频
        </Button>
        <Button
          type={fileType === 'video' ? 'primary' : 'default'}
          onClick={() => toggleType('video')}
        >
          视频
        </Button>
        <Button type={fileType === 'doc' ? 'primary' : 'default'} onClick={() => toggleType('doc')}>
          文档
        </Button>
        <Button
          type={fileType === 'other' ? 'primary' : 'default'}
          onClick={() => toggleType('other')}
        >
          其他
        </Button>
        &nbsp;
        <Button
          type='primary'
          onClick={() => {
            const ids = selectedRowKeys.map(key => Number(key)).filter(id => !Number.isNaN(id))
            if (ids.length === 0) {
              message.warning('请先选择要下载的附件')
              return
            }

            downloadFn(ids)
          }}
        >
          批量下载
        </Button>
        &nbsp;
        <Button type='primary' onClick={clickSearch}>
          查询
        </Button>
        &nbsp;
        <Button onClick={handleReset}>重置</Button>
      </>
    )
  }

  // 故事管理/藏品总账定制右侧操作按钮
  const storyTableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => (
          <>
            <Button
              size='small'
              type='text'
              onClick={() => openLink(`/goodsLook/${item.moduleId}`)}
            >
              查看藏品
            </Button>
            <Button
              size='small'
              type='text'
              onClick={() => {
                const id = Number(item.id)
                if (Number.isNaN(id)) {
                  message.error('当前附件ID异常，无法下载')
                  return
                }
                downloadFn(id)
              }}
            >
              下载
            </Button>
            <Button size='small' type='text' onClick={() => setDownLogId(item.id)}>
              下载记录
            </Button>
          </>
        )
      }
    ]
  }, [])

  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>
        }
      }
    })

    return arr
  }, [])

  return (
    <div className={styles.B1collect}>
      <div className='pageTitle'>藏品附件</div>

      <TableList
        baseFormData={C4baseFormData}
        getListAPI={API_getFileList}
        pageKey='file'
        tableInfo={tableInfo}
        columnsTemp={goodsFileTableC}
        yHeight={585}
        rightBtnWidth={720}
        leftRowWidth={'50%'}
        searchDom={C4search}
        storyTableListToprr={storyTableListToprr}
        storyTableLastBtn={storyTableLastBtn}
        extraParams={extraParams}
        rowSelection={rowSelection}
        staBtn={staBtn}
      />

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

const MemoC4file = React.memo(C4file)

export default MemoC4file
