import React, { useCallback, useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, Form, FormInstance, Input, InputNumber, 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'
// import { findMissingIds } from '@/pages/Z_system/Z3flowSet/Z3edit/data'

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

function D2edit({ sId, succToLookFu, closeFu, isLook }: Props) {
  // 获取用户列表
  const dispatch = useDispatch()

  const [loding, setLoding] = useState(false)

  useEffect(() => {
    dispatch(
      getUserListAPI(
        {
          pageNum: 1,
          pageSize: 99999,
          searchKey: ''
        },
        () => {
          setLoding(true)
        }
      )
    )
  }, [dispatch])

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

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

  const getInfoFu = useCallback(
    async (id: number) => {
      if (loding) {
        const res = await D2_APIgetInfo(id)

        if (res.code === 0) {
          const obj = res.data

          if (obj.memberUserIds)
            obj.memberUserIds = obj.memberUserIds.split(',').map((v: string) => Number(v))
          else obj.memberUserIds = []

          // console.log('---------', obj)

          // if (!userList.some(v => v.id === obj.managerUserId)) {
          //   obj.managerUserId = null
          // }

          // if (obj.memberUserIds && obj.memberUserIds.length) {
          //   const isDelIdArrRef = findMissingIds(userList, obj.memberUserIds)
          //   if (isDelIdArrRef && isDelIdArrRef.length) {
          //     const userIds = new Set(isDelIdArrRef.map(u => u))
          //     const copyUserIds = obj.memberUserIds.filter((id: any) => !userIds.has(id))
          //     obj.memberUserIds = copyUserIds
          //   }
          // }

          FormBoxRef.current?.setFieldsValue(res.data)
        }
      }
    },
    [loding]
  )

  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={isLook ? '查看' : 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 readOnly={isLook} maxLength={30} showCount placeholder='请输入内容' />
          </Form.Item>

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

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

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

          <Form.Item label='仓库说明' name='description'>
            <TextArea
              readOnly={isLook}
              maxLength={500}
              showCount
              placeholder={isLook ? '（空）' : '请输入内容'}
            />
          </Form.Item>

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

          <Form.Item
            label='排序值'
            name='sort'
            initialValue={999}
            rules={[{ required: true, message: '请输入排序值' }]}
          >
            <InputNumber
              readOnly={isLook}
              min={0}
              max={999}
              style={{ width: '100%' }}
              placeholder='请输入1-999的数字。数字越小，排序越靠前'
            />
          </Form.Item>

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

const MemoD2edit = React.memo(D2edit)

export default MemoD2edit
