import React from 'react';
import { filter, Renderer, SchemaApi, SchemaApiObject, toast } from '..';
import Action, { ActionProps, ActionRenderer } from './Action';
import { Button, Col, Form, Input, Modal, Row, Space, Spin, Table, message } from 'antd';
import VirtualTable from '../components/VirtualTable';
import Dialog from '../components/DragModal';
import { RendererProps } from '../factory';
import { IColumn } from '../store/table';
import { Schema } from '../types';
import { Shell } from '../utils/shell';
import { createObject, getLagerThanMaxZindex, isMobile } from '../utils/helper';
import { IScopedContext, ScopedContext } from '../Scoped';
import MSG from '../renderers/Lion/utils/msgsub';
import { KeyStepCommonFunction } from '../utils/keyStep';
import { clone, isNil, pick } from 'lodash';
import { resolveVariable, resolveVariableAndFilter } from 'amis-formula';
import { SearchOutlined } from '@ant-design/icons';
import { dataMapping } from '../utils/tpl-builtin';
import { RFIDTrigeerCodeEnum, transportEpcList, windowRFIDTriger } from '../utils/RfidUtil';
import './scss/rfidActionTable.scss'


const testRfidInventogyData = () => {
  return new Array(30000).fill({
    SHELF: 'HC010001', EPC: 'SKU00001AEPC00001', SKU: 'SKU00001', score: 80
  })
}
// RFID单条数据
interface RFIDOBJ {
  epc: string;
  sku: string;
  tid?: string;
  rssi?: number; // 信号强度
  god_id?: string; // 货号
  count?: number // 命中计数
  shelf?: string // 货架号
  score?: number // 得分
  tagCount?: number // 标签总数
  skuCount?: number // sku总数
  shelfCount?: number // 货架数
}

interface RFIDDATABASE {
  EPC: string;
  SKU: string;
  TID?: string;
  RSSI?: number; // 信号强度
  SCORE?: number; // 得分
  SHELF?: string; // 货架号
  GOD_ID?: string; // 货号
  COUNT?: number // 命中计数
  TAGCOUNT?: number // 标签总数
  SKUCOUNT?: number // sku总数
  SHELFCOUNT?: number // 货架数
}

enum InventoryTypeEnum {
  COUNT = 0,
  PROCESS = 1,
  PAUSE = 2,
  END = 3
}
enum RFIDActionEnum {
  SCAN = 'scan', // 盘存
  SEARCH = 'search',  // 找货
  PORT = 'port', // keystep触发
  INVENTORY = 'inventory', // 货架盘存
  SCANSINGLEBLANKTAG = 'scanSingleBlankTag', // 白标扫描
  WRITETAG = 'writeTag' // 目标epc写入
}

// 扳机事件



const TitleMap: any = {
  [RFIDActionEnum.SCAN]: 'RFID扫描',
  [RFIDActionEnum.SEARCH]: 'RFID找货',
  [RFIDActionEnum.INVENTORY]: 'RFID货架盘存',
  [RFIDActionEnum.PORT]: '重试写入',
}





const defaultProPertyForm = {
  "type": "property",
  "items": [] as any
}


export enum SearchInventoryType {
  EPC = 0,
  SKU = 1
}


interface RfidColumn extends IColumn {
  width?: string;
  key: string;
  updateQuery?: string; // 单行的更新模式 也是留口子
  acceptQuery?: string; // 是否弃用数据 也是留口子
  [key: string]: any; // 是否弃用数据 也是留口子
}
// 参考表格设计
interface RfidScanerProps extends RendererProps {
  cloumns: RfidColumn[]
  searchMode: SearchInventoryType  // 指定搜索模式
  searchKey: string // 父级作用域传下来的值
}

interface RfidScanerState {
  formHigh: number;// 表格高
  modalVisable: boolean; // 弹窗是否展示
  modalHide: boolean; // 是否隐藏
  onInfrared: boolean; // 是否红外扫码中
  onScan: boolean; // 是否在扫描
  currentShelf: string; // 当前货架号
  inventoryCount: {}; // RFID存放数组
  curInputshelf?: string; // 暂存的货架号
  RfidList: RFIDDATABASE[]; // RFID存放数组-最终提交数组
  RfidIndexMap?: any; // 索引 方便更新用的
  StaticList?: RFIDDATABASE[]; // 汇总数组
  StaticIndexMap?: any; // 汇总索引方便更新用的
}


class RfidScaner extends React.Component<RendererProps & RfidScanerProps & {
  onAction: (
    e: React.MouseEvent<any> | void | null,
    action: object,
    data: any
  ) => void
}, RfidScanerState> {

  appShell: any = window['AppShell'];

  staticColumnsKey = [
    { key: 'TID', name: 'TID', label: 'tid' },
    { key: 'EPC', name: 'EPC', label: 'epc码', width: 180 },
    { key: 'STATUS', name: 'STATUS', label: '状态', width: 80 },
    { key: 'GOD_ID', name: 'GOD_ID', label: '货号', width: 120 },
    { key: 'SKU', name: 'SKU', label: 'sku码', width: 100 },
    { key: 'COUNT', name: 'COUNT', label: '命中数', width: 80 },
    { key: 'TAGCOUNT', name: 'TAGCOUNT', label: '个数' },
    { key: 'SHELF', name: 'SHELF', label: '货架号', width: 150 },
    { key: 'SCORE', name: 'SCORE', label: '得分', width: 60 },
    { key: 'SKUCOUNT', name: 'SKUCOUNT', label: '扫描量', width: 100 },
    { key: 'RSSI', name: 'RSSI', label: '信号强度', type: 'progress', width: 100 },
    { key: 'BRANCHNO', name: 'BRANCHNO', label: '分部号', width: 100 }
  ]

  //  扫货中的columns比较特殊
  inventoryScanColumns = this.staticColumnsKey.filter(_ => ['EPC', 'SKU', 'TAGCOUNT'].includes(_.key))

  state = {
    formHigh: 0,
    modalVisable: false,
    modalHide: false,
    onScan: false,
    currentShelf: '',
    inventoryCount: {} as any,
    onInfrared: false, // 在红外扫码
    RfidList: [] as RFIDDATABASE[],// 存放Rfid刷新列表的数组
    StaticList: [] as RFIDDATABASE[],// 存放汇总刷新列表的数组
    RfidIndexMap: {} as any, // 存放对应Rfid所在行的索引映射表 epc码作为索引
    StaticIndexMap: {} as any, // 存放对应汇总所在行的索引映射表 配置主键 作为索引
    curInputshelf: '',
  }
  // 更新主键
  primaryFiled: string
  // 默认数据源
  defaultDataSource: any[]
  // 工作模式
  workMode: RFIDActionEnum
  // 携带字段
  workParam: { [key: string]: any }
  propertyDisplayPanel: any
  // 盘存开始扫码的状态
  hasStartINVENTORY = false
  rfidWorkModeMap: any = {
    [RFIDActionEnum.SCAN]: {
      start: (scanFn: any, successFn: any, data: any, fail: any) => Shell.startRFIDScan(data, scanFn, successFn, fail),
      end: () => Shell.UHFStopScan(),
    },
    [RFIDActionEnum.SEARCH]: {
      start: (scanFn: any, successFn: any, searchData: any, fail: any) => {
        if (searchData.sku) {
          return Shell.UHFStartSearchForSKU(scanFn, successFn, searchData, fail)
        } else if (searchData.epcList) {
          return Shell.UHFStartSearchForEPC(scanFn, successFn, searchData, fail)
        } else {
          return message.warn('非法参数，未找到对应的RFID执行方法')
        }
      },
      end: () => Shell.UHFStopSearch(),
    },
    [RFIDActionEnum.INVENTORY]: { // 盘存
      start: (scanFn: any, successFn: any, searchData?: any, fail?: any) => {
        // 暂时根据data里面给了啥来做区分 后期改模式切换
        let data = searchData
        this.hasStartINVENTORY = true
        if (searchData.shelf) {
          if (searchData?.branchNo) {
            return Shell.UHFStartInventoryForBranch(data, successFn, scanFn, fail)
          } else if (searchData?.epcList) {
            return Shell.UHFStartInventoryForEPC(data, successFn, scanFn, fail)
          } else {
            return Shell.UHFStartInventoryForAll(data, successFn, scanFn, fail)
          }
        } else {
          message.warn('非法参数，未找到对应的RFID执行方法')
        }
      },
      end: (endFn: any) => Shell.UHFStopInventory(),
      pause: () => Shell.UHFPauseInventory(),
      resume: (shelf: string) => Shell.UHFResumeInventory(shelf),
      clear: (shelf: string) => Shell.UHFClearInventoryData(shelf), // 根据货架号清空扫到的列表
    },
  }
  fnBack: any //回调标记
  updateInstance: any //回调标记
  defaultSeachValue: { [key: string]: any } // 如果有需要搜索对应的值
  showColumns: RfidColumn[] = []
  updateQueryMap: any = {} // 存放更新逻辑的部分 省的每次去找
  acceptQueryMap: any = {} // 存放更新逻辑的部分 省的每次去找

  // 通过红外获取货架号
  getshelf = (time = 10) => new Promise((res, rej) => {
    this.setState({ onInfrared: true, curInputshelf: '' }, () => {
      const result = Shell.UHFStartInfrared(time * 1000, (result: any) => {
        this.setState({ onInfrared: false })
        // console.log('shelf', JSON.stringify(result))
        res(result?.data?.content)
      })
      if (!result) this.setState({ onInfrared: false })
    })
  })

  reloadTarget(target: string, data: any) {
    const scoped = this.context as IScopedContext;
    scoped.reload(target, data);
  }


  startSetTime = 0
  lastData = {}
  lastDataSetTimer: any
  // 节流 最后一次之前都当作节流 最后一次进入再提交一次
  setInventoryCount(data: any) {
    // 每次进来先清除上一次最后设置的定时器
    clearTimeout(this.lastDataSetTimer)
    // 记录当前数据 当数据不再进入以后认为是最后一次的数据
    this.lastData = data

    // 此定时器是当数据再250ms内不再进入的情况下能够设置最后一次页面上的数据做的定时器 防止250ms内到结束的时候数据有缺失
    this.lastDataSetTimer = setTimeout(() => {
      this.setState({ inventoryCount: this.lastData })
    }, 16 * 16.6)

    // 上一次设置和这次的间隔超过 12 帧ms才放行 
    if (performance.now() - this.startSetTime < 12 * 16.6) return

    this.setState({ inventoryCount: data }, () => {
      // 保证ui更新了以后再设置 减少卡顿
      this.startSetTime = performance.now()
    })
  }


  dealScanCodeList = (_data: any, ScanCodes?: RFIDDATABASE[]) => {

    const { reload, valueAttr, confirmApi, env, api } = this.props;

    const data = { [valueAttr || 'items']: ScanCodes, ..._data }

    const dealCode = async () => {
      // 移除默认值
      const ctx: any = (ScanCodes || _data) ? createObject(this.props.data, data) : this.props.data
      // const ctx = createObject(this.props.data, { items: [{ EPC: '38739204B0100000001' }], ids: '38739204B0100000001' })
      // keyStep操作
      this.setState({ modalVisable: false, RfidList: [], RfidIndexMap: {} as RFIDOBJ, onInfrared: false, onScan: true })
      if (api) {
        const payload = await env.fetcher({ url: (location.href.includes('127.0.0.1') ? 'https://bwt.sanfu.com/saas/' : '') + api.url, method: api.method || 'post', data: api.data }, ctx)
        // const payload = await env.fetcher({ url: (location.protocol === 'http:' ? 'https://bwt.sanfu.com/saas' : '') + api.url, method: api.method || 'post', data: api.data }, ctx)
        if (payload.ok && payload.status == 20003) {
          await KeyStepCommonFunction(payload.data.scanAfterDo, data, env, this.props, this.writeErrorCallBack)
          payload.msg && message.success(payload.msg)
        }
      }
      reload && this.reloadTarget(reload, ctx);
      this.setState({ onScan: false })
    }
    if (confirmApi) {
      this.confirmAction(data, () => { dealCode() })
    } else {
      dealCode()
    }
  }


  closeScanModal = () => {
    this.setState({ modalVisable: false, onScan: false, onInfrared: false })
  }

  confirmAction = async (data: any, conFirmDo: () => any) => {
    const { confirmApi, env } = this.props
    try {
      const confirmMsg = confirmApi && await env.fetcher(confirmApi, data).catch((ref) => {
        toast.error(ref.message);
        return { data: ref, status: 500 }
      })

      if (confirmMsg?.status === 10004 || confirmMsg?.status === 10001 || confirmMsg?.status === 1) {
        env.notify('warning', confirmMsg?.msg)
        return this.closeScanModal()
      } else if (confirmMsg?.status === 500) {
        return this.closeScanModal()
      } else if (confirmMsg?.status === 10003) {
        env?.confirm(filter(confirmMsg?.data?.showText, data)).then((confirmd: boolean) => {
          if (confirmd) {
            conFirmDo()
          } else {
            this.closeScanModal()
          }
          return
        })
        return
      } else if (confirmMsg?.status === 10005) {
        env?.confirm(confirmMsg).then((confirmd: boolean) => {
          if (confirmd) {
            conFirmDo()
          } else {
            this.closeScanModal()
          }
        })
        return
      } else {
        conFirmDo()
      }
    }
    catch (ref) {
      toast.error(ref.message);
      return
    }
  }

  // 存放空实现的暂存量 方便直接调用
  writeErrorDealCode: any = undefined
  isLastStep: boolean = false
  modifyError: boolean = false
  // 写入失败的回调 方便直接展示用的
  writeErrorCallBack = (restScanDo: any[], data: any, env: any, errorData: any) => {
    this.modifyError = true
    // 先注册写入错误回调 方便下次使用
    this.writeErrorDealCode = async (skip: boolean) => {
      this.modifyError = false
      this.setState({ modalVisable: false })
      if (skip && restScanDo[0].afterApi) {
        // 取afterapi并执行
        const payload = await env.fetcher(restScanDo[0].afterApi, data)
        if (payload?.ok && payload?.status == 20003) {
          // 跳过的话跳过当前的Scando
          return KeyStepCommonFunction(payload.data.scanAfterDo, data, env, this.props, this.writeErrorCallBack)
        } else {
          return payload.msg && message.warn(payload.msg)
        }
      } else {
        return KeyStepCommonFunction(restScanDo, data, env, this.props, this.writeErrorCallBack)
      }

    }
    this.isLastStep = !!restScanDo[0].afterApi
    // 展示列固定
    this.showColumns = this.staticColumnsKey.filter(_ => ['GOD_ID', 'SKU', 'EPC'].includes(_.key)) as any[]

    this.setRfidList(transportEpcList(errorData), () => {
      // 打开弹窗
      this.setState({ modalVisable: true, onScan: true })
    })

  }

  componentDidMount(): void {
    const { columns, rfidParam, data, triggerMode } = this.props
    // 如果有触发模式 注册
    if (triggerMode) {
      windowRFIDTriger.addEventListener(triggerMode, this.handleAction)
    }
    // 初始化工作模式和字段
    this.workMode = rfidParam?.cmd
    this.workParam = dataMapping(rfidParam?.param, this.props.data) || {}
    // console.log(this.workParam)
    // 如果已经有scanList数组 先推一部分进去 不过这个要从哪里来还真没想到
    // 数据源设置

    // 主键设置
    this.primaryFiled = (rfidParam.primaryField as string)?.toLocaleUpperCase()

    this.propertyDisplayPanel = this.props.body
    // this.propertyDisplayPanel = this.props.body || (() => {
    //   const workParamLength = Object.keys(this.workParam)
    //   if (this.workMode === RFIDActionEnum.INVENTORY) {
    //     workParamLength.push('shelf')
    //   }
    //   if (!workParamLength.length) return undefined
    //   const _defaultProPertyForm = { ...defaultProPertyForm }
    //   _defaultProPertyForm.items = Object.keys(this.workParam).map(key => {
    //     // console.log(this.props.data, key, dataMapping({ test: `\${${key.toUpperCase()}}` }, this.props.data))
    //     return {
    //       "label": this.staticColumnsKey.find(_ => _.key === key.toUpperCase())?.label || key,
    //       "content": {
    //         type: "tpl",
    //         tpl: `\${${key.toUpperCase()}}`
    //       }
    //     }
    //   })
    //   return _defaultProPertyForm
    // })()
  }

  componentDidUpdate(prevProps: any, prevState: Readonly<{
    modalVisable: boolean,
  }>, snapshot?: any): void {
    if (this.state.modalVisable && !prevState.modalVisable) {
      // 打开注册按住暂停
      windowRFIDTriger.addEventListener(RFIDTrigeerCodeEnum.TRIGGERCLICK, this.scanShelfAndResume)
      windowRFIDTriger.addEventListener(RFIDTrigeerCodeEnum.TRIGGERHOLD, this.pauseScan)
      windowRFIDTriger.onRfidAct = true
    } else if (!this.state.modalVisable && prevState.modalVisable) {
      //关闭同时移除
      this.modifyError = false
      windowRFIDTriger.onRfidAct = false
      // 移除扫描状态
      this.hasStartINVENTORY = false
      // 保证执行关闭动作的时候扫描状态是false
      this.setState({ onInfrared: false, onScan: false, currentShelf: '', curInputshelf: '' })
      windowRFIDTriger.removeEventListener(RFIDTrigeerCodeEnum.TRIGGERCLICK, this.scanShelfAndResume)
      windowRFIDTriger.removeEventListener(RFIDTrigeerCodeEnum.TRIGGERHOLD, this.pauseScan)
      windowRFIDTriger.removeEventListener(RFIDTrigeerCodeEnum.TRIGGERHOLD, this.resumeScan)
      this.rfidWorkModeMap[this.workMode]?.end?.()
    }
  }



  // 开始扫码
  acceptRfid = () => {
    // 货号特殊处理下
    const curShelf = this.workParam?.['shelf']
    // console.log(curShelf, 'curShelf', this.workParam)
    // 如果取得出 暂存货架号
    if (curShelf) {
      this.setState({ currentShelf: curShelf })
    }
    const res = this.rfidWorkModeMap[this.workMode].start((res: any) => {
      switch (this.workMode) {
        // 扫描模式放data.tag里面
        case RFIDActionEnum.SCAN:
        case RFIDActionEnum.SEARCH:
          if (!res?.data?.tag?.epc) return // 移除脏数据
          this.addRfidToList({ ...res.data.tag, skuCount: res.data.skuCount })
          return
        // 盘点模式放data里面
        case RFIDActionEnum.INVENTORY:
          // console.log('res.data：', JSON.stringify(res.data))
          switch (res.data.type as InventoryTypeEnum) {
            // case InventoryTypeEnum.START:
            case InventoryTypeEnum.COUNT:
              // epc用和tag合并出来  tag 给个假的表示每次都是新的
              this.setInventoryCount(res.data)
              break;
            case InventoryTypeEnum.PAUSE:
            case InventoryTypeEnum.END:
              this.setRfidList(res.data.tagList)
              // this.setRfidList(testRfidInventogyData())
              break;
          }
          return
        default:
          break;
      }
    }, (result: any) => { console.log(JSON.stringify('result', result)) }, this.workParam, (res: any) => {
      message.warn(res.msg)
      this.setState({ modalVisable: false, onScan: false, onInfrared: false })
    })

    // 测试代码
    // this.setState({ modalVisable: true, onScan: true, RfidList: new Array(30000).fill(1).map(_ => ({ EPC: new Date().getTime() + '', RSSI: new Date().getTime(), SKU: new Date().getTime() + '' })) })

    if (res) {
      //得有方法才能开弹窗
      this.setState({ modalVisable: true, onScan: true })
    } else {
      this.setState({ onScan: false, onInfrared: false })
    }
  }
  getCurrentInventoryResult = (callback?: any) => {
    Shell.UHFGetInventoryResult((result: any) => {
      // console.log('result', JSON.stringify(result))
      // 回调优化 保证获取以后提交扫货数据
      this.setRfidList(result?.data.tagList, () => {
        callback?.()
      })
      // 移除一下taglist
      result.tagList = []
      this.setState({ inventoryCount: result })
    })
  }
  //停止扫码
  stopAcceptRfid = () => {
    this.setState({ onScan: false }, () => {
      // 调用关闭功能
      this.rfidWorkModeMap[this.workMode]?.end?.()
      // 更新表单用的代码 暂时不需要
    })
  }


  // 设置多条汇总 初始化的时候设置一个汇总表
  setStaticList = (_StaticList: any[], successFn?: () => any) => {
    const StaticIndexMap: any = {}
    _StaticList.map((_, index) => StaticIndexMap[_[this.primaryFiled as any]] = index)
    const StaticList: RFIDDATABASE[] = _StaticList.map((_StaticObj: any, index) => {
      const Static = {} as any
      // 转大写
      Object.keys(_StaticObj).map(key => Static[key.toUpperCase()] = _StaticObj[key])
      return { ...Static, rowIndex: index }
    })
    this.setState({ StaticList: StaticList, StaticIndexMap }, () => successFn?.())
  }

  // 设置多条rifd 针对每次操作都会给我所有数据的情况做的
  // 盘点的时候 暂停，清空，提交的时候都会回调一个厂商处理过的数据
  // 以该数据作为最终要提交的数据
  setRfidList = (_RfidObjList: RFIDOBJ[], successFn?: () => any) => {
    const RfidIndexMap: any = {}
    _RfidObjList.map((_, index) => RfidIndexMap[_.epc] = index)
    const RfidObjList: RFIDDATABASE[] = _RfidObjList.map((_RfidObj: any, index) => {
      const RfidObj = {} as any
      Object.keys(_RfidObj).map(key => RfidObj[key.toUpperCase()] = _RfidObj[key])
      return { ...RfidObj, rowIndex: index }
    })
    this.setState({ RfidList: RfidObjList, RfidIndexMap: { ...RfidIndexMap } }, () => successFn?.())
  }
  isStatic = () => {
    // 有primayFiled也算你要汇总
    return (this.defaultDataSource || this.primaryFiled) && this.workMode === RFIDActionEnum.SCAN
  }
  // 设置单条的RFID数据
  addRfidToList = (_RfidObj: any) => {
    if (!_RfidObj) return
    // console.log('RfidObj', JSON.stringify(_RfidObj))
    if (_RfidObj)
      _RfidObj.god_id = _RfidObj?.sku?.slice(0, 6)
    const RfidObj = {} as any // 转大写后的数据
    // 转大写
    Object.keys(_RfidObj).map(key => RfidObj[key.toUpperCase()] = _RfidObj[key])
    const StaticObj = { ...RfidObj } // 复制一份汇总数据先
    let changeState = {} // 变化量保存

    const RfidList = this.state.RfidList
    const updateQueryKeys = Object.keys(this.updateQueryMap)
    const RfidIndexMap = this.state.RfidIndexMap
    const RfidIndex = RfidIndexMap[RfidObj.EPC] // 记录数据
    const RecordRfid = RfidList[RfidIndex]
    // 防止数组操作慢 有索引导的直接用索引改
    if (RfidObj.EPC && RfidIndex !== undefined) {
      // 原有的记录
      const newRfidObj = { ...RfidObj }
      // 增加命中次数
      RfidList[RfidIndex] = { ...RecordRfid, ...newRfidObj, COUNT: (RecordRfid.COUNT || 0) + 1 }
    }
    else {
      RfidObj['rowIndex'] = RfidList.length
      RfidList.push({ ...RfidObj, COUNT: 1 })
      RfidIndexMap[RfidObj.EPC] = RfidList.length - 1
    }
    // 修改数据
    changeState = { RfidList: [...RfidList], RfidIndexMap: { ...RfidIndexMap } }

    // 如果有默认数据源并且工作模式是扫描 同步跟新汇总数据 -- 单独处理 互不干扰
    if (this.isStatic()) {
      // StaticObj 在最上方定义 
      const StaticList = this.state.StaticList
      const updateQueryKeys = Object.keys(this.updateQueryMap)
      const hasUpdateQuery = !!updateQueryKeys.length
      const StaticIndexMap = this.state.StaticIndexMap
      const RecordIndex = StaticIndexMap[StaticObj[this.primaryFiled]] // 记录数据
      const RecordStatic = StaticList[RecordIndex]
      // 模拟测试数据
      // if (!StaticObj.SKUCOUNT) {
      //   StaticObj.SKUCOUNT = 10
      // }
      // if (!StaticObj.TRAN_AMOUNT) {
      //   StaticObj.TRAN_AMOUNT = 20
      // }
      // 防止数组操作慢 有索引导的直接用索引改

      // 原有的记录
      const newStaticObj = { ...StaticObj }
      // 有更新逻辑的情况 需要按照条目每条都更新
      if (hasUpdateQuery) {
        // {...RecordStatic, ...StaticObj} //更新原来哪条的数据
        const SingleData = { ...RecordStatic, ...StaticObj, pristine: { ...RecordStatic } }
        updateQueryKeys.map(key => {
          // console.log(key, this.updateQueryMap[key], SingleData, resolveVariableAndFilter(this.updateQueryMap[key], SingleData, '| raw'))
          const newValue = resolveVariableAndFilter(this.updateQueryMap[key], SingleData, '| raw')
          newStaticObj[key] = newValue
        })
      }



      if (StaticObj[this.primaryFiled] && RecordIndex !== undefined) {
        // 增加命中次数
        StaticList[RecordIndex] = { ...RecordStatic, ...newStaticObj, COUNT: (RecordStatic.COUNT || 0) + 1 }
      }
      else {
        // 如果没有数据源 走添加逻辑 有的话不能增加额外数据 
        if (!this.defaultDataSource?.length) {
          newStaticObj['rowIndex'] = StaticList.length
          StaticList.push({ ...newStaticObj, COUNT: 1 })
          StaticIndexMap[newStaticObj[this.primaryFiled]] = StaticList.length - 1
        }
      }
      changeState = { ...changeState, StaticList: [...StaticList], StaticIndexMap: { ...StaticIndexMap } }
    }
    this.setState(changeState)
  }

  componentWillUnmount() {
    // 保证销毁了能关闭扫描 防止异常退出
    this.stopAcceptRfid()
    // 处理异常退出的情况
    windowRFIDTriger.onRfidAct = false
    if (this.state.onScan || this.state.onInfrared || this.state.modalVisable) {
      windowRFIDTriger.removeEventListener(this.props.triggerMode, this.handleAction)
      // 取消所有注册
      windowRFIDTriger.removeEventListener(RFIDTrigeerCodeEnum.TRIGGERCLICK, this.scanShelfAndResume)
      windowRFIDTriger.removeEventListener(RFIDTrigeerCodeEnum.TRIGGERHOLD, this.pauseScan)
      windowRFIDTriger.removeEventListener(RFIDTrigeerCodeEnum.TRIGGERHOLD, this.resumeScan)
      // 关闭一下 // 防止异常退出
      this.rfidWorkModeMap[this.workMode]?.end?.()
    }
  }

  // 暂停 清除因为可以输入进行货号传入 所以下一部要定义出来
  nextAction: any

  endScan = (e: any, userConfirm?: boolean) => {
    const { api } = this.props
    this.mutationObserver?.disconnect()

    // 有api才有提交逻辑
    if (userConfirm && api)
      this.dealScanCodeList(e, this.state.RfidList)
    else
      // 清空为初始化逻辑
      this.setState({ modalVisable: false, RfidList: [], RfidIndexMap: {} as RFIDOBJ, onInfrared: false })
  }
  closeScanDilaog = (e: any, userConfirm?: boolean) => {
    // if (this.state.onScan) {
    //   this.stopAcceptRfid()
    // }
    // this.endScan(e, userConfirm)
    switch (this.workMode) {
      case RFIDActionEnum.SCAN:
      case RFIDActionEnum.SEARCH:
        //扫描查找直接关了就行
        if (this.state.onScan) {
          this.stopAcceptRfid()
        }
        this.endScan(e, userConfirm)
        break;
      case RFIDActionEnum.INVENTORY:
        // 扫描中关闭扫码
        if (this.state.onInfrared) {
          Shell.UHFStopInventory()
        }

        const endScan = () => {
          if (this.state.onScan) {
            this.stopAcceptRfid()
          }
          this.endScan(e, userConfirm)
        }

        if (this.state.onScan) {
          // 如果你在扫描中 先暂停
          Shell.UHFPauseInventory(() => {
            // 关闭的时候要特殊调回调
            if (userConfirm) {
              this.getCurrentInventoryResult(endScan)
            } else {
              this.setState({ inventoryCount: {} })
              endScan()
            }
          })
        } else {
          endScan()
        }

        break;
      default:
        this.setState({ modalVisable: false, onScan: false })
        break;
    }

  }

  handleSingleBlankTag = (res: any) => {
    const { valueAttr } = this.props;
    const epc = res?.data?.epc
    if (!epc) return message.warn(res?.msg || '未获取到白标EPC码')
    else {
      message.success('扫描到白标EPC码:' + epc)
      // 改为只有一条的selectItems
      this.dealScanCodeList({ [valueAttr ?? 'EPC']: epc })
    }
  }

  handleAction = async (e: void | React.MouseEvent<any, MouseEvent> | null): Promise<void> => {
    e?.stopPropagation?.()
    if (this.state.modalHide) {
      this.setState({ modalHide: false })
      return
    }
    // console.log('走到这里了',this.props)
    // 如果有其中一种情况说明弹窗已经打开 直接返回不往下走 主要是为了防止按钮触发再走一遍 或者已经开了窗口又用其他按钮触发
    if (this.state.onInfrared || this.state.modalVisable || this.state.onScan || this.props.disabled || this.props.btnDisabled || windowRFIDTriger.onRfidAct) {
      if (this.state.onInfrared || this.state.modalVisable || this.state.onScan)
        return message.warn('自身启用中，请勿重复操作')
      if (this.props.disabled || this.props.btnDisabled)
        return message.warn('按钮禁用中')
      if (windowRFIDTriger.onRfidAct)
        return message.warn('其他按钮占用中,请勿重复重复操作')
      return message.warn('未知问题')
    }

    // 所有columns放入
    this.showColumns = this.props.columns

    if (this.primaryFiled)
      this.defaultDataSource = [] // 数据预源置入 方便清空时候处理下
    if (this.props.source)
      this.defaultDataSource = resolveVariableAndFilter(this.props.source, this.props.data, '| raw')
    // 初始化api
    if (this.props.initApi) {
      const env = this.props.env
      message.loading('获取数据源中', 99 * 1000)
      try {
        const res = await env.fetcher(this.props.initApi, this.props.data)
        message.destroy()
        if (res?.data?.length) {
          message.success('获取成功')
          this.defaultDataSource = res.data
        } else {
          if (!res?.data)
            return message.warn('无对应数据源，请检查')
          if (!res?.data?.length)
            return message.warn('数据源无数据')
        }
      } catch (error) {
        message.destroy()
        message.success('请求数据源失败，请检查接口')
        return
      }
    }

    // 设置一下过滤和更新语句
    this.showColumns?.map(_ => {
      _.width = this.staticColumnsKey.find(col => col.key == _.name)?.width || 120 as any
      _.type = _.type || this.staticColumnsKey.find(col => col.key == _.name)?.type as any
      // 更新字段
      if (_.calculatedExpr)
        this.updateQueryMap[_.name || ''] = _.calculatedExpr
    })

    // 如果有数据源
    if (this.defaultDataSource) {
      // 是数组设置
      if (Array.isArray(this.defaultDataSource)) {
        this.setStaticList(this.defaultDataSource)
      }
      else
        return message.warn('数据源非数组，请配置人员检查')
    }
    // if (this.workMode === RFIDActionEnum.INVENTORY) { 
    //   return  this.dealScanCodeList({},[{EPC:"82663210a0700000022","SCORE":86,SHELF}])
    // }
    // this.setState({ modalVisable: true }); return
    switch (this.workMode) {
      // 盘存 找货 货架盘存全部先开启弹窗
      case RFIDActionEnum.SCAN:
      case RFIDActionEnum.SEARCH:
      case RFIDActionEnum.INVENTORY:
        this.workParam = dataMapping(this.props.rfidParam?.param, this.props.data) || {}
        if (!this.workParam?.shelf && this.workMode === RFIDActionEnum.SEARCH && !this.workParam.epcList && !this.workParam.sku)
          return message.warn('请传入epcList或者sku进行找货')
        if (typeof this.workParam.epcList === 'string') {
          // 字符串转数组 直接做方便点
          this.workParam.epcList = [this.workParam.epcList]
        }
        // 如果param没有货号 并且是盘点模式 每次进去都要扫码
        if (!this.workParam?.shelf && this.workMode === RFIDActionEnum.INVENTORY) {
          const actionAfterScan = (_shelf: string) => {
            if (!_shelf) return message.warn('扫码失败')
            // 设进param
            this.workParam.shelf = _shelf
            this.setState({ currentShelf: _shelf }, () => {
              // 货架盘存需要特殊继续
              // 改为ui渲染完毕以后再进行扫码
              this.acceptRfid()
            })
          }

          this.setState({ modalVisable: true }, async () => {
            this.nextAction = actionAfterScan
            const shelf = await this.getshelf(120) as string
            actionAfterScan(shelf)
          })

          return
        }

        requestAnimationFrame(() => {
          // 改为ui渲染完毕以后再进行扫码
          this.acceptRfid()
        })
        break;
      case RFIDActionEnum.PORT: // 报废
        this.dealScanCodeList(e)
        break;
      case RFIDActionEnum.SCANSINGLEBLANKTAG: // 白标扫码
        windowRFIDTriger.onRfidAct = true
        this.setState({ onScan: true }, () => {
          const res = Shell.UHFScanSingleBlankTag(this.workParam || {}, (res: any) => {
            windowRFIDTriger.onRfidAct = false
            this.setState({ onScan: false })
            message.destroy()
            // console.log('res', JSON.stringify(res))
            this.handleSingleBlankTag(res)
          })
          if (res) {
            // 2s以后保证停止扫描
            setTimeout(() => {
              windowRFIDTriger.onRfidAct = false
            }, 2 * 1000)
            message.loading('扫描白标中', 10 * 1000)
          } else {
            windowRFIDTriger.onRfidAct = false
            this.setState({ onScan: false })
          }
        })
        // this.handleSingleBlankTag({ data: { epc: 'E28011B0A502006B582AD094' } })
        break;
      case RFIDActionEnum.WRITETAG: // 写入
        windowRFIDTriger.onRfidAct = true
        if (this.workParam.tagEpc && this.workParam.writeEpc)
          this.setState({ onScan: true }, () => {
            const res = Shell.UHFWriteTag(this.workParam as { tagEpc: string, writeEpc: string }, (res: any) => {
              windowRFIDTriger.onRfidAct = false
              this.setState({ onScan: false })
              message.destroy()
              if (res?.data?.epc1 && res?.data?.epc2) {
                message.success('写入成功')
                this.dealScanCodeList({})
              } else {
                message.warn(res.msg || `EPC:${this.workParam.tagEpc},写入失败`)
              }
            })
            if (res) {
              // 10s以后保证停止扫描
              setTimeout(() => {
                windowRFIDTriger.onRfidAct = false
              }, 10 * 1000)
              message.loading('白标写入中', 10 * 1000)
            } else {
              windowRFIDTriger.onRfidAct = false
              this.setState({ onScan: false })
            }
          })
        else {
          return message.warn(`缺少${!this.workParam.tagEpc ? '目标EPC' : ''} ${!this.workParam.writeEpc ? '待写入EPC' : ''},请检查`)
        }
        break;
      default:
        message.warn('未适配的cmd')
        break;
    }
  }

  mutationObserver: MutationObserver

  formRef = (ref: any) => {
    const MutationObserver = window.MutationObserver;
    if (this.mutationObserver)
      this.mutationObserver.disconnect()
    this.mutationObserver = new MutationObserver((e) => {
      const formHigh = ref.getBoundingClientRect().height
      if (formHigh !== this.state.formHigh)
        this.setState({ formHigh: ref.getBoundingClientRect().height })
    });
    // 先关闭之前的
    this.mutationObserver.disconnect()
    if (ref) {
      this.setState({ formHigh: ref.getBoundingClientRect().height })
      this.mutationObserver.observe(ref as HTMLElement, {
        attributes: true,
        childList: true,
        subtree: true
      });
    }
  }

  formData: any

  // 扫描货架并继续 目前只有盘点有这个功能
  scanShelfAndResume = async () => {
    // 如果已经开始了或者在扫码中 返回 防止重复触发
    if (this.state.onInfrared || this.state.onScan) {
      return
    }
    switch (this.workMode) {
      case RFIDActionEnum.INVENTORY:
        const actionAfterScan = (_shelf: string) => {
          // 成功了才反转注册
          windowRFIDTriger.removeEventListener(RFIDTrigeerCodeEnum.TRIGGERHOLD, this.resumeScan)
          windowRFIDTriger.addEventListener(RFIDTrigeerCodeEnum.TRIGGERHOLD, this.pauseScan)
          this.setState({ currentShelf: _shelf }, () => {
            // 货架盘存需要特殊继续
            this.rfidWorkModeMap[this.workMode].resume(_shelf)
          })
        }
        this.nextAction = actionAfterScan
        const shelf: string = await this.getshelf(120) as string
        // console.log('shelf', shelf)
        if (shelf) {
          message.success('扫描到货架号' + shelf)
          // 注册下一步
          this.setState({ onScan: true }, async () => {
            actionAfterScan(shelf)
          })
        } else {
          message.warn('未获取到扫码')
        }
        break;
      default:
        break;
    }
  }

  resumeScan = async () => {
    // 如果已经开始了或者在扫码中 返回 防止重复触发
    if (this.state.onInfrared || this.state.onScan) {
      return
    }
    // 反转注册
    windowRFIDTriger.addEventListener(RFIDTrigeerCodeEnum.TRIGGERHOLD, this.pauseScan)
    windowRFIDTriger.removeEventListener(RFIDTrigeerCodeEnum.TRIGGERHOLD, this.resumeScan)
    switch (this.workMode) {
      case RFIDActionEnum.SCAN:
      case RFIDActionEnum.SEARCH:
        // 反转注册
        this.acceptRfid()
        break;
      case RFIDActionEnum.INVENTORY:
        this.setState({ modalVisable: true, onScan: true }, () => {
          this.rfidWorkModeMap[this.workMode].resume(this.state.currentShelf)
        })
        break;
      default:
        break;
    }

  }

  clear = async () => {
    // 如果是盘点要先暂停下
    switch (this.workMode) {
      // 盘存 找货 清空
      case RFIDActionEnum.SCAN:
        const originScanStatus = this.state.onScan
        this.pauseScan()
        const changeState = { RfidList: [], RfidIndexMap: {} }
        if (this.isStatic()) {
          this.setStaticList(this.defaultDataSource, () => {
            this.setState(changeState, () => {
              if (originScanStatus)
                setTimeout(() => {
                  this.acceptRfid()
                }, 250)
            })
          })
        } else {
          this.setState(changeState, () => {
            if (originScanStatus)
              setTimeout(() => {
                this.acceptRfid()
              }, 250)
          })
        }
        break;
      case RFIDActionEnum.SEARCH:
        this.pauseScan()
        this.setState({ RfidList: [], RfidIndexMap: {} }, () => {
          if (this.state.onScan)
            setTimeout(() => {
              this.acceptRfid()
            }, 250)
        })
        break;
      case RFIDActionEnum.INVENTORY:
        this.pauseScan()
        setTimeout(async () => {
          const actionAfterScan = (_shelf: string) => {
            // 货架盘存需要特殊继续
            this.rfidWorkModeMap[this.workMode].clear(_shelf)
            // 清完重新取一下
            this.getCurrentInventoryResult()

          }
          this.nextAction = actionAfterScan
          const shelf = await this.getshelf(120)
          if (shelf) {
            // 货架盘存需要特清空
            message.success(`清空货架号:${shelf}`)
            actionAfterScan(shelf as string)
          } else {
            message.warn('未获取到扫码')
          }
        }, 250)

        break;
      default:
        break;
    }
  }

  pauseScan = () => {
    // 如果已经暂停了或者在扫码中 返回 防止重复触发
    if (this.state.onInfrared || !this.state.onScan) {
      return
    }
    // 暂停以后修改注册
    windowRFIDTriger.removeEventListener(RFIDTrigeerCodeEnum.TRIGGERHOLD, this.pauseScan)
    windowRFIDTriger.addEventListener(RFIDTrigeerCodeEnum.TRIGGERHOLD, this.resumeScan)
    switch (this.workMode) {
      // 盘存 找货 暂停就是停止
      case RFIDActionEnum.SCAN:
      case RFIDActionEnum.SEARCH:
        this.stopAcceptRfid()
        break;
      case RFIDActionEnum.INVENTORY:
        this.setState({ onScan: false }, () => {
          // 货架盘存需要特殊暂停
          this.rfidWorkModeMap[this.workMode].pause()
        })
        break;
      default:
        break;
    }
  }



  searchInput = ({ setSelectedKeys, selectedKeys, confirm, clearFilters, close }: any) => (
    <div style={{ padding: 8 }} onKeyDown={(e) => e.stopPropagation()}>
      <Input
        value={selectedKeys[0]}
        onChange={(e) => setSelectedKeys(e.target.value ? [e.target.value] : [])}
        style={{ marginBottom: 8, display: 'block' }}
      />
      <Space>
        <Button
          type="primary"
          onClick={() => {
            clearFilters()
            confirm('')
            close()
          }}
          size="small"
          style={{ width: 90 }}
        >
          清空
        </Button>
        <Button
          type="primary"
          onClick={() => {
            confirm(selectedKeys[0])
            close()
          }}
          icon={<SearchOutlined />}
          size="small"
          style={{ width: 90 }}
        >
          搜索
        </Button>
      </Space>
    </div>
  )

  modalWidth = isMobile() ? '95vw' : this.props?.cloumns?.length > 3 ? '40vw' : '65vw'


  staticINVENTORYColumnList = [{ name: '已盘货架总数', key: 'shelfCount' }, { name: '已盘sku总数', key: 'skuCount' }, { name: '已盘数量', key: 'tagCount' }]

  renderScanResult = () => {
    // 行高 按钮底部高 
    const tableShowHigh = this.state.formHigh > window.innerHeight * 0.95 ? window.innerHeight * 0.95 : (window.innerHeight * 0.95 - 55 - 38 - 45 - 24 - this.state.formHigh)
    const { render } = this.props
    // 如果有表格渲染逻辑

    let showColumns: any[] = this.showColumns

    // 盘点仅展示汇总值
    if (this.workMode === RFIDActionEnum.INVENTORY) {
      // 扫描过程中的columns调整下
      showColumns = this.inventoryScanColumns
      return <>
        <p style={{ margin: '0.5rem' }}>当前货架号：{this.state.currentShelf}</p>
        <table style={{ marginBottom: '20px', border: '1px solid #afafaf' }}>

          <thead>
            <tr>{this.staticINVENTORYColumnList.map(_ => {
              return <th style={{ textAlign: 'center', fontWeight: 'normal', border: '1px solid #afafaf', backgroundColor: '#efefef', fontSize: '16px' }}>{_.name}</th>
            })}</tr>
          </thead>
          <tbody>
            <tr>
              {this.staticINVENTORYColumnList.map(_ => {
                return <td style={{ border: '1px solid #afafaf', textAlign: 'center', fontSize: '16px' }}>{this.state.inventoryCount[_.key] || 0}</td>
              })}
            </tr>
          </tbody>
        </table>
      </>
    }

    // 展示字段 - 默认加一个序号进去
    const columns: any[] = [{
      title: "序号",
      dataIndex: 'rowIndex',
      key: 'rowIndex',
      width: 65,
      fixed: 'center',
      align: 'center',
      showSorterTooltip: false,
      sorter: (cur: any, next: any) => cur['rowIndex'] - next['rowIndex'],
      sortDirections: ['descend', 'ascend'],
      render: (_: any, record: any, index: number) => {
        return <div style={{ textAlign: 'center' }}>{`${_ + 1}`}</div>
      },
    }, ...showColumns.map((_, colIndex) => {
      // console.log(_)
      return {
        title: _.label,
        key: _.name,
        label: _.label,
        name: _.label,
        dataIndex: _.name,
        width: _.width,
        render: (value: any, record: any, index: any) => {
          const columnInfo = showColumns[colIndex]
          // 有type按照type渲染
          if (columnInfo.type) {
            // 如果是进度特殊处理下
            if (columnInfo.type === 'progress' && columnInfo.name === 'RSSI') {
              value = (value / 7) * 100
            }
            return render(`scanRfid/list/${index}/${colIndex}`, columnInfo, { value: value })
          }
          return value
        }
      }
    })]

    let dataSource = this.state.RfidList
    // 如果有默认数据源并且工作模式是扫描 切换视图
    let extraList = <></>
    const showHigh = tableShowHigh
    // const showHigh = this.isStatic() && !isMobile() ? ((tableShowHigh / 2) - 50) : tableShowHigh
    if (this.isStatic()) {
      dataSource = this.state.StaticList

      // const extraColumns = [{
      //   title: "序号",
      //   dataIndex: 'rowIndex',
      //   key: 'rowIndex',
      //   width: 65,
      //   fixed: 'center',
      //   align: 'center',
      //   showSorterTooltip: false,
      //   sorter: (cur: any, next: any) => cur['rowIndex'] - next['rowIndex'],
      //   sortDirections: ['descend', 'ascend'],
      //   render: (_: any, record: any, index: number) => {
      //     return <div style={{ textAlign: 'center' }}>{`${_ + 1}`}</div>
      //   },
      // }, ...this.staticColumnsKey.filter(_ => ['GOD_ID', 'SKU', 'EPC'].includes(_.key)).map((_, colIndex) => {
      //   // console.log(_)
      //   return {
      //     title: _.label,
      //     key: _.name,
      //     label: _.label,
      //     name: _.label,
      //     dataIndex: _.name,
      //     width: _.width,
      //     render: (value: any, record: any, index: any) => {
      //       return value
      //     }
      //   }
      // })]
      // extraList = <>
      //   <div style={{ borderTop: '1px solid #f0f0f0', marginBottom: '20px' }}></div>
      //   <VirtualTable dataSource={this.state.RfidList}
      //     onOneScreen={false}
      //     scroll={{ y: showHigh, x: this.modalWidth }} columns={extraColumns} tempList={['tid', 'epc', 'sku', 'count', 'rssi']}>
      //   </VirtualTable>
      // </>
    }
    return <>
      <VirtualTable dataSource={dataSource}
        rowKey={this.primaryFiled}
        key={this.primaryFiled}
        onOneScreen={false}
        scroll={{ y: showHigh, x: this.modalWidth }} columns={columns} tempList={['tid', 'epc', 'sku', 'count', 'rssi']}>
      </VirtualTable>
    </>

  }

  render() {
    const { env, api, disabled, btnDisabled, loading, render, body, title, ...rest } = this.props;

    // 计算标题
    let displayTitle
    if (this.state.modalVisable)
      displayTitle = title ? resolveVariableAndFilter(title, createObject(this.props.data, { SHELF: this.state.currentShelf || this.workParam.SHELF })) : `${TitleMap[this.workMode]}中`
    const ModalProps = {
      ...isMobile() ?
        {} :
        {
          minHeight: window.innerHeight * 0.95,
          // onHide: () => { this.setState({ modalHide: true }) },
          // hide: this.state.modalHide
        },
      title: !this.modifyError ? displayTitle : '重试中',
      modalRender: (children: any) => {
        return <div className='rfid-warp' onClick={(e) => {
          e.stopPropagation()
        }}>{children}</div>
      },
      zIndex: getLagerThanMaxZindex(), bodyStyle: { padding: '4px 4px 0', display: 'flex', flexDirection: 'column', overflow: 'auto', maxHeight: '80vh' },
      width: this.modalWidth, onCancel: this.closeScanDilaog,
      closable: true,
      footer: < div style={{ display: 'flex', justifyContent: 'center', width: '100%', overflow: 'visible' }
      }>
        {
          this.modifyError ? <>
            {!this.isLastStep ? <Button type='primary' onClick={() => this.writeErrorDealCode(true)}>跳过并继续</Button> : null}
            <Button type='primary' onClick={() => this.writeErrorDealCode()}>重试写入</Button></>
            :
            <>
              {(this.workMode === RFIDActionEnum.INVENTORY && !this.state.onScan) ? <Button type='primary' onClick={this.scanShelfAndResume}>扫描货架</Button> : null}
              {this.state.onScan ?
                <Button type='primary' onClick={this.pauseScan}>暂停</Button> :
                <Button type='primary' onClick={this.resumeScan}>继续</Button>}

              {this.workMode === RFIDActionEnum.SEARCH ? '' : <>
                {api ? <Button type='primary' onClick={(e) => this.closeScanDilaog(e, true)}>{`${this.state.onScan ? '停止并' : ''}提交`}</Button> : <Button type='primary' onClick={(e) => this.closeScanDilaog(e, true)}>{`${this.state.onScan ? '停止并' : ''}关闭`}</Button>}
                <Button type='primary' onClick={this.clear}>清空{this.workMode === RFIDActionEnum.INVENTORY ? '货架' : ''}</Button>
              </>}</>
        }
      </div >,
      getContainer: env.getModalContainer,
      dialogVisible: this.state.modalVisable,
      open: this.state.modalVisable,
      centered: true,
      destroyOnClose: true
    } as any
    const modalContent = this.state.modalVisable ?
      <>
        {this.state.onInfrared ? <div
          style={{
            position: 'absolute',
            zIndex: 2,
            display: 'flex',
            width: 'calc(100% - 8px)',
            height: 'calc(100% - 60px)',
            background: 'rgba(255, 255, 255, 0.5)',
            backdropFilter: 'blur(5px)',
            flexDirection: 'column',
            justifyContent: 'center',
            alignItems: 'center'
          }}
        >
          <Space align='center' direction="vertical">
            <span style={{ fontWeight: 'bold' }}> 红外扫码中  <Spin size="small" /></span>
            <Space size={0}> <Input onChange={(e) => {
              this.setState({ curInputshelf: e.target.value })
            }} placeholder='输入8位货架号' minLength={8} maxLength={8}  ></Input><Button onClick={(e) => {
              this.setState({
                onInfrared: false,
                onScan: true
              }, () => {
                this.nextAction(this.state.curInputshelf)
              })
            }} disabled={this.state.curInputshelf.length !== 8} type='primary'>确定</Button></Space>
            <Button type='primary' onClick={() => {
              this.setState({ onInfrared: false }, () => {
                if (!this.hasStartINVENTORY) {
                  this.setState({ modalVisable: false })
                }
              })
              Shell.UHFStopInfrared()
            }}>停止扫码</Button>
          </Space>
        </div> : null}
        {(this.propertyDisplayPanel) ? <div style={{ padding: '12px 0 8px' }} ref={this.formRef}>{render('rfid/form', this.propertyDisplayPanel, { ...this.props, data: createObject(this.props.data, { SHELF: this.state.currentShelf }) })}
        </div> : null}
        {this.renderScanResult()}
      </> : null
    return <>
      {this.state.modalVisable ?
        <>{isMobile() ?
          <Modal maskClosable={false} {...ModalProps}>{modalContent}</Modal> :
          <Dialog maskClosable={false} {...ModalProps}>
            {modalContent}
          </Dialog >
        }</>
        : null
      }
      <Action   {...(rest as any)}
        env={env}
        disabled={disabled || btnDisabled || this.state.onScan || this.state.onInfrared || this.state.modalVisable}
        onAction={this.handleAction}
        loading={loading || this.state.modalHide}
        tooltipContainer={
          env?.getTopModalContainer || undefined
        }></Action>
    </>
  }
}

@Renderer({
  type: 'rfid-action'
})
export class RfidScanerRenderer extends RfidScaner {
  static contextType = ScopedContext;
  constructor(props: RfidScanerProps, context: IScopedContext) {
    super(props as any);
    const scoped = context;
    scoped.registerComponent(this);
  }

  componentWillUnmount(): void {
    super.componentWillUnmount()
    const scoped = this.context as IScopedContext;
    scoped.unRegisterComponent(this)
  }

  reloadTarget(target: string, data: any) {
    const scoped = this.context as IScopedContext;
    scoped.reload(target, data);
  }
}