import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useHistory, 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_APIgetStorageList, F1API_obj } from '@/store/action/Fstorehouse/F1inStorage'
import { Button, Dropdown, Select } from 'antd'
import { selectObj } from '@/utils/dataChange'
import FileArchive from '@/pages/Zother/FileArchive'
import {
  F4_APIgetClueList,
  F4_APIgetRelatedOrderList,
  F4API_obj
} from '@/store/action/Fstorehouse/F4check'
import { NewPcsCell, PdRemarkCell, PdRemarkModal } from './components'
import MyTable from '@/components/MyTable'
import { GoodsType } from '@/pages/Zother/SonGoodsList/data'
import { openLink } from '@/utils/history'

const rowArr = rowArrTemp('盘点')
const registerMenu = [
  {
    key: 'accident',
    label: '事故登记',
    type: 'SG'
  },
  {
    key: 'actuality',
    label: '现状登记',
    type: 'XZ'
  },
  {
    key: 'repair',
    label: '修复登记',
    type: 'XF'
  }
]

function F1editContent() {
  const history = useHistory()
  const { info, setSnapsFu } = useInfo() as { info: any; setSnapsFu: (snaps: any[]) => void }
  const { key } = useParams<any>()
  const canEdit = useMemo(() => ['1', '2'].includes(key), [key])
  const isLook = useMemo(() => ['4'].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 [remarkModal, setRemarkModal] = useState<{
    open: boolean
    item: any
    value: string
    onChange: (v: string) => void
  } | null>(null)
  const [relatedOrderList, setRelatedOrderList] = useState<any[]>([])

  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 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) => typeof values[`${snap.id}-newPcs`] !== 'number'
    )
    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
      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,
          newPcs: values[`${v.id}-newPcs`] ?? v.newPcs,
          pdRemark: values[`${v.id}-pdRemark`] ?? v.pdRemark
        })
      }
    })
    return {
      storageId: selectStorage?.value ?? undefined,
      snaps: snapsArr
    }
  }

  const customTableLastBtn = (item: GoodsType) => {
    return info.status === 4 ? (
      <Dropdown
        menu={{
          items: registerMenu,
          style: { width: 100 },
          onClick: ({ key }) => {
            history.push(`/${key}_edit/1/null?pNum=${`${info.num},${item.id}`}`)
          }
        }}
        placement='bottom'
      >
        <Button size='small' type='text'>
          盘点登记
        </Button>
      </Dropdown>
    ) : null
  }

  useEffect(() => {
    if (!isLook || !info.num) return
    F4_APIgetRelatedOrderList(info.num).then((res: any) => {
      if (res.code === 0) {
        setRelatedOrderList(res.data)
      }
    })
  }, [info.num, isLook])

  return (
    <div className={styles.F4edit} id='editBox'>
      <div className='editMain'>
        {/* 顶部 */}
        <EditTop
          pageTxt='藏品盘点'
          rowArr={rowArr}
          APIobj={F1API_obj}
          fileUpInfo={{ myUrl: 'cms/orderSite/check/upload', dirCode: 'check' }}
        />

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

        {/* 藏品清单 */}
        <SonGoodsList
          ref={sonGoodsListRef}
          label={canEdit ? '盘点计划' : '盘点结果'}
          needEdit={true}
          btnTxt='选择藏品'
          addShow={false}
          goodsSonTable={[
            ['connectTxt', '库房位置', 'storageName', 'siteLoc'],
            ['txt', '藏品登记号', 'num'],
            ['img', '封面', 'thumb'],
            ['txtCTag', '藏品标签', 'tagDictId'],
            ['txt', '藏品名称', 'name'],
            ['select', '级别', 'level', selectObj['藏品级别']],
            ['txtC', '类别', 'typeDictId'],
            ['txtC', '年代', 'ageDictId'],
            ['txtC', '质地', 'textureDictId'],
            ['select', '完残程度', 'tornLevel', selectObj['完残程度']],
            ['ping', '盘点前数量', 'pcs', 'pcsUnitDictId'],
            [
              'custom',
              '*盘点后数量',
              'newPcs',
              {
                render(readOnly?: boolean, item?: any) {
                  return <NewPcsCell item={item} readOnly={!!readOnly} />
                }
              }
            ],
            [
              'custom',
              '盘点备注',
              'pdRemark',
              {
                render(readOnly?: boolean, item?: any) {
                  return (
                    <PdRemarkCell
                      item={item}
                      readOnly={!!readOnly}
                      onOpen={(val, onChange) => {
                        setRemarkModal({
                          open: true,
                          item,
                          value: val,
                          onChange
                        })
                      }}
                    />
                  )
                }
              }
            ]
          ]}
          fileUpInfo={{ myUrl: 'cms/orderSite/check/upload', dirCode: 'checkGoods' }}
          selectApi={F4_APIgetClueList}
          isClueSelect={false}
          clueShowBtnDisabled={!selectStorage?.value}
          selectGoodsParams={{
            storageId: selectStorage?.value
          }}
          tableLastWidth={150}
          customTableLastBtn={customTableLastBtn}
        />

        <div
          className='F4editStorage'
          style={{ flexDirection: 'column', alignItems: 'flex-start' }}
        >
          <p className='F4editStorageTitle'>盘点登记</p>
          <MyTable
            classKey='SonGoodsList'
            list={relatedOrderList}
            columnsTemp={[
              ['select', '业务类型', 'type', selectObj['维护类型']],
              ['txt', '申请编号', 'num'],
              ['txt', '发起部门', 'deptName'],
              ['txt', '发起人', 'creatorName'],
              ['txt', '发起日期', 'date'],
              ['select', '申请状态', 'status', selectObj['藏品入库申请状态']]
            ]}
            lastBtn={[
              {
                title: '操作',
                render: (item: any) => {
                  return (
                    <Button
                      size='small'
                      type='text'
                      onClick={() =>
                        openLink(
                          `/${registerMenu.find(v => v.type === item.type)?.key}_edit/4/${item.id}?pNum=${`${item.num},${item.id}`}`
                        )
                      }
                    >
                      查看
                    </Button>
                  )
                }
              }
            ]}
            pagingInfo={false}
          />
        </div>

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

        {/* 盘点备注弹窗 */}
        <PdRemarkModal
          readOnly={!canEdit}
          open={!!remarkModal}
          value={remarkModal?.value ?? ''}
          onOk={val => {
            remarkModal?.onChange(val)
            setRemarkModal(null)
          }}
          onCancel={() => setRemarkModal(null)}
        />

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

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

const MemoF1edit = React.memo(F1edit)

export default MemoF1edit
