import React, { useCallback, useEffect, useRef, useState } from 'react'
import AddGoods from './AddGoods'
import {
  FourAPI_create,
  FourAPI_getInfo,
  FourAPI_saveApply,
  FourAPI_saveDraft
} from '@/store/action/FourAll'
import history from '@/utils/history'
import { FourTableType } from '@/pages/B_enterTibet/B1collect/type'
function C1register() {
  const [waiId, setWaiId] = useState('')

  useEffect(() => {
    const url = window.location.href
    if (url.includes('?id=')) {
      const id = url.split('?id=')[1]
      if (id) setWaiId(id)
    } else setWaiId('null')
  }, [])

  // 顶部数据
  const [topInfo, setTopInfo] = useState({} as FourTableType)

  // 藏品清单快照数据1对1-把本身的id存起来
  const snapsIdRef = useRef(0)

  // 藏品登记 进来创建订单
  const createFu = useCallback(async () => {
    const res = await FourAPI_create('3')
    if (res.code === 0) {
      setTopInfo(res.data)
    }
  }, [])

  // 获取详情
  const getInfoFu = useCallback(async (id: string) => {
    const res = await FourAPI_getInfo('3', id)
    if (res.code === 0) {
      const data = res.data
      setTopInfo(data)
      if (data.snaps && data.snaps.length) {
        snapsIdRef.current = data.snaps[0].id
      }
    }
  }, [])

  useEffect(() => {
    if (waiId === 'null') createFu()
    else if (waiId) getInfoFu(waiId)
  }, [createFu, getInfoFu, waiId])

  return (
    <div>
      <div className='pageTitle'>藏品登记{waiId !== 'null' ? '-编辑' : ''}</div>

      {topInfo.id ? (
        <AddGoods
          closeFu={() => {}}
          nowSta={{ key: '藏品登记', id: topInfo.goodsIds ? topInfo.goodsIds : 'null' }}
          isEdit={false}
          succFu={async (obj, type, sta) => {
            const obj2 = {
              ...topInfo,
              goodsIds: obj.id + '',
              snaps: [
                {
                  goodsId: obj.id,
                  id: type === '新增' ? null : snapsIdRef.current ? snapsIdRef.current : null,
                  orderId: topInfo.id,
                  snap: JSON.stringify(obj)
                }
              ]
            }
            const res =
              sta === '存草稿'
                ? await FourAPI_saveDraft('3', obj2)
                : await FourAPI_saveApply('3', obj2)

            if (res.code === 0) {
              history.push('/goodEdit')
            }
          }}
        />
      ) : null}
    </div>
  )
}

const MemoC1register = React.memo(C1register)

export default MemoC1register
