import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import { TypeD2form, TypeD2list } from './type'
import { useDispatch, useSelector } from 'react-redux'
import { D2_APIdel, D2_APIgetList } from '@/store/action/D2storSet'
import { Button, Input, Select } from 'antd'
import { D2select } from './data'
import { RootState } from '@/store'
import MyTable from '@/components/MyTable'
import { D2tableC } from '@/utils/tableData'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import D2edit from './D2edit'
import history from '@/utils/history'

const formDataTemp: TypeD2form = {
  pageNum: 1,
  pageSize: 10,
  name: '',
  num: '',
  managerUser: '',
  description: '',
  enable: null
}

function D2storSet() {
  const dispatch = useDispatch()

  const [formData, setFormData] = useState(formDataTemp)
  const formDataRef = useRef(formDataTemp)

  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(D2_APIgetList(formDataRef.current))
  }, [dispatch])

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

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

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

  const tableInfo = useSelector((state: RootState) => state.D2storSet.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 = await D2_APIdel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功!')
        getListFu()
      }
    },
    [getListFu]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        width: 240,
        render: (item: TypeD2list) => {
          return (
            <>
              <Button
                size='small'
                type='text'
                onClick={() => history.push(`/storSet_look/${item.id}`)}
              >
                查看
              </Button>
              <Button
                size='small'
                type='text'
                onClick={() => history.push(`/storSet_site/${item.id}/${item.name}`)}
              >
                库位设置
              </Button>
              <Button size='small' type='text' onClick={() => setEditId(item.id)}>
                编辑
              </Button>
              <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
            </>
          )
        }
      }
    ]
  }, [delTableFu])

  // 新增和编辑
  const [editId, setEditId] = useState(0)

  return (
    <div className={styles.D2storSet}>
      <div className='pageTitle'>库房设置</div>
      <div className='D2top'>
        <div className='D2topll'>
          <span>仓库名称：</span>
          <Input
            placeholder='请输入内容'
            maxLength={30}
            value={formData.name}
            onChange={e => txtChangeFu(e.target.value, 'name')}
          />
          <span>仓库编码：</span>
          <Input
            placeholder='请输入内容'
            maxLength={30}
            value={formData.num}
            onChange={e => txtChangeFu(e.target.value, 'num')}
          />
          <span>仓库负责人：</span>
          <Input
            placeholder='请输入内容'
            maxLength={30}
            value={formData.managerUser}
            onChange={e => txtChangeFu(e.target.value, 'managerUser')}
          />
          <span>仓库说明：</span>
          <Input
            placeholder='请输入内容'
            maxLength={30}
            value={formData.description}
            onChange={e => txtChangeFu(e.target.value, 'description')}
          />
          <span>仓库状态：</span>
          <Select
            allowClear={true}
            placeholder='全部'
            options={D2select}
            value={formData.enable}
            onChange={e => setFormData({ ...formData, pageNum: 1, enable: e })}
          />
        </div>
        <div className='D2toprr'>
          <Button type='primary' onClick={() => setEditId(-1)}>
            新增
          </Button>
          &emsp;
          <Button type='primary' onClick={clickSearch}>
            查询
          </Button>
          &emsp;
          <Button onClick={resetFu}>重置</Button>
        </div>
      </div>
      <div className='D2tableBox'>
        <MyTable
          yHeight={630}
          list={tableInfo.list}
          columnsTemp={D2tableC}
          lastBtn={tableLastBtn}
          pageNum={formData.pageNum}
          pageSize={formData.pageSize}
          total={tableInfo.total}
          onChange={(pageNum, pageSize) => paginationChange(pageNum, pageSize)}
          widthSet={{ description: 500 }}
        />
      </div>

      {/* 新增和编辑弹窗 */}
      {editId ? (
        <D2edit
          sId={editId}
          succToLookFu={id => history.push(`/storSet_look/${id}`)}
          closeFu={() => setEditId(0)}
        />
      ) : null}
    </div>
  )
}

const MemoD2storSet = React.memo(D2storSet)

export default MemoD2storSet
