import React, { forwardRef, useImperativeHandle, 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 AddGoods from '../AddGoods'
import { useInfo } from '../InfoContext'
import {
  GoodsType,
  sgBaseFormData,
  sgBaseFormDataGood,
  sgTopSelectDom,
  sgTopSelectDomGood
} from './data'
import { goodsSelectCuleC, goodsSonTableC } from '@/utils/tableData'
import { useParams } from 'react-router-dom'
import { openLink } from '@/utils/history'
import { FileUpInfoType } from '../data'
import SelectGoods from '../SelectGoods'
import MyTableForm, { MyTableMethods } from '@/components/MyTable/form'

type Props = {
  // 上传附件的信息(不需要新增藏品的不用传)
  fileUpInfo?: FileUpInfoType
  // 从征集中添加的api
  selectApi: any
  // 新增藏品的api(不需要新增藏品的不用传)
  addGoodsApi?: any
  // 拿线索为true，拿藏品为false
  isClueSelect: boolean
  // 选择藏品的按钮字符串
  btnTxt?: string
  // 是否有新增和编辑可以操作藏品，默认true
  addShow?: boolean
  // 是否需要编辑藏品
  needEdit?: boolean
  goodsSonTable?: any[]
  customRightBtn?: React.ReactNode
  // 选择列表按钮是否禁用
  clueShowBtnDisabled?: boolean
  selectGoodsParams?: any
  label?: string
  customTableLastBtn?: (item: GoodsType) => React.ReactNode
  tableLastWidth?: number
}

function SonGoodsList(
  {
    fileUpInfo,
    selectApi,
    addGoodsApi,
    isClueSelect,
    btnTxt,
    addShow = true,
    needEdit,
    goodsSonTable,
    customRightBtn,
    clueShowBtnDisabled,
    selectGoodsParams,
    label = '藏品清单',
    customTableLastBtn,
    tableLastWidth
  }: Props,
  ref: any
) {
  const tableRef = useRef<MyTableMethods | null>(null)
  const { info, snaps, setSnapsFu } = useInfo()

  const { key } = useParams<any>()
  // key:1 新增 2编辑 3审批 4查看

  const isLook = useMemo(() => {
    return ['3', '4'].includes(key)
  }, [key])

  const [openInfo, setOpenInfo] = useState({} as GoodsType)

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        width: tableLastWidth,
        render: (item: GoodsType) => {
          return (
            <>
              {isLook ? (
                <Button size='small' type='text' onClick={() => openLink(`/goodsLook/${item.id}`)}>
                  查看
                </Button>
              ) : (
                <>
                  {addShow ? (
                    <Button size='small' type='text' onClick={() => setOpenInfo(item)}>
                      编辑
                    </Button>
                  ) : null}

                  <MyPopconfirm
                    txtK='删除'
                    onConfirm={() => {
                      setSnapsFu(snaps.filter(v => v.id !== item.id))
                    }}
                  />
                </>
              )}
              {customTableLastBtn ? customTableLastBtn(item) : null}
            </>
          )
        }
      }
    ]
  }, [tableLastWidth, isLook, addShow, customTableLastBtn, setSnapsFu, snaps])

  // 从征集线索中添加
  const [clueShow, setClueShow] = useState(false)

  useImperativeHandle(ref, () => ({
    tableRef,
    snaps
  }))

  return (
    <div className={styles.SonGoodsList}>
      <div className='EdTit'>
        <div>{label}</div>
        {isLook ? (
          <div></div>
        ) : (
          <div>
            {customRightBtn ? customRightBtn : null}
            <Button type='primary' onClick={() => setClueShow(true)} disabled={clueShowBtnDisabled}>
              {btnTxt ? btnTxt : '从征集线索中添加'}
            </Button>
            {addShow ? (
              <Button type='primary' onClick={() => setOpenInfo({ id: -1 } as GoodsType)}>
                新增
              </Button>
            ) : null}
          </div>
        )}
      </div>
      <div className='SonGoodsListTable'>
        {needEdit ? (
          <MyTableForm
            ref={tableRef}
            rowKey='idTemp'
            classKey='SonGoodsList'
            list={snaps}
            columnsTemp={goodsSonTable || goodsSonTableC()}
            lastBtn={tableLastBtn}
            pagingInfo={false}
            readOnly={isLook}
          />
        ) : (
          <MyTable
            rowKey='idTemp'
            classKey='SonGoodsList'
            list={snaps}
            columnsTemp={goodsSonTableC()}
            lastBtn={tableLastBtn}
            pagingInfo={false}
          />
        )}
      </div>
      {openInfo.id ? (
        <AddGoods
          fileUpInfo={fileUpInfo!}
          APIsave={addGoodsApi}
          info={openInfo}
          isEdit={false}
          closeFu={() => setOpenInfo({} as GoodsType)}
          moduleId={info.id}
          succFu={(val: '新增' | '编辑', infoTemp: GoodsType) => {
            const info: GoodsType = { ...infoTemp, idTemp: infoTemp.id + 'goods' }

            if (val === '新增') setSnapsFu([info, ...snaps])
            else
              setSnapsFu(
                snaps.map(v => {
                  if (v.id === info.id || v.id === info.clueId) return info
                  else return v
                })
              )
          }}
        />
      ) : null}

      {/* 从藏品征集中添加 */}
      {clueShow ? (
        <SelectGoods
          canObj={selectGoodsParams}
          myType={isClueSelect ? '线索' : '藏品'}
          API_getList={selectApi}
          baseFormData={isClueSelect ? sgBaseFormData : sgBaseFormDataGood}
          topSelectDom={isClueSelect ? sgTopSelectDom : sgTopSelectDomGood}
          columnsTemp={isClueSelect ? goodsSelectCuleC : goodsSonTableC(true)}
          closeFu={() => setClueShow(false)}
          oldCheckArr={snaps}
          dataResFu={data => {
            // 需要过滤掉已经有id的-不替换数据，没有id的替换数据 因为数据可能已经在另外一个弹窗更新了
            const nowIds = snaps.map(v => v.id)
            const dataRes: GoodsType[] = data.map((v, i) => {
              v.idTemp = v.id + (isClueSelect ? 'clue' : 'goods')
              // 优先使用已存在的snap数据，否则使用新数据
              const item = nowIds.includes(v.id) ? snaps[i] : v
              // 如果是线索选择，添加标识
              if (isClueSelect) {
                // 因为征集和藏品表分开的，所以在藏品里面拿征集信息，自己加上这个标识
                return { ...item, pageType: 'clue' }
              }
              return item
            })

            setSnapsFu(dataRes)
          }}
        />
      ) : null}
    </div>
  )
}

const MemoSonGoodsList = React.memo(forwardRef(SonGoodsList))

export default MemoSonGoodsList
