import React, { useCallback, useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { Button, Form, FormInstance, Input, Modal, Radio, Select } from 'antd'
import TextArea from 'antd/es/input/TextArea'
import MyPopconfirm from '@/components/MyPopconfirm'
import { useDispatch, useSelector } from 'react-redux'
import { getUserListAPI } from '@/store/action/Z6user'
import { RootState } from '@/store'
import { D2_APIedit, D2_APIgetInfo } from '@/store/action/D2storSet'
import { MessageFu } from '@/utils/message'

type Props = {
  sId: number
  succToLookFu: (id: number) => void
  closeFu: () => void
}

function D2edit({ sId, succToLookFu, closeFu }: Props) {
  // 获取用户列表
  const dispatch = useDispatch()
  useEffect(() => {
    dispatch(
      getUserListAPI({
        pageNum: 1,
        pageSize: 99999,
        searchKey: ''
      })
    )
  }, [dispatch])

  const userList = useSelector((state: RootState) => state.Z6user.tableInfo.list)

  // 设置表单ref
  const FormBoxRef = useRef<FormInstance>(null)

  const getInfoFu = useCallback(async (id: number) => {
    const res = await D2_APIgetInfo(id)
    const obj = res.data

    if (obj.memberUserIds)
      obj.memberUserIds = obj.memberUserIds.split(',').map((v: string) => Number(v))
    else obj.memberUserIds = []
    if (res.code === 0) FormBoxRef.current?.setFieldsValue(res.data)
  }, [])

  useEffect(() => {
    if (sId > 0) getInfoFu(sId)
    else FormBoxRef.current?.setFieldsValue({ enable: 1 })
  }, [getInfoFu, sId])

  // 没有通过校验
  const onFinishFailed = useCallback(() => {
    // return MessageFu.warning("有表单不符号规则!");
  }, [])

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      const res = await D2_APIedit({
        ...values,
        id: sId > 0 ? sId : null,
        level: 1,
        memberUserIds: values.memberUserIds ? values.memberUserIds.join(',') : ''
      })
      if (res.code === 0) {
        MessageFu.success(sId > 0 ? '编辑成功' : '新增成功')
        succToLookFu(res.data.id)
        closeFu()
      }
    },
    [closeFu, sId, succToLookFu]
  )

  return (
    <Modal
      wrapClassName={styles.D2edit}
      open={true}
      title={sId > 0 ? '编辑' : '新增'}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='D2aMain'>
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name='basic'
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <Form.Item
            label='仓库名称'
            name='name'
            rules={[{ required: true, message: '请输入仓库名称' }]}
          >
            <Input maxLength={30} showCount placeholder='请输入内容' />
          </Form.Item>

          <Form.Item
            label='仓库编码'
            name='num'
            rules={[{ required: true, message: '请输入仓库编码' }]}
          >
            <Input maxLength={30} showCount placeholder='请输入内容' />
          </Form.Item>

          <Form.Item
            label='仓库负责人'
            name='managerUserId'
            rules={[{ required: true, message: '请选择仓库负责人' }]}
          >
            <Select
              placeholder='请选择'
              options={userList.map(v => ({ value: v.id, label: v.realName || v.userName }))}
            />
          </Form.Item>

          {/* 库保员 */}
          <Form.Item label='库保员' name='memberUserIds'>
            <Select
              showSearch={false}
              mode='multiple'
              allowClear
              style={{ width: '100%' }}
              placeholder='请选择'
              options={userList.map(v => ({ value: v.id, label: v.realName || v.userName }))}
            />
          </Form.Item>

          <Form.Item label='仓库说明' name='description'>
            <TextArea maxLength={500} showCount placeholder='请输入内容' />
          </Form.Item>

          <Form.Item label='仓库状态' name='enable' rules={[{ required: true, message: '' }]}>
            <Radio.Group>
              <Radio value={1}>启用</Radio>
              <Radio value={0}>禁用</Radio>
            </Radio.Group>
          </Form.Item>

          {/* 确定和取消按钮 */}
          <br />
          <Form.Item wrapperCol={{ offset: 9, span: 16 }}>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
            &emsp;
            <MyPopconfirm txtK='取消' onConfirm={closeFu} />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  )
}

const MemoD2edit = React.memo(D2edit)

export default MemoD2edit
