import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Input, Tree, TreeDataNode } from 'antd'
import D1Loc from './D1Loc'
import D1goods from './D1goods'
import { filterTreeByName } from '@/utils/history'
import { TypeZ1dict } from '@/pages/Z_system/Z1dict/type'
import { D1_APIgetTree } from '@/store/action/D1storage'

type TypeTopBtn = '按库位查看' | '按藏品查看'

const topBtnArr: TypeTopBtn[] = ['按库位查看', '按藏品查看']

function D1storage() {
  const [topAc, setTopAc] = useState<TypeTopBtn>('按库位查看')

  // 库位传递参数给藏品
  const lookData = useRef<string[]>([])

  // 有关树------
  const [loding, setLoding] = useState(false)

  const [dictList, setDictList] = useState<TypeZ1dict[]>([])

  const getTreeFu = useCallback(async () => {
    const res = await D1_APIgetTree()
    if (res.code === 0) {
      setDictList(res.data)
      setLoding(true)
      if (res.data && res.data.length) setAcShu(res.data[0].id)
    }
  }, [])

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

  // 当前选中的树节点ID
  const [acShu, setAcShu] = useState(0)

  // 点击树节点
  const onSelect = (id: any) => {
    // console.log('点击树节点', id)
    if (id[0]) setAcShu(id[0])
  }

  const [value, setValue] = useState('')
  const [value2, setValue2] = useState('')

  const timeRef = useRef(-1)
  const valueChange = useCallback((val: string) => {
    setValue(val.trim())
    clearTimeout(timeRef.current)
    timeRef.current = window.setTimeout(() => {
      setValue2(val.trim())
    }, 500)
  }, [])

  // value变化的时候获取所有dom 设置隐藏
  const treeDataTemp = useMemo(() => {
    if (value2) {
      return filterTreeByName(dictList, value2)
    } else return dictList
  }, [dictList, value2])

  // 搜索高亮
  const treeData = useMemo(() => {
    const loop = (dataTemp: any[]): TreeDataNode[] => {
      const data = dataTemp || []

      return data.map(item => {
        const strTitle = ((item.num ? item.num + ' - ' : '') + item.name) as string

        const index = strTitle.indexOf(value)

        const beforeStr = strTitle.substring(0, index)
        const afterStr = strTitle.slice(index + value.length)
        const title =
          index > -1 ? (
            <span key={item.id}>
              {beforeStr}
              <span className='site-tree-search-value'>{value}</span>
              {afterStr}
            </span>
          ) : (
            <span key={item.id} className='hiddenTree'>
              {strTitle}
            </span>
          )
        if (item.children) {
          return { title, key: item.id, children: loop(item.children) }
        }
        return {
          title,
          key: item.id
        }
      })
    }

    return loop(treeDataTemp)
  }, [treeDataTemp, value])

  // 数列表
  const TreeDom = useMemo(() => {
    return (
      <div className='D1Lmainll'>
        <div className='D1Lmainll1'>
          <Input
            style={{ width: 300 }}
            placeholder='请输入需要搜索仓库或区域名称'
            maxLength={30}
            value={value}
            onChange={e => valueChange(e.target.value)}
          />
        </div>

        {treeDataTemp && treeDataTemp.length ? (
          <div className='D1Lmainll2'>
            <Tree
              // 默认全部展开
              defaultExpandAll={true}
              // 数据
              treeData={treeData}
              // 自定义字段
              // fieldNames={{ title: 'name', key: 'id', children: 'children' }}
              // 选中
              selectedKeys={[acShu]}
              // 点击
              onSelect={onSelect}
            />
          </div>
        ) : null}

        {loding && treeDataTemp.length === 0 ? <div className='D1null'>暂无数据</div> : null}
      </div>
    )
  }, [])

  return (
    <div className={styles.D1storage}>
      <div className='pageTitle'>分库管理</div>
      <div className='D1top'>
        <span className='D1topllTxt'>仓库列表</span>
        {topBtnArr.map(v => (
          <Button
            onClick={() => {
              lookData.current = []
              setTopAc(v)
            }}
            key={v}
            type={topAc === v ? 'primary' : 'default'}
          >
            {v}
          </Button>
        ))}
      </div>
      <div className='D1main'>
        {topAc === '按库位查看' ? (
          <D1Loc
            lookFu={val => {
              lookData.current = val
              setTopAc('按藏品查看')
            }}
          />
        ) : null}
        {topAc === '按藏品查看' ? <D1goods lookData={lookData.current} /> : null}
      </div>
    </div>
  )
}

const MemoD1storage = React.memo(D1storage)

export default MemoD1storage
