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

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 { 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,
    });
  };
  // 勾选库存设置
  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;
    // 回调库存
    modifiedInventory(type, idx, values);
    setConfirmLoading(true);
    setTimeout(() => {
      setOpenRepertory(false);
      setConfirmLoading(false);
    }, 1000);
  };

  const handleCancel = () => {
    setOpenRepertory(false);
  };
  useEffect(() => {
    if (item?.serviceItem) {
      const { productStock = 1, autoStock = 0, maxStock = 2 } = item?.serviceItem;
      const params = {
        productStock,
        autoStock: +autoStock === 1,
        maxStock,
      };
      switch (type) {
        case 'all': // 统一设置
          form.setFieldsValue(params);
          break;
        case 'multi': // 多规格设置
          form.setFieldsValue(params);
          break;
        case 'singular': // 单规格设置
          // setInitialValues(params);
          form.setFieldsValue(params);
          break;
        default:
          break;
      }
    }
  }, [openRepertory, item]);
  return (
    <>
      {openRepertory && (
        <Modal
          title="修改库存"
          visible={openRepertory}
          onOk={handleOk}
          confirmLoading={confirmLoading}
          onCancel={handleCancel}
        >
          <Form form={form} initialValues={initialValues} onValuesChange={getFormValues}>
            <Form.Item className={styles.itemInlineModal}>
              <Form.Item
                name="productStock"
                label="剩余库存"
                style={{
                  display: 'flex',
                  marginRight: '8px',
                }}
                rules={[{ required: true, message: '请填写剩余库存' }]}
              >
                <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>
            <Form.Item
              name="maxStock"
              label="最大库存"
              rules={[{ required: true, message: '请填写最大库存' }]}
            >
              <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);
