import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { A1_APIfileDel, A1_APIfileGetList, A1_APIfileSave } from '@/store/action/A1record'
import { Button, Input, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import { A1fileArr, fileImgArr, fileTypeRes, fileVideoArr } from '../data'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import MyTable from '@/components/MyTable'
import { API_upFile } from '@/store/action/layout'
import { fileDomInitialFu } from '@/utils/domShow'
import ImageLazy from '@/components/ImageLazy'
import YtableVideo from '@/components/YtableVideo'
import { baseURL } from '@/utils/http'

type ListType = {
  id: number
  fileName: string
  filePath: string
  thumb: string
  type: string
  effectDictId: number
}

type FromDataType = {
  effectDictId: number | null
  searchKey: string
  type: string | null
}

const baseFromData: FromDataType = {
  effectDictId: null,
  searchKey: '',
  type: null
}

type Props = {
  sId: number
}

function A1tab2file({ sId }: Props) {
  const listObj = useSelector((state: RootState) => state.A3dict.listObj)

  const [fromData, setFromData] = useState(baseFromData)

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

  const getListFu = useCallback(async () => {
    const res = await A1_APIfileGetList({ ...fromData, moduleId: sId })

    if (res.code === 0) {
      setList(res.data || [])
    }
  }, [fromData, sId])

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

  // 作品名称的输入
  const timeRef = useRef(-1)
  const [inputKey, setInputKey] = useState(0)
  const fromKeyChangeFu = useCallback(
    (e: React.ChangeEvent<HTMLInputElement>, key: 'searchKey') => {
      clearTimeout(timeRef.current)
      timeRef.current = window.setTimeout(() => {
        setFromData({ ...fromData, [key]: e.target.value })
      }, 500)
    },
    [fromData]
  )

  // 下拉框的改变
  const selectChangeFu = useCallback(
    (value: any, key: 'type' | 'effectDictId') => {
      setFromData({ ...fromData, [key]: value })
    },
    [fromData]
  )

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setInputKey(Date.now())
    setFromData({ ...baseFromData })
  }, [])

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      const res = await A1_APIfileDel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功!')
        getListFu()
      }
    },
    [getListFu]
  )

  // 表格下拉框改变
  const effectDictIdChange = useCallback(
    async (id: number, effectDictId: number) => {
      const res = await A1_APIfileSave({ id, effectDictId })
      if (res.code === 0) {
        getListFu()
      }
    },
    [getListFu]
  )

  const staBtn = useMemo(() => {
    return [
      {
        title: '附件名称',
        render: (item: ListType) => item.fileName || '（空）'
      },
      {
        title: '附件类型',
        render: (item: ListType) => A1fileArr.find(v => v.value === item.type)?.label
      },
      {
        title: '附件用途',
        render: (item: ListType) => (
          <Select
            style={{ width: 200 }}
            value={item.effectDictId}
            onChange={e => effectDictIdChange(item.id, e)}
            options={listObj.effect.map(v => ({ value: v.id, label: v.name }))}
          />
        )
      },
      {
        title: '缩略图/视频',
        render: (item: ListType) => {
          const fileNameArr = item.fileName.split('.')
          const fileNameLast = fileNameArr[fileNameArr.length - 1]

          return fileImgArr.includes(fileNameLast.toLowerCase()) ? (
            <div className='tableImgAuto'>
              <ImageLazy width={60} height={60} srcBig={item.filePath} src={item.thumb} />
            </div>
          ) : fileVideoArr.includes(fileNameLast.toLowerCase()) ? (
            <YtableVideo src={item.filePath} />
          ) : (
            ' - '
          )
        }
      }
    ]
  }, [effectDictIdChange, listObj.effect])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: ListType) => {
          return (
            <>
              <Button size='small' type='text'>
                <a
                  href={baseURL + item.filePath}
                  download
                  target='_blank'
                  className='ZTbox2Down'
                  rel='noreferrer'
                >
                  下载
                </a>
              </Button>
              <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
            </>
          )
        }
      }
    ]
  }, [delTableFu])

  const myInput = useRef<HTMLInputElement>(null)

  // 上传附件
  const handeUpPhoto = useCallback(
    async (e: React.ChangeEvent<HTMLInputElement>) => {
      if (e.target.files) {
        // 拿到files信息
        const filesInfo = e.target.files[0]
        // console.log("-----", filesInfo.type);
        // 创建FormData对象
        const fd = new FormData()
        // 把files添加进FormData对象（‘photo’为后端需要的字段）
        const typeRes = fileTypeRes(filesInfo.name)
        fd.append('type', typeRes)
        fd.append('dirCode', 'A1recordFile')
        fd.append('moduleId', sId + '')
        fd.append('isDb', 'true')
        fd.append('file', filesInfo)

        // 开启压缩图片
        fd.append('isCompress', 'true')

        e.target.value = ''

        try {
          const res = await API_upFile(fd, 'cms/bridgeFile/upload')
          if (res.code === 0) {
            MessageFu.success('上传成功!')
            getListFu()
          }
          fileDomInitialFu()
        } catch (error) {
          fileDomInitialFu()
        }
      }
    },
    [getListFu, sId]
  )

  return (
    <div className={styles.A1tab2file}>
      <input id='upInput' type='file' ref={myInput} onChange={e => handeUpPhoto(e)} />

      <div className='A1T2top'>
        <div className='A1T2top1'>
          <div>
            <Input
              key={inputKey}
              maxLength={30}
              showCount
              style={{ width: 300 }}
              placeholder='请输入附件名称'
              allowClear
              onChange={e => fromKeyChangeFu(e, 'searchKey')}
            />
          </div>

          <div>
            <Select
              allowClear
              style={{ width: 200 }}
              placeholder='附件类型'
              value={fromData.type || null}
              onChange={e => selectChangeFu(e, 'type')}
              options={A1fileArr}
            />
          </div>

          <div>
            <Select
              allowClear
              style={{ width: 200 }}
              placeholder='附件用途'
              value={fromData.effectDictId || null}
              onChange={e => selectChangeFu(e, 'effectDictId')}
              options={listObj.effect.map(v => ({ value: v.id, label: v.name }))}
            />
          </div>
        </div>
        <div className='A1T2top2'>
          <Button onClick={resetSelectFu}>重置</Button>&emsp;
          <Button type='primary' onClick={() => myInput.current?.click()}>
            上传附件
          </Button>
        </div>
      </div>

      <MyTable
        classKey='A1tab2file'
        list={list}
        columnsTemp={[
          ['txt', '上传人', 'creatorName'],
          ['txt', '上传时间', 'createTime']
        ]}
        staBtn={staBtn}
        lastBtn={tableLastBtn}
        pagingInfo={false}
      />
    </div>
  )
}

const MemoA1tab2file = React.memo(A1tab2file)

export default MemoA1tab2file
