import React, { useState, useEffect, useRef, useMemo } from 'react'
import styles from './index.module.scss'
import { importZipDataTableCheckC } from '@/utils/tableData'
import { selectObj } from '@/utils/dataChange'
import MyTable from '@/components/MyTable'
import { Input, Select, Button } from 'antd'
import { API_addImportZip, API_addImportZipRecord } from '@/store/action/Cledger/C1ledger'
import { MessageFu } from '@/utils/message'

type Props = {
  onClose: () => void
  tableInfo: any
  uploadFu: (e: React.ChangeEvent<HTMLInputElement>) => void
  isLook?: boolean // 是否查看模式
}

function C1ImportZipRes({ onClose, tableInfo, uploadFu, isLook = false }: Props) {
  console.log('tableInfo', tableInfo)
  const successCount = useMemo(() => {
    return tableInfo.pcsSuccess ?? tableInfo.img.filter((item: any) => item.isTrue === 1).length
  }, [tableInfo.img, tableInfo.pcsSuccess])
  const errorCount = useMemo(() => {
    return tableInfo.pcsError ?? tableInfo.img.filter((item: any) => item.isTrue === 0).length
  }, [tableInfo.img, tableInfo.pcsError])
  const [tableInfoData, setTableInfoData] = useState(tableInfo.img)
  const [searchKey, setSearchKey] = useState('')
  const [checkResult, setCheckResult] = useState()
  const [importLoading, setImportLoading] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)

  // 条件搜索
  useEffect(() => {
    const filtered = tableInfo.img.filter((item: any) => {
      const matchesSearch =
        !searchKey || item.num.includes(searchKey) || item.name.includes(searchKey)
      const matchesCheck = checkResult === undefined || item.isTrue === checkResult
      return matchesSearch && matchesCheck
    })
    setTableInfoData(filtered)
  }, [tableInfo.img, searchKey, checkResult])

  // 重新上传
  const reUploadFu = () => {
    fileInputRef.current?.click()
    setSearchKey('')
    setCheckResult(undefined)
  }

  // 导入校验成功的数据：先添加记录，再导入数据
  const importSuccessFu = async () => {
    const successData = tableInfo.img.filter((item: any) => item.isTrue === 1)
    if (successData.length === 0) {
      MessageFu.warning('没有校验成功的数据可导入')
      return
    }
    setImportLoading(true)
    try {
      // 1. 先添加记录
      const recordRes: any = await API_addImportZipRecord({
        fileName: tableInfo.fileName,
        filePath: tableInfo.filePath,
        pcsError: errorCount,
        pcsSuccess: successCount,
        pcsTotal: tableInfo.img.length,
        type: 'zip'
      } as any)
      if (recordRes?.code !== 0) {
        MessageFu.error(recordRes?.msg || '添加记录失败')
        return
      } else {
        // 2. 再导入数据
        const importId = recordRes.data.id
        const payload = successData.map((item: any) => ({
          description: item.description ?? item.desc ?? '',
          effect: item.effect ?? '',
          fileName: item.fileName ?? '',
          filePath: item.filePath ?? '',
          id: item.id ?? 0,
          importError: 0,
          importId: importId,
          isTrue: item.isTrue,
          num: item.num ?? '',
          type: item.type
        }))
        const res: any = await API_addImportZip(payload as any)
        if (res?.code === 0) {
          MessageFu.success('导入成功')
          onClose()
        } else {
          MessageFu.error(res?.msg || '导入失败')
        }
      }
    } catch (err: any) {
      MessageFu.error(err?.response?.data?.msg || err?.message || '导入失败')
    } finally {
      setImportLoading(false)
    }
  }

  return (
    <div className={styles.C1ImportRes}>
      <div className={styles.TableListTopInfo}>
        <h2>{tableInfo.fileName}</h2>
        <div className='i1'>导入数据条数: {tableInfo.img.length}</div>
        <div className='i1'>校验成功条数: {successCount}</div>
        <div className='i1'>校验失败条数: {errorCount}</div>
      </div>
      <div className={styles.TableListTop}>
        <div
          className='TableListTopll'
          style={{
            width: `100%`
          }}
        >
          <div style={{ width: '20%' }}>
            <Input
              placeholder='搜索藏品登记号、藏品名称，不超过30个字'
              maxLength={30}
              value={searchKey}
              onChange={e => setSearchKey(e.target.value)}
            />
          </div>
          <div style={{ width: '20%' }}>
            <Select
              allowClear={true}
              placeholder='校验结果'
              value={checkResult}
              onChange={e => setCheckResult(e)}
              options={selectObj['校验结果']}
            />
          </div>
        </div>
      </div>
      <div className={`${styles.TableListTable} table-list-table`}>
        <MyTable
          rowKey='fileName'
          list={tableInfoData}
          columnsTemp={importZipDataTableCheckC}
          yHeight={500}
        />
      </div>
      <div className={styles.TableListBottom}>
        {!isLook ? (
          <>
            <input
              ref={fileInputRef}
              type='file'
              accept='.zip,.rar'
              style={{ display: 'none' }}
              onChange={uploadFu}
            />
            <Button type='primary' onClick={reUploadFu}>
              重新上传压缩包
            </Button>
            <Button type='primary' loading={importLoading} onClick={importSuccessFu}>
              导入校验成功的数据
            </Button>
            <Button onClick={() => onClose()}>取消导入</Button>
          </>
        ) : (
          <Button onClick={() => onClose()}>返回</Button>
        )}
      </div>
    </div>
  )
}

const MemoC1ImportZipRes = React.memo(C1ImportZipRes)

export default MemoC1ImportZipRes
