import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useParams } from 'react-router-dom'
import styles from './index.module.scss'
import EditTop from '@/pages/Zother/EditTop'
import EditBtn from '@/pages/Zother/EditBtn'
import { InfoProvider, useInfo } from '@/pages/Zother/InfoContext'
import { rowArrTemp } from '@/pages/Zother/data'
import SonGoodsList from '@/pages/Zother/SonGoodsList'
import { F3_APIgetClueList, F3API_obj } from '@/store/action/Fstorehouse/F3outStorage'
import { Select } from 'antd'
import { selectObj } from '@/utils/dataChange'
import FileArchive from '@/pages/Zother/FileArchive'
import { F1_APIgetShowList, F1_APIgetStorageList } from '@/store/action/Fstorehouse/F1inStorage'

const rowArrBase = rowArrTemp('出库')
const rowArr = [
  rowArrBase[0],
  {
    name: '借展出库',
    key: 'showId',
    type: 'SelectSearch',
    placeholder: '请搜索展览名称',
    api: F1_APIgetShowList,
    searchParam: 'searchKey',
    labelKey: 'name',
    valueKey: 'id',
    optionLabel: (info: any) => info?.showName
  },
  ...rowArrBase.slice(1)
]

function F3editContent() {
  const { info, setSnapsFu, setInfoFu } = useInfo() as {
    info: any
    setSnapsFu: (snaps: any[]) => void
    setInfoFu: (info: any) => void
  }
  const { key } = useParams<any>()
  const canEdit = useMemo(() => ['1', '2'].includes(key), [key])
  const sonGoodsListRef = useRef<any>(null)
  const [selectStorage, setSelectStorage] = useState<any>(null)
  const [allWarehouseList, setAllWarehouseList] = useState<any[]>([])
  const warehouseOptions = useMemo(() => {
    return allWarehouseList.map((i: any) => ({
      label: i.name,
      value: i.id,
      managerUser: i.managerUser
    }))
  }, [allWarehouseList])

  const handleStorageChange = useCallback(
    async (value: string, option: any) => {
      setSelectStorage(option)
      setSnapsFu([])
    },
    [setSnapsFu]
  )

  const getStorageList = useCallback(async () => {
    const res = await F1_APIgetStorageList()
    setAllWarehouseList(res.data.records)
  }, [])

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

  useEffect(() => {
    if (!info?.storageId || !allWarehouseList.length) return
    const opt = warehouseOptions.find((o: any) => o.value === info.storageId)
    if (opt) {
      setSelectStorage(opt)
    }
  }, [info?.storageId, allWarehouseList.length, warehouseOptions])

  const getExtraData = (info: any, snaps: any[]) => {
    return {
      storageId: selectStorage?.value ?? undefined
    }
  }

  useEffect(() => {
    if (!info.num) return
    const hash = window.location.hash
    const queryIndex = hash.indexOf('?')
    const search = queryIndex >= 0 ? hash.slice(queryIndex) : ''
    const params = new URLSearchParams(search)
    const showIdStr = params.get('showId')
    const showName = params.get('showName')
    if (showIdStr) {
      const showId = Number(showIdStr)
      setInfoFu((v: any) => ({ ...v, showId, ...(showName != null && { showName }) }))
    }
  }, [info.num, setInfoFu])

  return (
    <div className={styles.F3edit} id='editBox'>
      <div className='editMain'>
        {/* 顶部 */}
        <EditTop
          pageTxt='藏品出库'
          rowArr={rowArr}
          APIobj={F3API_obj}
          fileUpInfo={{ myUrl: 'cms/orderSite/out/upload', dirCode: 'outStorage' }}
        />

        <div className='F3editStorage'>
          <p className='F3editStorageTitle'>*出库库房</p>
          <Select
            style={{ width: 200 }}
            options={warehouseOptions}
            placeholder='请选择'
            value={selectStorage?.value}
            onChange={handleStorageChange}
            disabled={!canEdit}
          />
          {selectStorage?.managerUser && (
            <p className='F3editStorageManager'>库房负责人：{selectStorage.managerUser}</p>
          )}
        </div>

        {/* 藏品清单 */}
        <SonGoodsList
          ref={sonGoodsListRef}
          needEdit={true}
          btnTxt='选择藏品'
          addShow={false}
          goodsSonTable={[
            ['txt', '藏品登记号', 'num'],
            ['img', '封面', 'thumb'],
            ['txtCTag', '藏品标签', 'tagDictId'],
            ['txt', '藏品名称', 'name'],
            ['select', '级别', 'level', selectObj['藏品级别']],
            ['txtC', '类别', 'typeDictId'],
            ['txtC', '年代', 'ageDictId'],
            ['txtC', '质地', 'textureDictId'],
            ['select', '完残程度', 'tornLevel', selectObj['完残程度']],
            ['ping', '数量', 'pcs', 'pcsUnitDictId'],
            ['connectTxt', '库房位置', 'storageName', 'siteLoc']
          ]}
          fileUpInfo={{ myUrl: 'cms/orderSite/out/upload', dirCode: 'outStorageGoods' }}
          selectApi={F3_APIgetClueList}
          isClueSelect={false}
          clueShowBtnDisabled={!selectStorage?.value}
          selectGoodsParams={{
            storageId: selectStorage?.value
          }}
        />

        {/* 附件归档 */}
        <FileArchive />

        {/* 底部按钮 */}
        <EditBtn
          path='/outStorage'
          APIobj={F3API_obj}
          checkListTxt='请添加藏品'
          getExtraData={getExtraData}
        />
      </div>
    </div>
  )
}

function F3edit() {
  return (
    <InfoProvider>
      <F3editContent />
    </InfoProvider>
  )
}

const MemoF3edit = React.memo(F3edit)

export default MemoF3edit
