import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { C1InputKeyArr1 } from '../../C1ledger/data'
import { Button, Cascader, Input, Select } from 'antd'
import { C8baseFormData } from './data'
import { openGoodsInfoFu } from '@/utils/history'
import classNames from 'classnames'
import { C1InputKeyType } from '../../C1ledger/type'
import MyTable from '@/components/MyTable'
import { C1tableC } from '@/utils/tableData'
import Y1cathet from '@/pages/Y_goodsDetails/Y1cathet'
import MyPopconfirm from '@/components/MyPopconfirm'
import { useDispatch, useSelector } from 'react-redux'
import { C8_APIgetList, C8_APIrecover } from '@/store/action/C8recycleBin'
import { MessageFu } from '@/utils/message'
import { RootState } from '@/store'

type Props = {
  closeFu: (falg: boolean) => void
}

function C8recycleBin({ closeFu }: Props) {
  const dispatch = useDispatch()

  const [formData, setFormData] = useState(C8baseFormData)
  const formDataRef = useRef(C8baseFormData)
  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(() => {
    dispatch(C8_APIgetList(formDataRef.current))
  }, [dispatch])

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

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

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setFormData(C8baseFormData)
    setTimeout(() => {
      setTimeKey(Date.now())
    }, 50)
  }, [])

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

  const changeRef = useRef(false)

  const regainFu = useCallback(
    async (id: number) => {
      const res = await C8_APIrecover(id)
      if (res.code === 0) {
        changeRef.current = true
        MessageFu.success('恢复成功')
        getListFu()
      }
    },
    [getListFu]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => {
          return (
            <>
              <Button size='small' type='text' onClick={() => openGoodsInfoFu(item.id)}>
                查看
              </Button>
              <MyPopconfirm txtK='恢复' onConfirm={() => regainFu(item.id)} />
            </>
          )
        }
      }
    ]
  }, [regainFu])

  // 打开侧边栏
  const [cathet, setCathet] = useState(0)

  const startBtn = useMemo(() => {
    return [
      {
        title: '藏品编号',
        render: (item: any) => {
          return (
            <span
              onClick={() => setCathet(item.id)}
              className={classNames('D1GtNum', item.id === cathet ? 'D1GtNumAc' : '')}
            >
              {item.num}
            </span>
          )
        }
      }
    ]
  }, [cathet])

  // 顶部筛选
  const searchDom = useCallback(
    (arr: any[]) => {
      return arr.map(item => {
        return (
          <div key={item.name}>
            <span>{item.name}：</span>
            {item.type === '输入框' ? (
              <Input
                placeholder='请输入'
                maxLength={30}
                value={formData[item.key as 'num']}
                onChange={e => txtChangeFu(e.target.value, item.key)}
              />
            ) : item.type === '下拉框' ? (
              <Select
                options={item.data}
                placeholder='全部'
                allowClear={true}
                value={formData[item.key as 'num'] ? formData[item.key as 'num'] : null}
                onChange={e => setFormData({ ...formData, [item.key]: e })}
              />
            ) : (
              <Cascader
                options={item.data}
                placeholder='全部'
                fieldNames={{ label: 'name', value: 'id', children: 'children' }}
                allowClear={true}
                value={
                  formData[item.key as 'num']
                    ? (formData[item.key as 'num'] as string).split(',')
                    : []
                }
                onChange={e => setFormData({ ...formData, [item.key]: e ? e.join(',') : '' })}
              />
            )}
          </div>
        )
      })
    },
    [formData, txtChangeFu]
  )

  // 从仓库拿数据
  const tableInfo = useSelector((state: RootState) => state.C8recycleBin.tableInfo)

  return (
    <div className={styles.C8recycleBin}>
      {/* <div className='pageTitle'>回收站</div> */}
      <div className='C8top'>
        <div className='C8topll'>{searchDom(C1InputKeyArr1)}</div>
        <div className='C8toprr'>
          <Button type='primary' onClick={clickSearch}>
            查询
          </Button>
          &emsp;
          <Button onClick={resetSelectFu}>重置</Button>
          &emsp;
          <Button onClick={() => closeFu(changeRef.current)}>返回</Button>
        </div>
      </div>

      {/* 表格 */}
      <MyTable
        classKey='C8recycleBin'
        yHeight={586}
        list={tableInfo.list}
        columnsTemp={[...C1tableC, ['txt', '删除日期', 'updateTime']]}
        lastBtn={tableLastBtn}
        startBtn={startBtn}
        pageNum={formData.pageNum}
        pageSize={formData.pageSize}
        total={tableInfo.total}
        onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
      />

      {/* 打开侧边栏 */}
      <Y1cathet sId={cathet} closeFu={() => setCathet(0)} />
    </div>
  )
}

const MemoC8recycleBin = React.memo(C8recycleBin)

export default MemoC8recycleBin
