import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button } from 'antd'
import { MessageFu } from '@/utils/message'
import { fileDomInitialFu } from '@/utils/domShow'
import { API_upFile } from '@/store/action/layout'
import MyTable from '@/components/MyTable'
import { C4zipResDtaFu, C4zipType } from '../data'
import C4imgModal from '../C4imgModal'
import { C4tableCFu } from '@/utils/tableData'
import { A3m_APIdel, A3m_APIgetList, A3m_APIlookInfo } from '@/store/action/A3machineReg'
import MyPopconfirm from '@/components/MyPopconfirm'

type Props = {
  hidden: boolean
}

function C4impImg({ hidden }: Props) {
  const [formData, setFormData] = useState({
    pageNum: 1,
    pageSize: 10
  })

  // 列表数据
  const [tableObj, setTableObj] = useState({
    list: [],
    total: 0
  })

  // 获取列表信息
  const getListFu = useCallback(async () => {
    const res = await A3m_APIgetList({
      ...formData,
      type: '3'
    })
    if (res.code === 0) {
      setTableObj({
        list: res.data.records || [],
        total: res.data.total
      })
    }
  }, [formData])

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

  // 上传表格数据
  const upBiaoGeRef = useRef<HTMLInputElement>(null)

  // 上传表格处理函数
  const upBiaoGeFu = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
    if (e.target.files) {
      // 拿到files信息
      const filesInfo = e.target.files[0]

      // 校验格式
      if (
        !filesInfo.name.toLowerCase().endsWith('.zip') &&
        !filesInfo.name.toLowerCase().endsWith('.rar')
      ) {
        e.target.value = ''
        return MessageFu.warning(`只支持zip/rar格式!`)
      }

      // 创建FormData对象
      const fd = new FormData()

      fd.append('file', filesInfo)
      fd.append('type', 'doc')
      // fd.append('dirCode', 'C4machineRegImg')
      fd.append('isDb', 'true')

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

      e.target.value = ''

      try {
        const res = await API_upFile(fd, 'cms/import/im/upload/zip')

        if (res.code === 0) {
          MessageFu.success('上传成功!')
          const { succArr, errArr } = C4zipResDtaFu(res.data.img || [])
          setZipList({
            type: '上传',
            succ: succArr,
            err: errArr,
            file: {
              fileName: res.data.fileName,
              filePath: res.data.filePath
            }
          })
        }
        fileDomInitialFu()
      } catch (error) {
        console.error(error)

        fileDomInitialFu()
      }
    }
  }, [])

  const lookFu = useCallback(async (id: number) => {
    const res = await A3m_APIlookInfo('3', id)
    if (res.code === 0) {
      const { succArr, errArr } = C4zipResDtaFu(res.data || [], true)
      setZipList({
        type: '查看',
        succ: succArr,
        err: errArr
      })
    }
  }, [])

  const delFu = useCallback(
    async (id: number) => {
      const res = await A3m_APIdel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功')
        getListFu()
      }
    },
    [getListFu]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '导入结果',
        render: (item: any) => (
          <Button size='small' type='text' onClick={() => lookFu(item.id)}>
            查看
          </Button>
        )
      },
      {
        title: '操作',
        render: (item: any) => {
          return (
            <MyPopconfirm
              txtK='删除'
              onConfirm={() => delFu(item.id)}
              Dom={
                <Button size='small' type='text' danger>
                  删除记录
                </Button>
              }
            />
          )
        }
      }
    ]
  }, [delFu, lookFu])

  // zip上传成功
  const [zipList, setZipList] = useState<C4zipType>({
    type: '',
    succ: [],
    err: []
  })

  // 页码变化
  const paginationChange = useCallback((pageNum: number, pageSize: number) => {
    setFormData({ pageNum, pageSize })
  }, [])

  return (
    <div className={styles.C4impImg} hidden={hidden}>
      <input
        id='upInput'
        type='file'
        accept='.zip,.rar'
        ref={upBiaoGeRef}
        onChange={e => upBiaoGeFu(e)}
      />

      <div className='C4Itop'>
        <Button type='primary' size='large' onClick={() => upBiaoGeRef.current?.click()}>
          上传压缩包(ZIP,RAR格式)
        </Button>
        <div>
          <p>图片需压缩成zip压缩包格式 &emsp;&emsp;图片的格式：jpg/png/bmp/gif，10M以内</p>
          <p>
            图片命名规则：藏品编号-图片类型-图片序号<span>(如D00001-A-01)</span>&emsp;&emsp;
            图片类型：A：正视图 B：俯视图 C：侧视图 D：全景图 E：局部图 F：底部图
          </p>
        </div>
      </div>

      <MyTable
        classKey='C4impImg'
        yHeight={590}
        list={tableObj.list}
        columnsTemp={C4tableCFu('')}
        lastBtn={tableLastBtn}
        pageNum={formData.pageNum}
        pageSize={formData.pageSize}
        total={tableObj.total}
        onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
      />

      {zipList.type ? (
        <C4imgModal
          succFu={getListFu}
          againUpFu={() => upBiaoGeRef.current?.click()}
          info={zipList}
          closeFu={() =>
            setZipList({
              type: '',
              succ: [],
              err: []
            })
          }
        />
      ) : null}
    </div>
  )
}

const MemoC4impImg = React.memo(C4impImg)

export default MemoC4impImg
