import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Input, Select } from 'antd'
import { TypeD1Gform } from './type'
import MyTable from '@/components/MyTable'
import { D1GtableC } from '@/utils/tableData'
import Y1cathet from '@/pages/Y_goodsDetails/Y1cathet'
import { openGoodsInfoFu } from '@/utils/history'
import classNames from 'classnames'
import { selectObj } from '@/utils/select'
import { D1_APIgetGoodsList } from '@/store/action/D1storage'
import { D1canType } from '../type'

const baseFormData: TypeD1Gform = {
  pageSize: 10,
  pageNum: 1,
  numName: '',
  num: '',
  name: '',
  statusStorage: null
}

type Props = {
  lookData: D1canType
  TreeDom: React.ReactNode
  tableId: number
}

function D1goods({ lookData, TreeDom, tableId }: Props) {
  const siteCan = useRef({} as D1canType)

  useEffect(() => {
    if (lookData.layer1) siteCan.current = lookData
  }, [lookData])

  const [formData, setFormData] = useState(baseFormData)
  const formDataRef = 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 [table, setTable] = useState({
    list: [],
    total: 0
  })

  // 封装发送请求的函数
  const getListFu = useCallback(async () => {
    const res = await D1_APIgetGoodsList({
      ...formDataRef.current,
      storageId: tableId,
      ...siteCan.current
    })
    if (res.code === 0) {
      setTable({
        list: res.data.records,
        total: res.data.total
      })
    }
  }, [tableId])

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

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

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

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

  // 打开侧边栏
  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 tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: any) => {
          return (
            <Button size='small' type='text' onClick={() => openGoodsInfoFu(item.id)}>
              查看
            </Button>
          )
        }
      }
    ]
  }, [])

  return (
    <div className={styles.D1goods}>
      <div className='D1Gtop'>
        <div className='D1GtRow'>
          <span className='D1GtRowTxt'>编号类型：</span>
          <Select
            allowClear={true}
            options={selectObj['藏品编号类型']}
            style={{ width: 160 }}
            value={formData.numName}
            placeholder='全部'
            onChange={e => setFormData({ ...formData, numName: e })}
          />
        </div>

        <div className='D1GtRow'>
          <span className='D1GtRowTxt'>藏品编号：</span>
          <Input
            placeholder='请输入内容'
            maxLength={30}
            value={formData.num}
            onChange={e => txtChangeFu(e.target.value, 'num')}
          />
        </div>

        <div className='D1GtRow'>
          <span className='D1GtRowTxt'>藏品名称：</span>
          <Input
            placeholder='请输入内容'
            maxLength={30}
            value={formData.name}
            onChange={e => txtChangeFu(e.target.value, 'name')}
          />
        </div>

        <div className='D1GtRow'>
          <span className='D1GtRowTxt'>库存状态：</span>
          <Select
            allowClear={true}
            options={selectObj['库存状态']}
            style={{ width: 160 }}
            value={formData.statusStorage}
            placeholder='全部'
            onChange={e => setFormData({ ...formData, statusStorage: e })}
          />
        </div>

        <div className='D1GtRow'>
          <Button type='primary' onClick={clickSearch}>
            查询
          </Button>
          &emsp;
          <Button onClick={resetSelectFu}>重置</Button>
        </div>
      </div>

      <div className='D1Gmain'>
        {TreeDom}
        <div className='D1Gmainrr'>
          {/* 表格 */}
          <MyTable
            yHeight={620}
            list={table.list}
            columnsTemp={D1GtableC}
            startBtn={startBtn}
            lastBtn={tableLastBtn}
            widthSet={{ description: 200 }}
            pageNum={formData.pageNum}
            pageSize={formData.pageSize}
            total={table.total}
            onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
          />
        </div>
      </div>

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

const MemoD1goods = React.memo(D1goods)

export default MemoD1goods
