import React, { useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import TableList from '@/pages/Zother/TableList'
import { useSelector } from 'react-redux'
import { RootState } from '@/store'
import {
  API_getImportExcelList,
  API_getImportZipList,
  API_uploadImportExcel,
  API_uploadImportZip,
  API_getImportResult,
  API_deleteImportResult,
  API_getImportExcelResult,
  API_deleteImportExcelResult
} from '@/store/action/Cledger/C1ledger'
import { importDataTableC } from '@/utils/tableData'
import { Button, Radio } from 'antd'
import { MessageFu } from '@/utils/message'
import { baseURL } from '@/utils/http'
import C1ImportRes from '../C1ImportRes'
import C1ImportZipRes from '../C1importZipRes'

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

function C1Import({ onClose }: { onClose: () => void }) {
  const importExcelTableInfo = useSelector(
    (state: RootState) => state.C1ledger.importExcelTableInfo
  )
  const importZipTableInfo = useSelector((state: RootState) => state.C1ledger.importZipTableInfo)
  const [isImportData, setIsImportData] = useState(true)
  // 是否查看模式(查看历史记录)
  const [isLook, setIsLook] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  const clickSearchRef = useRef<() => void>(() => {})
  const [uploadData, setUploadData] = useState<{
    visible: boolean
    result: any | null
    errorMsg?: string
  }>({ visible: false, result: null })
  // 选择文件并上传--导入数据（excel
  const handleUploadExcel = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    const ext = file.name.split('.').pop()?.toLowerCase()
    if (!['xlsx'].includes(ext || '')) {
      MessageFu.warning('请选择 Excel 文件（.xlsx 或 .xls）')
      e.target.value = ''
      return
    }
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', 'doc')
    formData.append('dirCode', 'importExcel')
    try {
      const res: any = await API_uploadImportExcel(formData)
      e.target.value = ''
      if (res?.code === 0) {
        const data = res.data || {}
        setIsLook(false)
        setUploadData({
          visible: true,
          result: data
        })
        MessageFu.success('上传校验完成')
        clickSearchRef.current?.()
      } else {
        setUploadData({
          visible: false,
          result: null,
          errorMsg: res?.msg || '上传失败'
        })
      }
    } catch (err: any) {
      e.target.value = ''
      setUploadData({
        visible: false,
        result: null,
        errorMsg: err?.response?.data?.msg || err?.message || '上传失败'
      })
    }
  }

  // 选择文件并上传--导入图片（zip/rar）
  const handleUploadZip = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0]
    if (!file) return
    const ext = file.name.split('.').pop()?.toLowerCase()
    if (!['zip', 'rar'].includes(ext || '')) {
      MessageFu.warning('请选择 zip/rar 文件（.zip 或 .rar）')
      e.target.value = ''
      return
    }
    const formData = new FormData()
    formData.append('file', file)
    formData.append('type', 'other')
    formData.append('dirCode', 'importZip')
    try {
      const res: any = await API_uploadImportZip(formData as any)
      e.target.value = ''
      if (res?.code === 0) {
        const data = res.data || {}
        setIsLook(false)
        setUploadData({
          visible: true,
          result: data
        })
        MessageFu.success('上传校验完成')
        clickSearchRef.current?.()
      } else {
        setUploadData({
          visible: false,
          result: null,
          errorMsg: res?.msg || '上传失败'
        })
      }
    } catch (err: any) {
      e.target.value = ''
      setUploadData({
        visible: false,
        result: null,
        errorMsg: err?.response?.data?.msg || err?.message || '上传失败'
      })
    }
  }

  // 故事管理/藏品总账定制右侧内容
  const storyTableListToprr = ({
    clickSearch,
    resetSelectFu
  }: {
    clickSearch: () => void
    resetSelectFu: () => void
  }) => {
    clickSearchRef.current = resetSelectFu
    return (
      <>
        <div className='TableListToprrBox'>
          <Button onClick={onClose}>返回</Button>
          <Radio.Group>
            <Button
              value='importData'
              type={isImportData ? 'primary' : 'default'}
              onClick={() => setIsImportData(true)}
            >
              导入藏品数据
            </Button>
            <Button
              value='importImage'
              type={isImportData ? 'default' : 'primary'}
              onClick={() => setIsImportData(false)}
            >
              导入藏品图片
            </Button>
          </Radio.Group>
        </div>
        <div className='TableListToprrBox'>
          <input
            ref={fileInputRef}
            type='file'
            accept={isImportData ? '.xlsx' : '.zip,.rar'}
            style={{ display: 'none' }}
            onChange={isImportData ? handleUploadExcel : handleUploadZip}
          />
          {isImportData ? (
            <>
              <Button
                type='primary'
                onClick={() => window.open(`${baseURL}/baseData/ZP_TEMP.xlsx`)}
              >
                下载模板
              </Button>
              <Button type='primary' onClick={() => fileInputRef.current?.click()}>
                上传藏品数据
              </Button>
            </>
          ) : (
            <Button type='primary' onClick={() => fileInputRef.current?.click()}>
              上传压缩包（ZIP,RAR格式）
            </Button>
          )}
        </div>
      </>
    )
  }

  // 故事管理/藏品总账定制右侧操作按钮
  const storyTableLastBtn = useMemo(() => {
    // 点击查看导入结果
    const handleGetImportResult = (item: any) => {
      if (isImportData) {
        API_getImportExcelResult(item.id).then((res: any) => {
          setIsLook(true)
          setUploadData({
            visible: true,
            result: {
              excel: res.data,
              fileName: item.fileName,
              pcsSuccess: item.pcsSuccess,
              pcsError: item.pcsError
            }
          })
        })
      } else {
        API_getImportResult(item.id).then((res: any) => {
          setIsLook(true)
          setUploadData({
            visible: true,
            result: {
              img: res.data,
              fileName: item.fileName,
              pcsSuccess: item.pcsSuccess,
              pcsError: item.pcsError
            }
          })
        })
      }
    }

    // 点击删除导入结果
    const handleDeleteImportResult = (item: any) => {
      if (isImportData) {
        API_deleteImportExcelResult(item.id).then(() => {
          MessageFu.success('删除成功')
          clickSearchRef.current?.()
        })
      } else {
        API_deleteImportResult(item.id).then(() => {
          MessageFu.success('删除成功')
          clickSearchRef.current?.()
        })
      }
    }
    return [
      {
        title: '操作',
        render: (item: any) => (
          <>
            <Button size='small' type='text' onClick={() => handleGetImportResult(item)}>
              查看
            </Button>
            <Button size='small' type='text' onClick={() => handleDeleteImportResult(item)}>
              删除记录
            </Button>
          </>
        )
      }
    ]
  }, [isImportData])

  return (
    <div className={styles.C1Import}>
      {uploadData.visible ? (
        isImportData ? (
          <C1ImportRes
            onClose={() => setUploadData({ visible: false, result: null })}
            tableInfo={uploadData.result}
            uploadFu={handleUploadExcel}
            isLook={isLook}
          />
        ) : (
          <C1ImportZipRes
            onClose={() => setUploadData({ visible: false, result: null })}
            tableInfo={uploadData.result}
            uploadFu={handleUploadZip}
            isLook={isLook}
          />
        )
      ) : (
        <TableList
          key={isImportData ? 'importExcel' : 'importZip'}
          baseFormData={C1ImportBaseFormData}
          getListAPI={isImportData ? API_getImportExcelList : API_getImportZipList}
          pageKey={isImportData ? 'importExcel' : 'importZip'}
          tableInfo={isImportData ? importExcelTableInfo : importZipTableInfo}
          columnsTemp={importDataTableC}
          rightBtnWidth={'100%'}
          leftRowWidth={'20%'}
          yHeight={592}
          searchDom={[]}
          storyTableListToprr={storyTableListToprr}
          storyTableLastBtn={storyTableLastBtn}
        />
      )}
    </div>
  )
}

const MemoC1Import = React.memo(C1Import)

export default MemoC1Import
