import React, { useState, useEffect } from 'react';
import { Modal, Form, InputNumber, Checkbox, Switch } from 'antd';
import { deepClone } from '@/utils/utils';
import styles from '../../style.less';
import { apiProductStock } from '../../service';
import { isIntegerNotZero } from '@/utils/validator';

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

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

  const onChangeMaxStock = 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;
    options.confirm({
      type: 7,
      ...params,
    });
  };

  const getStockInfo = async () => {
    const res = await apiProductStock({
      skuId: options.skuIds[0],
      shopId: options.shopId,
    });
    if (res && res.code === '0000' && res.businessCode === '0000' && res.data) {
      const info = res.data;
      form.setFieldsValue({
        autoStockStep: info.autoStockStep,
        productStock: info.stock,
        autoStock: info.autoStock === 1,
      });
      setMaxStock(info.autoStockStep);
      setIsChecked(info.autoStock === 1);
    }
  };

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

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

  useEffect(() => {
    if (options.visible) {
      setStockType(0);
      setMaxStock(0);
      setIsChecked(false);
      form.resetFields();
      if (options.skuIds && options.skuIds.length === 1) {
        getStockInfo();
      }
    }
  }, [options.visible]);

  const maxStockRule = [{ validator: isIntegerNotZero, message: '请输入大于0的整数' }];
  if (isChecked || stockType === 2) {
    maxStockRule.push({ required: true, message: '请输入最大库存!' });
  }

  return (
    <Modal
      visible={options.visible}
      title="修改库存"
      onOk={handleOk}
      maskClosable={false}
      keyboard={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: '请输入剩余库存!' },
            { validator: isIntegerNotZero, message: '请输入大于0的整数' },
          ]}
        >
          <InputNumber
            min={0}
            max={999999999}
            className={styles['stock-box--inputnum']}
            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={maxStockRule}>
          <InputNumber
            min={0}
            max={999999999}
            className={styles['stock-box--inputnum']}
            onChange={onChangeMaxStock}
          />
        </Form.Item>
        <Form.Item label="自动补足" name="autoStock">
          <Switch
            checkedChildren="开启"
            checked={isChecked}
            unCheckedChildren="关闭"
            onChange={setIsChecked}
          />
        </Form.Item>
      </Form>
      <div className={styles['stock-box--red']}>修改成功后，原库存将被替换，请谨慎操作</div>
    </Modal>
  );
};

export default StockModal;
