import React, { useCallback, useEffect, useState } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { A7_APIgetList, A7_APIsave } from '@/store/action/A7numData'
import { RootState } from '@/store'
import { Button, InputNumber } from 'antd'
import { A7ListType } from './data'
import { MessageFu } from '@/utils/message'
function A7numData() {
  const dispatch = useDispatch()

  useEffect(() => {
    dispatch(A7_APIgetList())
  }, [dispatch])

  const list = useSelector((state: RootState) => state.A7numData.list)

  const [listTemp, setListTemp] = useState<A7ListType[]>([])

  useEffect(() => {
    setListTemp(list)
  }, [list])

  const changeFu = useCallback(
    (id: number, val: number) => {
      setListTemp(
        listTemp.map(v => ({
          ...v,
          pcs: v.id === id ? val : v.pcs
        }))
      )
    },
    [listTemp]
  )

  // 是否编辑
  const [isEdit, setIsEdit] = useState(false)

  // 点击提交
  const btnOk = useCallback(async () => {
    let flag = false
    listTemp.forEach(v => {
      if (!v.pcs) flag = true
    })
    if (flag) return MessageFu.warning('请输入>0的正整数')

    const res = await A7_APIsave({
      id: 10,
      rtf: JSON.stringify(listTemp)
    })
    if (res.code === 0) {
      MessageFu.success('编辑成功')
      setIsEdit(false)
      dispatch(A7_APIgetList())
    }
  }, [dispatch, listTemp])

  return (
    <div className={styles.A7numData}>
      <div className='pageTitle'>数据维护</div>

      {listTemp.map(item => (
        <div className='A7row' key={item.id}>
          <div className='A7row1'>{item.name}：</div>
          <div className='A7row2'>
            <InputNumber
              style={{ width: 200 }}
              disabled={!isEdit}
              value={item.pcs}
              onChange={e => changeFu(item.id, e as number)}
              max={99999}
              min={1}
            />
          </div>
        </div>
      ))}

      <div className='A7btn' style={{ top: isEdit ? 250 : 23 }}>
        {isEdit ? (
          <>
            <Button
              onClick={() => {
                setIsEdit(false)
                setListTemp(list)
              }}
            >
              取消
            </Button>
            &emsp;
            <Button type='primary' onClick={btnOk}>
              提交
            </Button>
          </>
        ) : (
          <Button type='primary' onClick={() => setIsEdit(true)}>
            编辑
          </Button>
        )}
      </div>
    </div>
  )
}

const MemoA7numData = React.memo(A7numData)

export default MemoA7numData
