import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Input, Tree, TreeDataNode } from 'antd'
import { treeResIdFu } from './data'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { A2_APIdel1, A2_APIdel2, A2_APIgetList1, A2_APIgetList2 } from '@/store/action/A2classify'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import A2add, { A2AddInfoType } from './A2add'
import { A2tableType, A2TreeType } from '@/types'
import MyTable from '@/components/MyTable'
import { A2tableC } from '@/utils/tableData'
import A2add2 from './A2add2'

export type TopLeftArrType = '中图法分类' | '展示分类'

const topLeftArr: TopLeftArrType[] = ['中图法分类', '展示分类']

function A2classify() {
  const treeDataTemp = useSelector((state: RootState) => state.A2classify.treeData)
  const dispatch = useDispatch()

  const [topType, setTopType] = useState<TopLeftArrType>('中图法分类')

  const getList1 = useCallback(() => {
    dispatch(A2_APIgetList1())
  }, [dispatch])

  const getList2 = useCallback(
    async (val: string) => {
      dispatch(A2_APIgetList2({ pageNum: 1, pageSize: 9999, searchKey: val }))
    },
    [dispatch]
  )

  useEffect(() => {
    getList1()
  }, [getList1])

  // 点击重置
  const resetSelectFu = useCallback(
    (flag?: boolean) => {
      setValue('')
      if (topType === '展示分类') getList2('')
      if (flag) getList1()
    },
    [getList1, getList2, topType]
  )

  // 顶部切换tab
  const cutTop = useCallback(
    (item: TopLeftArrType) => {
      setValue('')
      setTopType(item)
      item === '中图法分类' ? getList1() : getList2('')
    },
    [getList1, getList2]
  )

  const [value, setValue] = useState('')

  const time = useRef(-1)
  const valueChange = useCallback(
    (val: string) => {
      setValue(val)
      clearInterval(time.current)
      time.current = window.setTimeout(() => {
        if (topType === '展示分类') getList2(val)
        // topType === '中图法分类' ? getList1(val) : getList2(val)
      }, 500)
    },
    [getList2, topType]
  )

  // 有关树------------------------
  const tab1Flag = useRef(true)
  useEffect(() => {
    if (treeDataTemp && treeDataTemp.length && tab1Flag.current) {
      tab1Flag.current = false
      setAcShu(treeDataTemp[0].id as number)
    }
  }, [treeDataTemp])

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

  // 点击树节点
  const onSelect = (id: any) => {
    if (id[0]) setAcShu(id[0])
  }

  // 搜索高亮
  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 A2TreeType

    obj = treeResIdFu(treeDataTemp, acShu)

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

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

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

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

  // -----------------展示分类
  const tableInfo = useSelector((state: RootState) => state.A2classify.tableInfo)

  const delTableFu = useCallback(
    async (id: number) => {
      const res = await A2_APIdel2(id)
      if (res.code === 0) {
        MessageFu.success('删除成功!')
        getList2(value)
      }
    },
    [getList2, value]
  )
  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: A2tableType) => (
          <>
            <Button size='small' type='text' onClick={() => setTab2Id(item.id)}>
              编辑
            </Button>
            <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
          </>
        )
      }
    ]
  }, [delTableFu])

  // tab新增/编辑
  const [tab2Id, setTab2Id] = useState(0)

  return (
    <div className={styles.A2classify}>
      <div className='pageTitle'>图书分类</div>
      {/* 顶部 */}
      <div className='A2top'>
        <div className='A2top1'>
          {topLeftArr.map(item => (
            <Button
              onClick={() => cutTop(item)}
              key={item}
              type={topType === item ? 'primary' : 'default'}
            >
              {item}
            </Button>
          ))}
        </div>
        <div className='A2top1'>
          <Input
            style={{ width: 240 }}
            placeholder={topType === '中图法分类' ? '请输入分类名称/编号' : '请输入标题'}
            value={value}
            onChange={e => valueChange(e.target.value)}
          />
          &emsp;
          <Button onClick={() => resetSelectFu()}>重置</Button>&emsp;
          <Button
            type='primary'
            onClick={() =>
              topType === '展示分类'
                ? setTab2Id(-1)
                : setAddInfo({ id: -1, txt: '新增', acInfo: rightData })
            }
          >
            新增
          </Button>
        </div>
      </div>

      {/* 主体 */}
      <div className='A2main'>
        <div className='A2m1' hidden={topType !== '中图法分类'}>
          <div className='A2m1ll'>
            {treeDataTemp && treeDataTemp.length ? (
              <Tree
                // 默认全部展开
                defaultExpandAll={true}
                // 数据
                treeData={treeData}
                // 自定义字段
                // fieldNames={{ title: 'title', key: 'key', children: 'children' }}
                // 选中
                selectedKeys={[acShu]}
                // 点击
                onSelect={onSelect}
              />
            ) : (
              <div className='A2Null'>暂无数据</div>
            )}
          </div>
          <div className='A2m1rr'>
            <div className='A2mr1'>分类详情</div>

            {rightData.id ? (
              <>
                <div className='A2mr2'>
                  <Button type='text' onClick={() => addSonFu(rightData.id)}>
                    编辑
                  </Button>
                  &emsp;
                  <MyPopconfirm txtK='删除' onConfirm={() => delTree(rightData.id)} />
                </div>

                <div className='A2mr3'>
                  <div className='A2mr3ll'>分类编号：</div>
                  <div className='A2mr3rr'>{rightData.num}</div>
                </div>

                <div className='A2mr3'>
                  <div className='A2mr3ll'>分类名称：</div>
                  <div className='A2mr3rr'>{rightData.name}</div>
                </div>

                <div className='A2mr3'>
                  <div className='A2mr3ll'>层级：</div>
                  <div className='A2mr3rr'>{rightData.level}</div>
                </div>

                <div className='A2mr3'>
                  <div className='A2mr3ll'>排序值：</div>
                  <div className='A2mr3rr'>{rightData.sort}</div>
                </div>

                <div className='A2mr3'>
                  <div className='A2mr3ll'>编辑时间：</div>
                  <div className='A2mr3rr'>{rightData.updateTime}</div>
                </div>

                <div className='A2mr3'>
                  <div className='A2mr3ll'>编辑人：</div>
                  <div className='A2mr3rr'>{rightData.creatorName}</div>
                </div>
              </>
            ) : (
              <div className='A2Null'>暂无数据</div>
            )}
          </div>
        </div>
        <div className='A2m2' hidden={topType !== '展示分类'}>
          <MyTable
            yHeight={678}
            list={tableInfo.list}
            columnsTemp={A2tableC}
            lastBtn={tableLastBtn}
            pagingInfo={false}
          />
        </div>
      </div>

      {/* 新增/编辑页面 中图法分类 */}
      {addInfo.id ? (
        <A2add
          addInfo={addInfo}
          addFu={() => resetSelectFu(true)}
          closeFu={() => setAddInfo({} as A2AddInfoType)}
        />
      ) : null}

      {/* 新增/编辑 展示分类 */}
      {tab2Id ? (
        <A2add2
          tab2Id={tab2Id}
          addFu={flag => (flag ? getList2(value) : resetSelectFu())}
          closeFu={() => setTab2Id(0)}
        />
      ) : null}
    </div>
  )
}

const MemoA2classify = React.memo(A2classify)

export default MemoA2classify
