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($t('max.stock.cannot.be.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={$t('edit.inventory')}
          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={$t('remaining.stock')}
                  style={{
                    display: 'flex',
                    marginRight: '8px',
                  }}
                  rules={[
                    { required: true, message: $t('enter.remaining.stock') },
                    {
                      validator: isIntegerNotZero,
                      type: 'number',
                      message: $t('enter.integer.0'),
                    },
                  ]}
                >
                  <InputNumber
                    min={0}
                    max={999999999}
                    style={{ width: 200, display: 'inline-block' }}
                    placeholder={$t('input.required')}
                  />
                </Form.Item>
                <Form.Item style={{ width: 200, display: 'inline-block' }}>
                  <Radio.Group value={repertoryState} onChange={onChangeSetRepertory}>
                    <Radio.Button value="0">{$t('clear')}</Radio.Button>
                    <Radio.Button value="1">{$t('max')}</Radio.Button>
                  </Radio.Group>
                </Form.Item>
              </Form.Item>
            </Space>

            <Form.Item
              name="maxStock"
              label={$t('max.stock')}
              rules={[
                { required: !isRequired, message: $t('enter.max.stock') },
                {
                  validator: isIntegerNotZero,
                  type: 'number',
                  message: $t('enter.integer.0'),
                },
              ]}
            >
              <InputNumber
                min={0}
                max={999999999}
                style={{ width: 200 }}
                placeholder={$t('input.required')}
                onChange={onChangeMaxStock}
              />
            </Form.Item>
            <Form.Item name="autoStock" label={$t('autoreplenish')} valuePropName="checked">
              <Switch
                checkedChildren={$t('enable')}
                unCheckedChildren={$t('close')}
                // defaultChecked
                onChange={onChangeAutoStock}
              />
            </Form.Item>
          </Form>
          <div className={styles.textStyle}>{$t('warning.original.inventory.will.be.overwritten.after.edit')}</div>
        </Modal>
      )}
    </>
  );
};

export default forwardRef(AddRepertoryModal);
