import React, { useState, useEffect, useRef, useMemo } from 'react'
import styles from './index.module.scss'
import { importDataTableCheckC } from '@/utils/tableData'
import { selectObj } from '@/utils/dataChange'
import MyTable from '@/components/MyTable'
import { Input, Select, Button } from 'antd'
import { API_addImportExcel, API_addImportExcelRecord } 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 C1ImportRes({ onClose, tableInfo, uploadFu, isLook = false }: Props) {
  const staBtn = [
    {
      title: '行数',
      render: (_: any, __: any, index: number) => index + 1
    }
  ]
  const lastBtn = [
    {
      title: '失败原因',
      render: (_: any, record: any) => {
        const isFail = record.importIsTrue === 0 || record.importIsTrue === 0
        const errArr = record.EError ?? record.eerror ?? []
        if (!isFail) return ''
        return Array.isArray(errArr) ? (
          <span style={{ whiteSpace: 'pre-line' }}>{errArr.join('\n')}</span>
        ) : (
          errArr
        )
      }
    }
  ]
  const successCount = useMemo(() => {
    return (
      tableInfo.pcsSuccess ?? tableInfo.excel.filter((item: any) => item.importIsTrue === 1).length
    )
  }, [tableInfo.excel, tableInfo.pcsSuccess])
  const errorCount = useMemo(() => {
    return (
      tableInfo.pcsError ?? tableInfo.excel.filter((item: any) => item.importIsTrue === 0).length
    )
  }, [tableInfo.excel, tableInfo.pcsError])
  const [tableInfoData, setTableInfoData] = useState(
    (tableInfo.excel ?? []).map((item: any, i: number) => ({ ...item, _rowKey: `row-${i}` }))
  )
  const [searchKey, setSearchKey] = useState('')
  const [checkResult, setCheckResult] = useState()
  const [importLoading, setImportLoading] = useState(false)
  const fileInputRef = useRef<HTMLInputElement>(null)
  // 条件搜索（保留 _rowKey 用于表格 key）
  useEffect(() => {
    const filtered = (tableInfo.excel ?? [])
      .map((item: any, i: number) => ({ ...item, _rowKey: `row-${i}` }))
      .filter((item: any) => {
        const matchesSearch =
          !searchKey || item.num.includes(searchKey) || item.name.includes(searchKey)
        const matchesCheck =
          checkResult === undefined ||
          item.importIsTrue === checkResult ||
          checkResult === item.importIsTrue
        return matchesSearch && matchesCheck
      })
    setTableInfoData(filtered)
  }, [tableInfo.excel, searchKey, checkResult])

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

  // 导入校验成功的数据
  const importSuccessFu = async () => {
    const successData = tableInfo.excel.filter((item: any) => item.importIsTrue === 1)
    if (successData.length === 0) {
      MessageFu.warning('没有校验成功的数据可导入')
      return
    }
    setImportLoading(true)
    try {
      // 1. 先添加记录
      const recordRes: any = await API_addImportExcelRecord({
        fileName: tableInfo.fileName,
        filePath: tableInfo.filePath,
        pcsError: errorCount,
        pcsSuccess: successCount,
        pcsTotal: tableInfo.excel.length,
        type: 'zip'
      } as any)
      if (recordRes?.code !== 0) {
        MessageFu.error(recordRes?.msg || '添加记录失败')
        return
      } else {
        // 2. 再导入数据
        const importId = recordRes.data.id
        const res: any = await API_addImportExcel(
          successData.map((item: any) => ({
            ...item,
            importId,
            importError: item.importIsTrue === 0 ? 1 : 0
          })) 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)
    }
  }

  const columnsTemp = useMemo(() => {
    const base = importDataTableCheckC
    return isLook
      ? [...base.slice(0, -1), ['txtChange', '校验结果', 'importError', { 1: '失败', 0: '成功' }]]
      : base
  }, [isLook])

  return (
    <div className={styles.C1ImportRes}>
      <div className={styles.TableListTopInfo}>
        <h2>{tableInfo.fileName}</h2>
        <div className='i1'>导入数据条数: {tableInfo.excel.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='_rowKey'
          list={tableInfoData}
          columnsTemp={columnsTemp}
          yHeight={500}
          staBtn={staBtn}
          lastBtn={lastBtn}
        />
      </div>
      <div className={styles.TableListBottom}>
        {!isLook ? (
          <>
            <input
              ref={fileInputRef}
              type='file'
              accept='.xlsx'
              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 MemoC1ImportRes = React.memo(C1ImportRes)

export default MemoC1ImportRes
