import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Input, Tree, TreeDataNode } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import { E1_APIdel, E1_APIgetTree } from '@/store/action/Eculture/E1tag'
import { filterTreeByName, treeResIdFu } from '@/pages/Isystem/I2dict/data'
import { I5AddInfoType, TypeI5Tree } from '@/pages/Isystem/I5organization/data'
import classNames from 'classnames'
import E1add from './E1add'

function E1tag() {
  const dispatch = useDispatch()

  const [loding, setLoding] = useState(false)

  const getInfoFu = useCallback(
    (flag: boolean) => {
      dispatch(
        E1_APIgetTree(data => {
          setLoding(true)

          if (flag && data && data.length) setAcShu(data[0].id)
        })
      )
    },
    [dispatch]
  )

  useEffect(() => {
    getInfoFu(true)
  }, [getInfoFu])

  const { treeData: dictAll } = useSelector((state: RootState) => state.E1tag)

  // 点击重置
  const resetFu = useCallback(
    (flag: boolean) => {
      // 重置 flag为true
      // 新增和编辑 为false
      getInfoFu(flag)

      setValue('')
      setValue2('')
    },
    [getInfoFu]
  )

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

  // 点击树节点
  const onSelect = (id: any) => {
    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(dictAll, value2)
    } else return dictAll
  }, [dictAll, 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 strTitleD = strTitle.toUpperCase()

        const valueD = value.toUpperCase()
        const index = strTitleD.indexOf(valueD)

        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}>{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 rightData = useMemo(() => {
    let obj = {} as TypeI5Tree

    obj = treeResIdFu(treeDataTemp, acShu)

    return obj || {}
  }, [acShu, treeDataTemp])

  // 点击删除
  const delTree = useCallback(
    async (id: string) => {
      const res = await E1_APIdel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功!')
        resetFu(true)
      }
    },
    [resetFu]
  )

  // 点击新增和编辑
  const [addInfo, setAddInfo] = useState({} as I5AddInfoType)

  const addSonFu = useCallback(
    (id: string) => {
      setAddInfo({
        id,
        txt: id === '-1' ? '新增' : '编辑',
        acInfo: rightData
      })
    },
    [rightData]
  )

  return (
    <div className={styles.E1tag}>
      <div className='pageTitle'>藏品标签</div>

      {/* 左侧 */}
      <div className='E1son E1ll'>
        <div className='E1ll1'>
          <Input
            style={{ width: 300 }}
            placeholder='请输入标签名称'
            maxLength={30}
            showCount
            value={value}
            onChange={e => valueChange(e.target.value)}
            allowClear
          />
        </div>
        <div className='E1ll2'>
          {treeDataTemp && treeDataTemp.length ? (
            <Tree
              // 默认全部展开
              defaultExpandAll={true}
              // 数据
              treeData={treeData}
              // 自定义字段
              // fieldNames={{ title: 'title', key: 'key', children: 'children' }}
              // 选中
              selectedKeys={[acShu]}
              // 点击
              onSelect={onSelect}
            />
          ) : loding ? (
            <div className='NODATA'>暂无相关搜索结果，请更换关键字搜索</div>
          ) : null}
        </div>
      </div>
      <div className='E1son E1rr'>
        {rightData.id ? (
          <>
            <div className='E1mr2'>
              <div className='E1mr2_1'>
                <div>操作：</div>
                <Button
                  size='large'
                  type='primary'
                  onClick={() => setAddInfo({ id: '-1', txt: '新增', acInfo: rightData })}
                >
                  新增
                </Button>
              </div>

              <div className='E1mr2_2'>
                <div onClick={() => addSonFu(rightData.id)} className={classNames('E1mr2Btn')}>
                  编辑
                </div>
                &emsp;
                <MyPopconfirm
                  txtK='删除'
                  onConfirm={() => delTree(rightData.id)}
                  disabled={rightData.parentId === '0'}
                  Dom={<div className={classNames('E1mr2Btn E1mr2Btn2')}>删除</div>}
                />
              </div>

              <div className='E1mr2Row'>
                <div className='E1mr2Row1'>标签名称：</div>
                <div className='E1mr2Row2'>{rightData.name}</div>
              </div>

              <div className='E1mr2Row'>
                <div className='E1mr2Row1'>层级：</div>
                <div className='E1mr2Row2'>{rightData.level}</div>
              </div>
              {/* <div className='E1mr2Row'>
                    <div className='E1mr2Row1'>id：</div>
                    <div className='E1mr2Row2'>{rightData.id}</div>
                  </div> */}

              <div className='E1mr2Row'>
                <div className='E1mr2Row1'>排序值：</div>
                <div className='E1mr2Row2'>{rightData.sort}</div>
              </div>

              <div className='E1mr2Row'>
                <div className='E1mr2Row1'>标签说明：</div>
                <div className='E1mr2Row2'>{rightData.intro || '（空）'}</div>
              </div>
            </div>
          </>
        ) : null}
      </div>

      {/* 右侧 */}

      <div className='E1top'></div>

      {/* 主体 */}
      <div className='E1main'>
        <div className='E1m1'>
          <div className='E1m1rr'></div>
        </div>
      </div>
      {/* 新增/编辑页面 中图法分类 */}
      {addInfo.id ? (
        <E1add
          addInfo={addInfo}
          addFu={() => resetFu(false)}
          closeFu={() => setAddInfo({} as I5AddInfoType)}
        />
      ) : null}
    </div>
  )
}

const MemoE1tag = React.memo(E1tag)

export default MemoE1tag
