import { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import { Input, Button, Cascader } from 'antd'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import styles from './index.module.scss'
import MyTable from '@/components/MyTable'
import MyPopconfirm from '@/components/MyPopconfirm'
import { I5_APIgetTree } from '@/store/action/Isystem/I5organization'
import { baseFormData, UserTableAPIType, UserTableListType } from './data'
import { getUserListAPI, userPassResetAPI, userRemoveAPI } from '@/store/action/Isystem/I7user'
import { I7tableC } from '@/utils/tableData'
import { buMenRes } from '@/utils/dataChange'
import I7add from './I7add'

function I7user() {
  const dispatch = useDispatch()

  // 获取组织管理列表
  useEffect(() => {
    dispatch(I5_APIgetTree())
  }, [dispatch])

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

  // 顶部筛选
  const [formData, setFormData] = useState(baseFormData)
  const formDataRef = useRef(baseFormData)
  const formDataOldRef = useRef(baseFormData)

  useEffect(() => {
    formDataRef.current = formData
  }, [formData])

  // 点击搜索的 时间戳
  const [timeKey, setTimeKey] = useState(0)

  // 点击搜索
  const clickSearch = useCallback(() => {
    setFormData({ ...formData, pageNum: 1 })
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [formData])

  // 封装发送请求的函数
  const getListFu = useCallback(
    (formOld?: UserTableAPIType) => {
      if (formOld) setFormData({ ...formOld })

      const obj = formOld
        ? { ...formOld }
        : {
            ...formDataRef.current
          }

      formDataOldRef.current = { ...formDataRef.current }

      let deptIdRes = obj.deptId

      if (deptIdRes) obj.deptId = Number(deptIdRes[deptIdRes.length - 1])

      dispatch(getUserListAPI(obj))
    },
    [dispatch]
  )

  useEffect(() => {
    getListFu()
  }, [getListFu, timeKey])

  // 输入框的改变
  const txtChangeFu = useCallback(
    (txt: string, key: 'searchKey') => {
      setFormData({
        ...formData,
        [key]: txt
      })
    },
    [formData]
  )

  // 点击重置
  const resetSelectFu = useCallback(() => {
    // 把2个输入框和时间选择器清空
    setFormData(baseFormData)
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [])

  // 从仓库中获取表格数据
  const tableInfo = useSelector((state: RootState) => state.I7user.tableInfo)

  // 页码变化
  const paginationChange = useCallback(
    (pageNum: number, pageSize: number) => {
      setFormData({ ...formData, pageNum, pageSize })
      setTimeout(() => {
        setTimeKey(Date.now())
      }, 50)
    },
    [formData]
  )

  // 点击删除
  const delTableFu = useCallback(
    async (id: number) => {
      const res: any = await userRemoveAPI(id)
      if (res.code === 0) {
        MessageFu.success('删除成功!')
        getListFu()
      }
    },
    [getListFu]
  )

  // 点击重置密码
  const resetPassFu = useCallback(async (id: number) => {
    const res: any = await userPassResetAPI(id)
    if (res.code === 0) MessageFu.success('重置成功!')
  }, [])

  // 0------------点击新增或者编辑出来的页面
  const [editPageShow, setEditPageShow] = useState(false)
  const editId = useRef(0)

  const openEditPageFu = useCallback((id: number) => {
    editId.current = id
    setEditPageShow(true)
  }, [])

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: UserTableListType) => {
          return item.isAdmin === 1 && !window.location.href.includes('?k=4DAGE') ? (
            '-'
          ) : (
            <>
              <MyPopconfirm
                txtK='重置密码'
                onConfirm={() => resetPassFu(item.id)}
                Dom={
                  <Button size='small' type='text'>
                    重置密码
                  </Button>
                }
              />
              <Button size='small' type='text' onClick={() => openEditPageFu(item.id)}>
                编辑
              </Button>
              <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
            </>
          )
        }
      }
    ]
  }, [delTableFu, openEditPageFu, resetPassFu])

  return (
    <div className={styles.I7user}>
      <div className='pageTitle'>用户管理</div>
      <div className='userTop'>
        <div className='selectBox'>
          <div className='selectBoxRow'>
            <span>搜索项：</span>
            <Input
              maxLength={15}
              showCount
              style={{ width: 300 }}
              placeholder='请输入用户名或真实姓名'
              value={formData.searchKey}
              onChange={e => txtChangeFu(e.target.value, 'searchKey')}
            />
            &emsp;&emsp;
            <span>选择部门：</span>
            <Cascader
              // allowClear={false}
              changeOnSelect
              style={{ width: 240 }}
              options={treeData}
              value={formData.deptId as string[]}
              fieldNames={{ label: 'name', value: 'id', children: 'children' }}
              placeholder='全部'
              onChange={e =>
                setFormData({
                  ...formData,
                  deptId: e as string[]
                })
              }
            />
          </div>

          <div className='selectBoxRow'>
            <Button type='primary' onClick={() => openEditPageFu(0)}>
              新增
            </Button>
            &emsp;
            <Button type='primary' onClick={clickSearch}>
              查询
            </Button>
            &emsp;<Button onClick={resetSelectFu}>重置</Button>
          </div>
        </div>
      </div>
      {/* 表格主体 */}
      <div className='tableBox'>
        <MyTable
          yHeight={585}
          list={buMenRes(tableInfo.list)}
          columnsTemp={I7tableC}
          lastBtn={tableLastBtn}
          pageNum={formData.pageNum}
          pageSize={formData.pageSize}
          total={tableInfo.total}
          onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
        />
      </div>

      {/* 点击新增或者编辑 */}
      {editPageShow ? (
        <I7add
          id={editId.current}
          closePage={() => setEditPageShow(false)}
          upTableList={formOld => getListFu(formOld)}
          addTableList={resetSelectFu}
          formOld={formDataOldRef.current}
        />
      ) : null}
    </div>
  )
}

const MemoI7user = React.memo(I7user)

export default MemoI7user
