import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { Z1_APIdel, Z1_APIgetDict } from '@/store/action/Z1dict'
import { RootState } from '@/store'
import { Button, Cascader, Input, Tree, TreeDataNode } from 'antd'
import { treeResIdFu, Z1toTowFu } from './data'
import { TypeZ1dict } from './type'
import Z1add, { Z1AddInfoType } from './Z1add'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import { filterTreeByName } from '@/utils/history'

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

  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(Z1_APIgetDict())
  }, [dispatch])

  // 级联改变
  const [topId, setTopId] = useState(['10000', '12000'])

  // 传给新增、编辑子组件（没有数据或者删除了的时候-既右侧没有操作的时候）
  const isNoAcIds = useRef<string[]>([])

  useEffect(() => {
    isNoAcIds.current = ['0', ...topId]

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

  const onChange = useCallback((value: any) => {
    // console.log('级联改变', value)
    setTopId(value)
  }, [])

  const { dictAll, dictList } = useSelector((state: RootState) => state.Z1dict)

  // 点击重置
  const resetFu = useCallback(
    (flag: boolean) => {
      // 重置 flag为true
      // 新增和编辑 为false
      if (flag) {
        setTopId(['10000', '12000'])
      } else dispatch(Z1_APIgetDict(topId[1]))

      setValue('')
      setValue2('')
    },
    [dispatch, topId]
  )

  // 当前选中的树节点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 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 TypeZ1dict
    if (treeDataTemp && treeDataTemp.length) obj = treeResIdFu(treeDataTemp, acShu)

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

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

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

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

  return (
    <div className={styles.Z1dict}>
      <div className='pageTitle'>数据字典</div>
      {/* 顶部 */}
      <div className='Z1top'>
        <div className='Z1topll'>
          {dictAll.length ? (
            <Cascader
              style={{ width: 240 }}
              value={topId}
              options={Z1toTowFu(dictAll)}
              fieldNames={{ label: 'name', value: 'id', children: 'children' }}
              onChange={onChange}
              allowClear={false}
            />
          ) : (
            <div style={{ width: 240 }}></div>
          )}
          &emsp;
          <Input
            style={{ width: 240 }}
            placeholder='请输入字典值'
            maxLength={30}
            value={value}
            onChange={e => valueChange(e.target.value)}
          />
        </div>
        <div className='Z1toprr'>
          <Button
            type='primary'
            onClick={() => setAddInfo({ id: '-1', txt: '新增', acInfo: rightData })}
          >
            新增
          </Button>
          &emsp;
          <Button onClick={() => resetFu(true)}>重置</Button>
        </div>
      </div>
      {/* 主体 */}
      <div className='Z1main'>
        <div className='Z1m1ll'>
          {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='Z1m1llNone'>暂无数据</div> : null}
        </div>
        <div className='Z1m1rr'>
          {rightData.id ? (
            <>
              <div className='Z1mr1'>操作</div>
              <div className='Z1mr2'>
                <Button type='text' onClick={() => addSonFu(rightData.id)}>
                  编辑
                </Button>
                &emsp;
                <MyPopconfirm txtK='删除' onConfirm={() => delTree(rightData.id)} />
              </div>

              {/* <div className='Z1mr3'>
                <div className='Z1mr3ll'>id:</div>
                <div className='Z1mr3rr'>{rightData.id}</div>
              </div> */}

              <div className='Z1mr3'>
                <div className='Z1mr3ll'>字典值：</div>
                <div className='Z1mr3rr'>{rightData.name}</div>
              </div>

              <div className='Z1mr3'>
                <div className='Z1mr3ll'>层级：</div>
                <div className='Z1mr3rr'>{rightData.level - 2}</div>
              </div>

              <div className='Z1mr3'>
                <div className='Z1mr3ll'>排序值：</div>
                <div className='Z1mr3rr'>{rightData.sort}</div>
              </div>
            </>
          ) : null}
        </div>
      </div>
      {/* 新增/编辑页面 中图法分类 */}
      {addInfo.id ? (
        <Z1add
          addInfo={addInfo}
          addFu={() => resetFu(false)}
          closeFu={() => setAddInfo({} as Z1AddInfoType)}
          isNoAcIds={isNoAcIds.current}
        />
      ) : null}
    </div>
  )
}

const MemoZ1dict = React.memo(Z1dict)

export default MemoZ1dict
