import React, { useCallback, useEffect, useRef, useState } from 'react'
import { Button, Modal } from 'antd'
import { MessageFu } from '@/utils/message'
import { API_upFile } from '@/store/action/layout'
import { fileDomInitialFu } from '@/utils/domShow'
import styles from './index.module.scss'
import { TypeinfoXLSX } from '../../type'
import MyPopconfirm from '@/components/MyPopconfirm'
import { B1Xtype } from '../../data'
import MyTable from '@/components/MyTable'
import { B1TableC2up } from '@/utils/tableData'
import { B1X_APIadds } from '@/store/action/B1collect'
import { forwardRef, useImperativeHandle } from 'react'
import { A3m_APIaddGoods_2, A3m_APIaddZip } from '@/store/action/A3machineReg'

// 删掉前面2个  0,10000,12008,12563 == 12008,12563
const arrTemp = [
  'dictAge',
  'dictAgeFirst',
  'dictType',
  'source',
  'dictTexture1',
  'dictTexture2',
  'dictTexture3',
  'inDictDateScope',
  'qualityDictScope',
  'dictTorn',
  'preserveState'
  // 重量单位。藏品征集的没有前缀
  // 'qualityUnit',
]

type Props = {
  closeFu: () => void
  infoXLSX: TypeinfoXLSX
  upSuccFu: (succArr: B1Xtype[], errArr: B1Xtype[]) => void
  clickSuccFu: (arr: B1Xtype[]) => void
  isZongZhang?: boolean
  ref: any //当前自己的ref，给父组件调用
  url: string
  pageType: '藏品总账' | '藏品征集'
}

function B1upXLSX(
  { closeFu, infoXLSX, clickSuccFu, upSuccFu, isZongZhang, url, pageType }: Props,
  ref: any
) {
  const arrTempRef = useRef(arrTemp)

  useEffect(() => {
    if (pageType === '藏品总账') arrTempRef.current.push('qualityUnit')
  }, [pageType])

  // 藏品总账导入的类型 一普 和省平台
  const zongZhnagType = useRef('')

  // 上传表格数据
  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('.xlsx')) {
          e.target.value = ''
          return MessageFu.warning(`只支持xlsx格式!`)
        }

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

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

        e.target.value = ''

        try {
          const res = await API_upFile(fd, url)

          if (res.code === 0) {
            MessageFu.success('上传成功!')
            const arrAll: any[] = (pageType === '藏品总账' ? res.data.excel : res.data) || []

            if (pageType === '藏品总账') {
              fileInfo.current = { fileName: res.data.fileName, filePath: res.data.filePath }
            }

            const succArr: B1Xtype[] = []
            const errArr: B1Xtype[] = []

            arrAll.forEach((v, i) => {
              arrTempRef.current.forEach(c => {
                if (v[c] && v[c] !== '-1') {
                  let tttt: string[] = v[c].split(',')
                  v[c] = tttt.slice(3).join(',')
                }
              })

              if (v.isTrue === 1) succArr.push(v)
              else errArr.push(v)
            })
            upSuccFu(succArr, errArr)
          }
          fileDomInitialFu()
        } catch (error) {
          console.error(error)

          fileDomInitialFu()
        }
      }
    },
    [pageType, upSuccFu, url]
  )

  const [btnAc, setBtnAc] = useState('成功')

  // 藏品总账才有的 附件名和附件路径
  const fileInfo = useRef({ fileName: '', filePath: '' })

  // 点击导入当前数据
  const btnOk = useCallback(async () => {
    if (pageType === '藏品征集') {
      const res = await B1X_APIadds(
        infoXLSX.succ.map(v => ({
          ...v,
          id: null
        }))
      )
      if (res.code === 0) {
        MessageFu.success('导入成功')
        clickSuccFu(res.data)
        closeFu()
      }
    } else {
      const obj = {
        fileName: fileInfo.current.fileName,
        filePath: fileInfo.current.filePath,
        pcsError: infoXLSX.err.length,
        pcsSuccess: infoXLSX.succ.length,
        pcsTotal: infoXLSX.err.length + infoXLSX.succ.length,
        type: zongZhnagType.current
      }

      const res1 = await A3m_APIaddZip(obj)

      if (res1.code === 0) {
        const obj2 = [...infoXLSX.succ, ...infoXLSX.err].map(v => ({
          ...v,
          id: null,
          importId: res1.data.id,
          importDesc: JSON.stringify(v.error || '[]'),
          importError: v.isTrue === 1 ? '0' : '1'
          // importRow: v.row
        }))

        const res2 = await A3m_APIaddGoods_2(obj2)

        if (res2.code === 0) {
          MessageFu.success('导入成功')
          clickSuccFu(res2.data)
          closeFu()
        }
      }
    }
  }, [clickSuccFu, closeFu, infoXLSX, pageType])

  // 让父组件调用
  const openUpFu = useCallback((val: string) => {
    // console.log(123, val)
    zongZhnagType.current = val

    upBiaoGeRef.current?.click()
  }, [])

  // 藏品总账点击查看

  // 可以让父组件调用子组件的方法
  useImperativeHandle(ref, () => ({
    openUpFu
  }))

  return (
    <>
      <Button hidden={isZongZhang} onClick={() => upBiaoGeRef.current?.click()}>
        上传表格数据
      </Button>
      <input
        id='upInput'
        type='file'
        accept='.xlsx'
        ref={upBiaoGeRef}
        onChange={e => upBiaoGeFu(e)}
      />
      {infoXLSX.show ? (
        <Modal
          wrapClassName={styles.B1upXLSX}
          destroyOnClose
          open={true}
          title={
            <>
              导入数据条数：{infoXLSX.succ.length + infoXLSX.err.length}&emsp;&emsp;校验成功条数：
              {infoXLSX.succ.length}&emsp;&emsp;校验失败条数：{infoXLSX.err.length}
            </>
          }
          footer={[]}
        >
          <div className='B1XLmain'>
            <div className='B1XLtop'>
              {['成功', '失败'].map(v => (
                <Button
                  key={v}
                  type={v === btnAc ? 'primary' : 'default'}
                  onClick={() => setBtnAc(v)}
                >
                  {v} {v === '成功' ? infoXLSX.succ.length : infoXLSX.err.length}
                </Button>
              ))}
            </div>

            <MyTable
              rowKey='row'
              classKey='B1upXLSX'
              yHeight={500}
              list={btnAc === '成功' ? infoXLSX.succ : infoXLSX.err}
              columnsTemp={B1TableC2up(btnAc, pageType === '藏品总账')}
              lastBtn={[]}
              pagingInfo={false}
            />

            <div className='B1XLbtn'>
              {infoXLSX.type === '查看' ? (
                <Button onClick={closeFu}>关闭</Button>
              ) : (
                <>
                  <Button type='primary' onClick={() => upBiaoGeRef.current?.click()}>
                    重新上传表格
                  </Button>
                  &emsp;
                  <Button type='primary' disabled={infoXLSX.succ.length === 0} onClick={btnOk}>
                    导入当前数据
                  </Button>
                  &emsp;
                  <MyPopconfirm txtK='取消' onConfirm={closeFu} Dom={<Button>取消导入</Button>} />
                </>
              )}
            </div>
          </div>
        </Modal>
      ) : null}
    </>
  )
}

export default forwardRef(B1upXLSX)
