import React, { useState, useEffect } from 'react';
import { Modal, Form, Input, Checkbox, Radio, Switch } from 'antd';
import { deepClone } from '@/utils/utils';
import styles from '../../style.less';

const StockModal = options => {
  const [stockType, setStockType] = useState(0);
  const [maxStock, setMaxStock] = useState(0);
  const [form] = Form.useForm();

  const onChangeType = v => {
    setStockType(v === stockType ? 0 : v);
    if (v === 1) {
      form.setFieldsValue({
        productStock: 0,
      });
    }
  };

  const onChangeMaxStock = ({ target: { value } }) => {
    setMaxStock(value);
  };

  const handleCancel = () => {
    options.cancel(false);
  };
  const handleOk = async () => {
    const values = await form.validateFields();
    const params = deepClone(values);
    params.autoStock = values.autoStock ? 1 : 0;
    console.log('values :>> ', values);
    options.confirm({
      type: 7,
      ...values,
    });
  };

  const initialValues = Object.assign(
    {
      productStock: '',
      autoStockStep: '',
      autoStock: false,
    },
    options.initialValues,
  );

  useEffect(() => {
    if (stockType === 2) {
      form.setFieldsValue({
        productStock: maxStock,
      });
    }
  }, [maxStock, stockType]);

  return (
    <Modal
      visible={options.visible}
      title="修改库存"
      onOk={handleOk}
      maskClosable={false}
      confirmLoading={options.loading}
      destroyOnClose
      onCancel={handleCancel}
    >
      <Form
        name="basic"
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        initialValues={initialValues}
        autoComplete="off"
        className={styles['stock-box']}
      >
        <Form.Item
          label="剩余库存"
          name="productStock"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 8 }}
          rules={[{ required: true, message: '请输入剩余库存!' }]}
        >
          <Input type="number" disabled={stockType > 0} />
        </Form.Item>
        <div className={styles['stock-box--btns']}>
          <Checkbox checked={stockType === 1} onChange={() => onChangeType(1)}>
            清零
          </Checkbox>
          <Checkbox checked={stockType === 2} onChange={() => onChangeType(2)}>
            最大
          </Checkbox>
        </div>
        <Form.Item
          label="最大库存"
          name="autoStockStep"
          rules={[{ required: true, message: '请输入最大库存!' }]}
        >
          <Input type="number" onChange={onChangeMaxStock} />
        </Form.Item>
        <Form.Item label="自动补足" name="autoStock">
          <Switch checkedChildren="开启" unCheckedChildren="关闭" />
        </Form.Item>
      </Form>
      <div className={styles['stock-box--red']}>修改成功后，原库存将被替换，请谨慎操作</div>
    </Modal>
  );
};

export default StockModal;
