import React, { useEffect, useState } from 'react'
import { Modal, Form, Input, Button, Select } from 'antd'
import { I1_APIwarehouseSave } from '@/store/action/Isystem/I1storageSet'
import MyPopconfirm from '@/components/MyPopconfirm'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { getUserListAPI } from '@/store/action/Isystem/I7user'

interface AddWarehouseModalProps {
  visible: boolean
  onCancel: () => void
  onSuccess: () => void
  editData?: any
}

const AddWarehouseModal: React.FC<AddWarehouseModalProps> = ({
  visible,
  onCancel,
  onSuccess,
  editData
}) => {
  const dispatch = useDispatch()
  const [loading, setLoading] = useState(false)
  const [form] = Form.useForm()
  const userInfo = useSelector((state: RootState) => state.I7user.tableInfo)

  const handleOk = async () => {
    try {
      const values = await form.validateFields()
      setLoading(true)
      const payload = editData ? { ...values, id: editData.id } : values
      const res = await I1_APIwarehouseSave(payload)
      setLoading(false)
      if (res.code === 0) {
        onSuccess()
        form.resetFields()
      }
    } catch (err) {
      setLoading(false)
    }
  }

  useEffect(() => {
    if (!visible) return

    dispatch(
      getUserListAPI({
        pageNum: 1,
        pageSize: 9999
      })
    )
    if (editData) {
      form.setFieldsValue({
        name: editData.name,
        managerUserId: editData.managerUserId,
        description: editData.description
      })
    } else {
      form.resetFields()
    }
  }, [dispatch, userInfo.list.length, visible, editData, form])

  return (
    <Modal
      title={editData ? '编辑' : '新增'}
      open={visible}
      onCancel={() => {
        form.resetFields()
        onCancel()
      }}
      footer={null}
      destroyOnClose
    >
      <Form form={form} labelCol={{ span: 5 }}>
        <Form.Item
          label='库房名称'
          name='name'
          rules={[{ required: true, message: '请输入库房名称' }]}
        >
          <Input placeholder='请输入库房名称' />
        </Form.Item>
        <Form.Item label='库房负责人' name='managerUserId'>
          <Select
            placeholder='请选择用户'
            options={userInfo.list.map((i: any) => ({ label: i.realName, value: i.id }))}
          />
        </Form.Item>
        <Form.Item
          label='库房说明'
          name='description'
          rules={[{ max: 500, message: '库房说明不能超过500字' }]}
        >
          <Input.TextArea placeholder='请输入库房说明（不超过500字）' maxLength={500} rows={4} />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 9, span: 16 }}>
          <Button type='primary' loading={loading} onClick={handleOk} style={{ marginRight: 8 }}>
            提交
          </Button>

          <MyPopconfirm
            txtK='取消'
            onConfirm={() => {
              form.resetFields()
              onCancel()
            }}
          />
        </Form.Item>
      </Form>
    </Modal>
  )
}

export default AddWarehouseModal
