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

function I2dict() {
  const [loding, setLoding] = useState(false)

  const dispatch = useDispatch()

  const getInfoFu = useCallback(
    (flag: boolean) => {
      // 默认选中第一个为true
      dispatch(
        I2_APIgetDict(data => {
          setLoding(true)
          if (flag && data && data.length) setAcShu(data[0].id)
        })
      )
    },
    [dispatch]
  )

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

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

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

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

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

  // 点击树节点
  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(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
    if (treeDataTemp && treeDataTemp.length && acShu) obj = treeResIdFu(treeDataTemp, acShu)

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

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

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

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

  return (
    <div className={styles.I2dict}>
      <div className='pageTitle'>数据字典</div>

      {/* 左侧 */}
      <div className='I2son I2ll'>
        <div className='I2ll1'>
          <Input
            style={{ width: 300 }}
            placeholder='请输入字典值'
            maxLength={30}
            showCount
            value={value}
            onChange={e => valueChange(e.target.value)}
            allowClear
          />
        </div>

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

          {loding && treeDataTemp.length === 0 ? (
            <div className='NODATA'>
              <p>暂无相关搜索结果，请更换关键字搜索</p>
            </div>
          ) : null}
        </div>
      </div>

      {/* 右侧 */}
      <div className='I2son I2rr'>
        {rightData.id ? (
          <>
            <div className='I2mr1'>
              <div>
                操作{' '}
                <span className='I2mr1Tit'>
                  {rightData.parentId === '0' ? '（一级字典不可编辑）' : ''}
                </span>
              </div>

              <Button
                size='large'
                type='primary'
                onClick={() =>
                  setAddInfo({
                    id: '-1',
                    txt: '新增',
                    acInfo: rightData
                  })
                }
              >
                新增
              </Button>
            </div>
            <div className='I2mr2'>
              <div
                onClick={() => addSonFu(rightData.id)}
                className={classNames('I2mr2Btn', rightData.parentId === '0' ? 'I2mr2BtnNo' : '')}
              >
                编辑
              </div>
              &emsp;
              <MyPopconfirm
                txtK='删除'
                onConfirm={() => delTree(rightData.id)}
                disabled={rightData.parentId === '0'}
                Dom={
                  <div
                    className={classNames(
                      'I2mr2Btn I2mr2Btn2',
                      rightData.parentId === '0' ? 'I2mr2BtnNo' : ''
                    )}
                  >
                    删除
                  </div>
                }
              />
            </div>

            {/* <div className='I2mr3'>
                <div className='I2mr3ll'>id:</div>
                <div className='I2mr3rr'>{rightData.id}</div>
              </div> */}

            <div className='I2mr3'>
              <div className='I2mr3ll'>字典值：</div>
              <div className='I2mr3rr'>{rightData.name}</div>
            </div>

            <div className='I2mr3'>
              <div className='I2mr3ll'>层级：</div>
              <div className='I2mr3rr'>{rightData.level}</div>
            </div>

            <div className='I2mr3'>
              <div className='I2mr3ll'>排序值：</div>
              <div className='I2mr3rr'>{rightData.sort}</div>
            </div>

            <div className='I2mr3'>
              <div className='I2mr3ll'>字典说明：</div>
              <div className='I2mr3rr'>{rightData.intro || '（空）'}</div>
            </div>
          </>
        ) : null}
      </div>

      {/* 新增/编辑页面 中图法分类 */}
      {addInfo.id ? (
        <I2add
          addInfo={addInfo}
          addFu={() => resetFu(false)}
          closeFu={() => setAddInfo({} as I2AddInfoType)}
        />
      ) : null}
    </div>
  )
}

const MemoI2dict = React.memo(I2dict)

export default MemoI2dict
