import React, { useState, useEffect, forwardRef, useRef, useImperativeHandle } from 'react';
import { Button, Modal, Radio, Form, InputNumber, Switch, Space, message } from 'antd';
import styles from '../common.less';
import { ENUM_SET_REPERTORY } from '../config';
import { debounce } from '@/utils/utils';
import { isCheckPriceTwoDecimal, isIntegerNotZero } from '@/utils/validator';

const AddRepertoryModal = (props, ref) => {
  const [confirmLoading, setConfirmLoading] = useState(false);
  const [openRepertory, setOpenRepertory] = useState(false);
  const [form] = Form.useForm();
  const [repertoryState, setRepertoryState] = useState('');
  const [initialValues, setInitialValues] = useState({
    productStock: 0,
    maxStock: 0,
    autoStock: false,
  });
  const [isRequired, setIsRequired] = useState(true);
  const { modifiedInventory, intactData, repertoryModel } = props;
  const { type, idx, item } = repertoryModel;
  useImperativeHandle(ref, () => ({
    // changeVal 就是暴露给父组件的方法
    setOpenRepertory: newVal => {
      setOpenRepertory(newVal);
    },
  }));
  // 自动补全
  const onChangeAutoStock = e => {
    form.setFieldsValue({
      autoStock: e ? 1 : 0,
    });
    setIsRequired(!e);
  };
  // 勾选库存设置
  const onChangeSetRepertory = e => {
    setRepertoryState(`${e.target.value}`);
    if (+e.target.value === 0) {
      form.setFieldsValue({
        productStock: 0,
      });
    } else {
      const { maxStock } = form.getFieldsValue(['maxStock']);
      form.setFieldsValue({
        productStock: maxStock,
      });
    }
  };
  // 最大库存设置
  const onChangeMaxStock = e => {
    // 已经勾选最大库存 自动更新剩余库存
    if (+repertoryState === 1) {
      form.setFieldsValue({
        productStock: e,
      });
    }
  };
  const getFormValues = debounce(() => {
    const values = form.getFieldsValue();
  }, 400);
  const handleOk = async () => {
    const values = await form.validateFields();
    values.autoStock = values.autoStock ? 1 : 0;
    if (+values.autoStock === 1 && +values.maxStock === 0) {
      message.error('最大库存不能为0');
      return;
    }
    // 回调库存
    modifiedInventory(type, idx, values);
    setConfirmLoading(true);
    setTimeout(() => {
      setOpenRepertory(false);
      setConfirmLoading(false);
    }, 1000);
  };

  const handleCancel = () => {
    setOpenRepertory(false);
  };
  useEffect(() => {
    if (item?.serviceItem) {
      const { productStock = 0, autoStock = 0, maxStock = 0 } = item?.serviceItem;
      const params = {
        productStock,
        autoStock: +autoStock === 1,
        maxStock,
      };
      form.setFieldsValue(params);
    }
  }, [openRepertory, item]);
  return (
    <>
      {openRepertory && (
        <Modal
          title="修改库存"
          visible={openRepertory}
          onOk={handleOk}
          confirmLoading={confirmLoading}
          onCancel={handleCancel}
        >
          <Form form={form} initialValues={initialValues} onValuesChange={getFormValues}>
            <Space>
              <Form.Item className={styles.itemInlineModal}>
                <Form.Item
                  name="productStock"
                  label="剩余库存"
                  style={{
                    display: 'flex',
                    marginRight: '8px',
                  }}
                  rules={[
                    { required: true, message: '请填写剩余库存' },
                    {
                      validator: isIntegerNotZero,
                      type: 'number',
                      message: '请输入大于0的整数',
                    },
                  ]}
                >
                  <InputNumber
                    min={0}
                    max={999999999}
                    style={{ width: 200, display: 'inline-block' }}
                    placeholder="请输入"
                  />
                </Form.Item>
                <Form.Item style={{ width: 200, display: 'inline-block' }}>
                  <Radio.Group value={repertoryState} onChange={onChangeSetRepertory}>
                    <Radio.Button value="0">清空</Radio.Button>
                    <Radio.Button value="1">最大</Radio.Button>
                  </Radio.Group>
                </Form.Item>
              </Form.Item>
            </Space>

            <Form.Item
              name="maxStock"
              label="最大库存"
              rules={[
                { required: !isRequired, message: '请填写最大库存' },
                {
                  validator: isIntegerNotZero,
                  type: 'number',
                  message: '请输入大于0的整数',
                },
              ]}
            >
              <InputNumber
                min={0}
                max={999999999}
                style={{ width: 200 }}
                placeholder="请输入"
                onChange={onChangeMaxStock}
              />
            </Form.Item>
            <Form.Item name="autoStock" label="自动补足" valuePropName="checked">
              <Switch
                checkedChildren="开启"
                unCheckedChildren="关闭"
                // defaultChecked
                onChange={onChangeAutoStock}
              />
            </Form.Item>
          </Form>
          <div className={styles.textStyle}>修改成功后，原库存将被替换，请谨慎操作！</div>
        </Modal>
      )}
    </>
  );
};

export default forwardRef(AddRepertoryModal);
