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 {
  F1_APIgetClueList,
  F1_APIgetShowList,
  F1_APIgetShelfEmptyList,
  F1_APIgetShelfList,
  F1_APIgetStorageList,
  F1API_obj
} from '@/store/action/Fstorehouse/F1inStorage'
import { Button, Select } from 'antd'
import { selectObj } from '@/utils/dataChange'
import FileArchive from '@/pages/Zother/FileArchive'

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 F1editContent() {
  const { info } = useInfo() as { info: any }
  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 [shelfList, setShelfList] = useState<any[]>([])

  const handleStorageChange = useCallback(async (value: string, option: any) => {
    setSelectStorage(option)
    const res = await F1_APIgetShelfList({ storageId: value })
    setShelfList(
      res.data.map((i: any) => ({
        label: [i.layer1, i.layer2, i.layer3, i.layer4].filter(i => Boolean(i)).join('-'),
        value: i.id
      }))
    )
  }, [])

  const handleAutoAssignShelf = async () => {
    const snaps = sonGoodsListRef.current?.snaps ?? []
    if (!snaps.length) return
    const res = await F1_APIgetShelfEmptyList({
      storageId: selectStorage?.value,
      limit: snaps.length
    })
    const idList: { id: number }[] = Array.isArray(res) ? res : (res?.data ?? [])
    const form = sonGoodsListRef.current?.tableRef?.current?.form
    if (!form) return
    const values: Record<string, number | undefined> = {}
    snaps.forEach((snap: any, i: number) => {
      values[`${snap.id}-siteId`] = idList[i]?.id
    })
    form.setFieldsValue(values)
  }

  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)
      F1_APIgetShelfList({ storageId: info.storageId }).then(res => {
        setShelfList(
          res.data.map((i: any) => ({
            label: [i.layer1, i.layer2, i.layer3, i.layer4].filter(i => Boolean(i)).join('-'),
            value: i.id
          }))
        )
      })
    }
  }, [info?.storageId, allWarehouseList.length, warehouseOptions])

  const verifyBackFu = (info: any) => {
    if (!selectStorage) return { flag: true, txt: '请选择入库库房' }
    const form = sonGoodsListRef.current?.tableRef?.current?.form
    if (!form) return { flag: true, txt: '请添加藏品' }
    const values = form.getFieldsValue()
    const snaps = sonGoodsListRef.current?.snaps ?? []
    const hasEmptyStorage = snaps.some((snap: any) => !values[`${snap.id}-siteId`])
    if (hasEmptyStorage) return { flag: true, txt: '请为藏品选择库房位置' }
    return { flag: false, txt: '' }
  }

  const getExtraData = (info: any, snaps: any[]) => {
    const form = sonGoodsListRef.current?.tableRef?.current?.form
    const values = form?.getFieldsValue() ?? {}
    const snapsArr = snaps.map((v: any) => {
      const flag = v.pageType === 'clue' && !v.clueId
      const siteId = values[`${v.id}-siteId`] ?? null
      const siteLoc = shelfList.find((s: any) => s.value === siteId)?.label ?? null
      return {
        goodId: v.isNew || flag ? null : v.id,
        orderId: info.id,
        storageInId: selectStorage?.value ?? null,
        snap: JSON.stringify({
          ...v,
          id: v.isNew || flag ? null : v.id,
          siteLoc,
          siteId
        })
      }
    })
    return {
      storageId: selectStorage?.value ?? undefined,
      snaps: snapsArr
    }
  }

  return (
    <div className={styles.F1edit} id='editBox'>
      <div className='editMain'>
        {/* 顶部 */}
        <EditTop
          pageTxt='藏品入库'
          rowArr={rowArr}
          APIobj={F1API_obj}
          fileUpInfo={{ myUrl: 'cms/orderSite/in/upload', dirCode: 'inStorage' }}
        />

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

        {/* 藏品清单 */}
        <SonGoodsList
          ref={sonGoodsListRef}
          needEdit={true}
          btnTxt='选择藏品'
          addShow={false}
          customRightBtn={
            <Button
              disabled={!selectStorage?.value || !canEdit}
              type='primary'
              ghost
              onClick={handleAutoAssignShelf}
            >
              自动分配空置位置
            </Button>
          }
          goodsSonTable={[
            ['txt', '藏品登记号', 'num'],
            ['img', '封面', 'thumb'],
            ['txtCTag', '藏品标签', 'tagDictId'],
            ['txt', '藏品名称', 'name'],
            ['select', '级别', 'level', selectObj['藏品级别']],
            ['txtC', '类别', 'typeDictId'],
            ['txtC', '年代', 'ageDictId'],
            ['txtC', '质地', 'textureDictId'],
            ['select', '完残程度', 'tornLevel', selectObj['完残程度']],
            ['ping', '数量', 'pcs', 'pcsUnitDictId'],
            [
              'custom',
              '库房位置',
              'siteId',
              {
                render(_readOnly?: boolean) {
                  return (
                    <Select
                      allowClear
                      options={shelfList}
                      disabled={!canEdit}
                      placeholder='请选择'
                    />
                  )
                }
              }
            ]
          ]}
          fileUpInfo={{ myUrl: 'cms/orderSite/in/upload', dirCode: 'inStorageGoods' }}
          selectApi={F1_APIgetClueList}
          isClueSelect={false}
        />

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

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

function F1edit() {
  return (
    <InfoProvider>
      <F1editContent />
    </InfoProvider>
  )
}

const MemoF1edit = React.memo(F1edit)

export default MemoF1edit
