import React, { useEffect, useState } from 'react'
import { Modal, Form, Button, Select, Flex, InputNumber, message } from 'antd'
import { I1_APIPositionSave } from '@/store/action/Isystem/I1storageSet'
import MyPopconfirm from '@/components/MyPopconfirm'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'

interface AddPositionModalProps {
  visible: boolean
  positionOptions: any[]
  onCancel: () => void
  onSuccess: () => void
}

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

  const expandRange = (from: number, to: number) => {
    const arr = []
    for (let i = from; i <= to; i++) arr.push(i)
    return arr
  }

  const handleOk = async () => {
    try {
      const values = await form.validateFields()

      const layers = ['layer1', 'layer2', 'layer3', 'layer4']
      for (const layer of layers) {
        if (values[layer]) {
          const [from, to] = values[layer]
          if (from > to) {
            message.error(
              `${form.getFieldInstance(layer)?.props?.label || layer}的起始值不能大于结束值`
            )
            return
          }
        }
      }

      const layer1Arr = expandRange(values.layer1[0], values.layer1[1])
      const layer2Arr = expandRange(values.layer2[0], values.layer2[1])
      const layer3Arr =
        values.layer3 && values.layer3[0] !== undefined && values.layer3[1] !== undefined
          ? expandRange(values.layer3[0], values.layer3[1])
          : [null]
      const layer4Arr =
        values.layer4 && values.layer4[0] !== undefined && values.layer4[1] !== undefined
          ? expandRange(values.layer4[0], values.layer4[1])
          : [null]
      const matrix = []
      for (const l1 of layer1Arr) {
        for (const l2 of layer2Arr) {
          for (const l3 of layer3Arr) {
            for (const l4 of layer4Arr) {
              matrix.push({
                storageId: values.storageId,
                layer1: l1,
                layer2: l2,
                layer3: l3,
                layer4: l4
              })
            }
          }
        }
      }
      setLoading(true)
      const res = await I1_APIPositionSave(matrix)
      setLoading(false)
      if (res.code === 0) {
        onSuccess()
        form.resetFields()
      }
    } catch (err) {
      setLoading(false)
    }
  }

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

    form.resetFields()
  }, [dispatch, userInfo.list.length, visible, form])

  return (
    <Modal
      title='新增'
      open={visible}
      onCancel={() => {
        form.resetFields()
        onCancel()
      }}
      footer={null}
      destroyOnClose
    >
      <Form form={form} labelCol={{ span: 5 }}>
        <Form.Item
          label='库房名称'
          name='storageId'
          rules={[{ required: true, message: '请选择库房' }]}
        >
          <Select
            showSearch
            filterOption={(input, option) =>
              (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
            }
            placeholder='请选择'
            options={positionOptions}
          />
        </Form.Item>

        <Form.Item label='排' required>
          <div>
            <Flex align='center' gap='10px'>
              从
              <Form.Item
                name={['layer1', 0]}
                noStyle
                rules={[{ required: true, message: '请输入起始值' }]}
              >
                <InputNumber min={0} max={9} style={{ width: 60 }} />
              </Form.Item>
              到
              <Form.Item
                name={['layer1', 1]}
                noStyle
                rules={[{ required: true, message: '请输入结束值' }]}
              >
                <InputNumber min={0} max={9} style={{ width: 60 }} />
              </Form.Item>
            </Flex>
            <span style={{ color: '#999', fontSize: 12 }}>单字母或3位内正整数</span>
          </div>
        </Form.Item>

        <Form.Item label='列' required>
          <div>
            <Flex align='center' gap='10px'>
              从
              <Form.Item
                name={['layer2', 0]}
                noStyle
                rules={[{ required: true, message: '请输入起始值' }]}
              >
                <InputNumber min={0} max={9} style={{ width: 60 }} />
              </Form.Item>
              到
              <Form.Item
                name={['layer2', 1]}
                noStyle
                rules={[{ required: true, message: '请输入结束值' }]}
              >
                <InputNumber min={0} max={9} style={{ width: 60 }} />
              </Form.Item>
            </Flex>
            <span style={{ color: '#999', fontSize: 12 }}>单字母或3位内正整数</span>
          </div>
        </Form.Item>

        <Form.Item label='层'>
          <div>
            <Flex align='center' gap='10px'>
              从
              <Form.Item name={['layer3', 0]} noStyle>
                <InputNumber min={0} max={9} style={{ width: 60 }} />
              </Form.Item>
              到
              <Form.Item name={['layer3', 1]} noStyle>
                <InputNumber min={0} max={9} style={{ width: 60 }} />
              </Form.Item>
            </Flex>
            <span style={{ color: '#999', fontSize: 12 }}>单字母或3位内正整数</span>
          </div>
        </Form.Item>

        <Form.Item label='格'>
          <div>
            <Flex align='center' gap='10px'>
              从
              <Form.Item name={['layer4', 0]} noStyle>
                <InputNumber min={0} max={9} style={{ width: 60 }} />
              </Form.Item>
              到
              <Form.Item name={['layer4', 1]} noStyle>
                <InputNumber min={0} max={9} style={{ width: 60 }} />
              </Form.Item>
            </Flex>
            <span style={{ color: '#999', fontSize: 12 }}>单字母或3位内正整数</span>
          </div>
        </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 AddPositionModal
