import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button } from 'antd'
import MyTable from '@/components/MyTable'
import MyPopconfirm from '@/components/MyPopconfirm'
import { baseURL } from '@/utils/http'
import B1upXLSX from '@/pages/B_enterTibet/B1collect/B1edit/B1upXLSX'
import { TypeinfoXLSX } from '@/pages/B_enterTibet/B1collect/type'
import C4impImg from './C4impImg'
import { C4tableCFu } from '@/utils/tableData'
import { A3m_APIdel, A3m_APIgetList, A3m_APIlookInfo } from '@/store/action/A3machineReg'
import { MessageFu } from '@/utils/message'
import { B1Xtype } from '@/pages/B_enterTibet/B1collect/data'

type Props = {
  colseFu: (flag: boolean) => void
}

function C4import({ colseFu }: 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: '4'
    })
    if (res.code === 0) {
      setTableObj({
        list: res.data.records || [],
        total: res.data.total
      })
    }
  }, [formData])

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

  const [acTxt, setAcTxt] = useState('导入藏品数据')

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

  // 点击查看
  const lookTableFu = useCallback(async (id: number) => {
    const res = await A3m_APIlookInfo('4', id)
    if (res.code === 0) {
      const succArr: B1Xtype[] = []
      const errArr: B1Xtype[] = []
      res.data.forEach((v: any) => {
        if (v.importError === 0) succArr.push({ ...v, row: v.id })
        else {
          errArr.push({
            ...v,
            row: v.id,
            error: JSON.parse(v.importDesc || '[]')
          })
        }
      })

      setInfoXLSX({
        show: true,
        succ: succArr,
        err: errArr,
        type: '查看'
      })
    }
  }, [])

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

  const flagRef = useRef(false)
  // 导入合格数据之后变成true

  const B1upXLSXRef = useRef<any>(null)

  // 上传表格数据
  const [infoXLSX, setInfoXLSX] = useState<TypeinfoXLSX>({
    show: false,
    succ: [],
    err: []
  })

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

  return (
    <div className={styles.C4import}>
      <div className='C4top'>
        <div>
          <span className='C4top11'>
            {['导入藏品数据', '导入藏品图片'].map(v => (
              <Button
                onClick={() => setAcTxt(v)}
                key={v}
                type={acTxt === v ? 'primary' : 'default'}
              >
                {v}
              </Button>
            ))}
          </span>
          {acTxt === '导入藏品数据' ? (
            <>
              一普数据{' '}
              <a
                href={`${baseURL}/baseData/ZP_TEMP.xlsx`}
                download='一普数据模板'
                target='_blank'
                rel='noreferrer'
              >
                <Button>下载模板</Button>
              </a>
              <Button type='primary' onClick={() => B1upXLSXRef.current?.openUpFu('1')}>
                上传表格
              </Button>
              <span className='jianGe'></span>
              省平台数据{' '}
              <a
                href={`${baseURL}/baseData/ZP_TEMP.xlsx`}
                download='省平台数据模板'
                target='_blank'
                rel='noreferrer'
              >
                <Button>下载模板</Button>
              </a>
              <Button type='primary' onClick={() => B1upXLSXRef.current?.openUpFu('2')}>
                上传表格
              </Button>
              <span className='C4tit'>每组数据最多1000条</span>
              <B1upXLSX
                pageType='藏品总账'
                ref={B1upXLSXRef}
                closeFu={() => setInfoXLSX({ show: false, succ: [], err: [] })}
                infoXLSX={infoXLSX}
                upSuccFu={(succ, err) => setInfoXLSX({ show: true, succ, err })}
                isZongZhang={true}
                url='cms/import/im/upload/excel'
                clickSuccFu={arr => {
                  // console.log(123, arr)
                  getListFu()
                  // 导入成功
                  flagRef.current = true
                }}
              />
            </>
          ) : null}
        </div>
        <Button onClick={() => colseFu(flagRef.current)}>返回</Button>
      </div>

      <div hidden={acTxt !== '导入藏品数据'}>
        <MyTable
          classKey='C4import'
          yHeight={655}
          list={tableObj.list}
          columnsTemp={C4tableCFu('导入藏品数据')}
          lastBtn={tableLastBtn}
          pageNum={formData.pageNum}
          pageSize={formData.pageSize}
          total={tableObj.total}
          onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
        />
      </div>

      <C4impImg hidden={acTxt === '导入藏品数据'} />

      {/* 表格 */}
    </div>
  )
}

const MemoC4import = React.memo(C4import)

export default MemoC4import
