import React, { useCallback, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { Button } from 'antd'
import MyTable from '@/components/MyTable'
import { B3eTableC } from '@/utils/tableData'
import MyPopconfirm from '@/components/MyPopconfirm'
import classNames from 'classnames'
import Y1cathet from '@/pages/Y_goodsDetails/Y1cathet'
import { openGoodsInfoFu } from '@/utils/history'
import { useParams } from 'react-router-dom'
import B3GaddNow from './B3GaddNow'
import { forwardRef, useImperativeHandle } from 'react'
import B3GaddNew from './B3GaddNew'
import { TypeB3PageSta } from '../B3_4page/type'
import { C1GoodType } from '@/pages/C_goodsManage/C1ledger/type'

const sonUrlObj = {
  1: 'cms/orderHouse/goods/getList',
  2: 'cms/orderHide/goods/getList',
  3: 'cms/register/goods/getList',
  4: 'cms/orderDel/goods/getList'
}

type Props = {
  pageSta: TypeB3PageSta
}

function B3goodsTable({ pageSta }: Props, ref: any) {
  const {
    // id,
    pageKey
  } = useParams<any>()

  // 表格数据
  const [table, setTable] = useState<C1GoodType[]>([])

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      setTable(table.filter(v => v.id !== id))
    },
    [table]
  )

  // 打开侧边栏
  const [cathet, setCathet] = useState(0)

  const startBtn = useMemo(() => {
    return [
      {
        title: '藏品编号',
        render: (item: C1GoodType) => {
          return (
            <span
              onClick={() => setCathet(item.id)}
              className={classNames('D1GtNum', item.id === cathet ? 'D1GtNumAc' : '')}
            >
              {item.num || '（空）'}
            </span>
          )
        }
      }
    ]
  }, [cathet])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: C1GoodType) => {
          return (
            <>
              {['1', '2', '3'].includes(pageKey) &&
              ['编辑'].includes(pageSta) &&
              item.display === 0 ? (
                <Button
                  size='small'
                  type='text'
                  onClick={() => setNowSta({ key: pageKey, id: item.id + '', type: 'new' })}
                >
                  编辑
                </Button>
              ) : null}

              <Button size='small' type='text' onClick={() => openGoodsInfoFu(item.id)}>
                查看
              </Button>
              {['查看', '审批'].includes(pageSta) ? null : (
                <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
              )}
            </>
          )
        }
      }
    ]
  }, [delTableFu, pageKey, pageSta])

  // 从已存在的藏品中添加
  const [nowSta, setNowSta] = useState({ key: '', id: '', type: '' })

  // 可以让父组件调用子组件的方法
  // 返回数据
  const resData = useCallback(() => {
    return { tableIds: table.map(v => v.id).join(',') }
  }, [table])

  // 设置数据
  const setData = useCallback((arr: C1GoodType[]) => {
    setTable(arr)
  }, [])

  useImperativeHandle(ref, () => ({
    resData,
    setData
  }))

  // 点击 从已存在的藏品中添加
  const isNowFu = useCallback(async () => {
    const url = sonUrlObj[pageKey as '1']
    setNowSta({ key: pageKey, id: url, type: 'now' })
  }, [pageKey])

  return (
    <div className={styles.B3goodsTable}>
      <div className='B3eGtop'>
        <div className='B3eGtop1'>藏品清单</div>
        <div>
          {['查看', '审批'].includes(pageSta) ? null : (
            <>
              <Button type='primary' onClick={isNowFu}>
                从已存在的藏品中添加
              </Button>
              &emsp;
              <Button
                type='primary'
                onClick={() => setNowSta({ key: pageKey, id: 'null', type: 'new' })}
              >
                新增
              </Button>
            </>
          )}
        </div>
      </div>
      {/* 表格 */}
      <MyTable
        list={table}
        columnsTemp={B3eTableC}
        startBtn={startBtn}
        lastBtn={tableLastBtn}
        pagingInfo={false}
      />
      {/* 打开侧边栏 */}
      <Y1cathet sId={cathet} closeFu={() => setCathet(0)} />

      {nowSta.id ? (
        nowSta.type === 'now' ? (
          <B3GaddNow
            nowSta={nowSta}
            closeFu={() => setNowSta({ key: '', id: '', type: '' })}
            dataResFu={data => setTable(data)}
            oldCheckArr={table}
          />
        ) : (
          <B3GaddNew
            nowSta={nowSta}
            closeFu={() => setNowSta({ key: '', id: '', type: '' })}
            isEdit={false}
            succFu={(obj, type) => {
              if (type === '新增') setTable([obj, ...table])
              else
                setTable(
                  table.map(v => {
                    return v.id === obj.id ? obj : v
                  })
                )
            }}
          />
        )
      ) : null}
    </div>
  )
}
export default forwardRef(B3goodsTable)
