import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { Button, Input, Tree, TreeDataNode } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { D4_APIgetTree, Z4_APIdel, Z4_APIgetUserById } from '@/store/action/Z4organization'
import { RootState } from '@/store'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import { treeResIdFu } from '../Z1dict/data'
import { TypeZ4Tree, TypeZ4UserList } from './type'
import Z4add, { Z4AddInfoType } from './Z4add'
function Z4organization() {
  const dispatch = useDispatch()

  const [loding, setLoding] = useState(false)

  useEffect(() => {
    dispatch(
      D4_APIgetTree(data => {
        setLoding(true)
        if (data && data.length) setAcShu(data[0].id)
      })
    )
  }, [dispatch])

  const { treeData: treeDataTemp } = useSelector((state: RootState) => state.Z4organization)

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

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

  const getUserByIdFu = useCallback(async (id: string) => {
    const res = await Z4_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 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}>{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 TypeZ4Tree

    obj = treeResIdFu(treeDataTemp, acShu)

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

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

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

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

  return (
    <div className={styles.Z4organization}>
      <div className='pageTitle'>组织管理</div>
      <div className='Z4top'>
        <Input value={value} onChange={e => setValue(e.target.value)} hidden />
        <Button
          type='primary'
          onClick={() => setAddInfo({ id: '-1', txt: '新增', acInfo: rightData })}
        >
          新增
        </Button>
      </div>

      {/* 主体 */}
      <div className='Z4main'>
        <div className='Z4m1'>
          <div className='Z4m1ll'>
            {treeDataTemp && treeDataTemp.length ? (
              <Tree
                // 默认全部展开
                defaultExpandAll={true}
                // 数据
                treeData={treeData}
                // 自定义字段
                // fieldNames={{ title: 'title', key: 'key', children: 'children' }}
                // 选中
                selectedKeys={[acShu]}
                // 点击
                onSelect={onSelect}
              />
            ) : loding ? (
              <div className='Z4Null'>暂无数据</div>
            ) : null}
          </div>
          <div className='Z4m1rr'>
            {rightData.id ? (
              <>
                <div className='Z4mr2'>
                  <div className='Z4mr2Row Z4mr2Row0'>
                    <div className='Z4mr2Row1'>操作：</div>
                    <div>
                      <Button type='text' onClick={() => addSonFu(rightData.id)}>
                        编辑
                      </Button>
                      &emsp;
                      <MyPopconfirm txtK='删除' onConfirm={() => delTree(rightData.id)} />
                    </div>
                  </div>

                  <div className='Z4mr2Row'>
                    <div className='Z4mr2Row1'>部门名称：</div>
                    <div>{rightData.name}</div>
                  </div>

                  <div className='Z4mr2Row'>
                    <div className='Z4mr2Row1'>部门说明：</div>
                    <div className='Z4mr2Row2'>{rightData.description || '（空）'}</div>
                  </div>

                  <div className='Z4mr2Row'>
                    <div className='Z4mr2Row1'>层级：</div>
                    <div>{rightData.level}</div>
                  </div>
                  {/* <div className='Z4mr2Row'>
                    <div className='Z4mr2Row1'>id：</div>
                    <div>{rightData.id}</div>
                  </div> */}

                  <div className='Z4mr2Row'>
                    <div className='Z4mr2Row1'>排序值：</div>
                    <div>{rightData.sort}</div>
                  </div>

                  <div className='Z4mr2Row Z4mr2RowLast'>
                    <div className='Z4mr2Row1'>相关成员：</div>
                    <div className='Z4mr2Row2'>
                      {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>
        </div>
      </div>
      {/* 新增/编辑页面 中图法分类 */}
      {addInfo.id ? (
        <Z4add
          addInfo={addInfo}
          addFu={() => dispatch(D4_APIgetTree())}
          closeFu={() => setAddInfo({} as Z4AddInfoType)}
        />
      ) : null}
    </div>
  )
}

const MemoZ4organization = React.memo(Z4organization)

export default MemoZ4organization
