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 { I5_APIdel, I5_APIgetTree, I5_APIgetUserById } from '@/store/action/Isystem/I5organization'
import { I5AddInfoType, TypeI5Tree, TypeI5UserList } from './data'
import { filterTreeByName, treeResIdFu } from '../I2dict/data'
import classNames from 'classnames'
import I5add from './I5add'

function I5organization() {
  const dispatch = useDispatch()

  const [loding, setLoding] = useState(false)

  const getInfoFu = useCallback(
    (flag: boolean) => {
      dispatch(
        I5_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.I5organization)

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

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

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

  // 获取相关成员列表
  const [userList, setUserList] = useState<TypeI5UserList[]>([])

  const getUserByIdFu = useCallback(async (id: string) => {
    const res = await I5_APIgetUserById(id)
    if (res.code === 0) {
      setUserList(res.data)
    }
  }, [])

  useEffect(() => {
    if (acShu) getUserByIdFu(acShu)
  }, [acShu, getUserByIdFu])

  // 点击树节点
  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 I5_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.I5organization}>
      <div className='pageTitle'>组织管理</div>

      {/* 左侧 */}
      <div className='I5son I5ll'>
        <div className='I5ll1'>
          <Input
            style={{ width: 300 }}
            placeholder='请输入部门名称'
            maxLength={30}
            showCount
            value={value}
            onChange={e => valueChange(e.target.value)}
            allowClear
          />
        </div>
        <div className='I5ll2'>
          {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='I5son I5rr'>
        {rightData.id ? (
          <>
            <div className='I5mr2'>
              <div className='I5mr2_1'>
                <div>操作：</div>
                <Button
                  size='large'
                  type='primary'
                  onClick={() => setAddInfo({ id: '-1', txt: '新增', acInfo: rightData })}
                >
                  新增
                </Button>
              </div>

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

              <div className='I5mr2Row'>
                <div className='I5mr2Row1'>部门名称：</div>
                <div className='I5mr2Row2'>{rightData.name}</div>
              </div>

              <div className='I5mr2Row'>
                <div className='I5mr2Row1'>层级：</div>
                <div className='I5mr2Row2'>{rightData.level}</div>
              </div>
              {/* <div className='I5mr2Row'>
                    <div className='I5mr2Row1'>id：</div>
                    <div className='I5mr2Row2'>{rightData.id}</div>
                  </div> */}

              <div className='I5mr2Row'>
                <div className='I5mr2Row1'>排序值：</div>
                <div className='I5mr2Row2'>{rightData.sort}</div>
              </div>

              <div className='I5mr2Row'>
                <div className='I5mr2Row1'>部门说明：</div>
                <div className='I5mr2Row2'>{rightData.description || '（空）'}</div>
              </div>

              <div className='I5mr2Row I5mr2RowLast'>
                <div className='I5mr2Row1'>相关成员：</div>
                <div className='I5mr2Row2'>
                  {userList.length
                    ? userList.map((v, i) => (
                        <div key={v.userId}>
                          {v.userName}
                          {v.isLeader === 1 ? '（部门主管）' : ''}
                          {i < userList.length - 1 ? '，' : ''}
                        </div>
                      ))
                    : '（空）'}
                </div>
              </div>
            </div>
          </>
        ) : null}
      </div>

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

const MemoI5organization = React.memo(I5organization)

export default MemoI5organization
