import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Modal, InputNumber, notification, Input, Radio } from 'antd';
import React, { useState } from 'react';
import { apiCreateGoodsLog } from '../service';
import styles from '../style.less';
import { isNumberSection } from '@/utils/validator';

const UpdateStock = props => {
  const { getFieldDecorator, validateFields, resetFields, getFieldValue } = props.form;
  const valueInfo = props.info;

  const [loading, setLoading] = useState(false);

  const submit = async () => {
    validateFields(async (err, { stock, changeReason, changeType }) => {
      if (err) return;
      setLoading(true);
      const params = {
        afterChange: stock,
        supplierId: valueInfo.supplierId,
        productIdType: 2,
        changeType,
        changeReason,
        productIds: props.skuIds,
      };
      console.log('params :>> ', params);
      const res = await apiCreateGoodsLog(params);
      if (res?.businessCode === '0000') {
        notification.success({ message: '库存更改申请已提交！' });
        props.onCancel('success');
        resetFields();
      }
      setLoading(false);
    });
  };
  const onCancel = () => {
    props.onCancel();
    resetFields();
  };
  const formItemLayout = {
    labelCol: {
      span: 7,
    },
    wrapperCol: {
      span: 15,
    },
  };

  const validatorCallback = (rule, value, callback) => {
    // 减库存存时，校验可售库存-输入值>=0,即可售库存不可为负；
    const changeType = getFieldValue('changeType');
    const increment = valueInfo.marketableStock - value;
    console.log('value :>> ', value, valueInfo.marketableStock);
    console.log('valueInfo :>> ', valueInfo, increment);
    return +changeType === 29 && increment < 0 ? callback(new Error(rule.message)) : callback();
  };

  return (
    <Modal
      title="修改库存"
      visible={props.visible}
      okButtonProps={{ loading, disabled: valueInfo.status === 1 }}
      onCancel={onCancel}
      onOk={submit}
      width={500}
    >
      <Form {...formItemLayout}>
        {valueInfo.curStock ? (
          <Form.Item label="当前库存:">
            <span>{valueInfo.curStock}</span>
          </Form.Item>
        ) : (
          <Form.Item label="可修改库存商品数:">
            <span>{props.skuIds.length}</span>
          </Form.Item>
        )}
        <Form.Item label="变更类型:">
          {getFieldDecorator('changeType', {
            rules: [{ required: true, message: '请选择类型!' }],
            initialValue: valueInfo.changeType || 28,
          })(
            <Radio.Group disabled={valueInfo.status === 1}>
              <Radio value={28}>增库存</Radio>
              <Radio value={29}>减库存</Radio>
              <Radio value={30}>使用新值</Radio>
            </Radio.Group>,
          )}
          <div className={styles.stockTip}>库存变更审批通过后生效</div>
        </Form.Item>
        <Form.Item label="库存数:">
          {getFieldDecorator('stock', {
            rules: [
              { required: true, message: '请输入库存!' },
              { validator: validatorCallback, message: '减库存,输入库存数不可大于可售库存！' },
              { validator: isNumberSection, min: 1, max: 500, message: '请输入1-500的整数' },
            ],
            validateTrigger: ['onSubmit', 'onChange'],
            initialValue: valueInfo.stock,
          })(
            <InputNumber
              min={0}
              precision={0}
              placeholder="请输入库存"
              disabled={valueInfo.status === 1}
              style={{ width: 200 }}
            />,
          )}
        </Form.Item>
        <Form.Item label="变更原因:">
          {getFieldDecorator('changeReason', {
            rules: [{ required: true, message: '请输入变更原因!' }],
            initialValue: valueInfo.changeReason,
          })(<Input.TextArea disabled={valueInfo.status === 1} maxLength={50} />)}
        </Form.Item>
        {valueInfo.stateDesc && (
          <div className={styles.stockErrMsg}>
            {valueInfo.stateDesc}：{valueInfo.rejectReason}
          </div>
        )}
      </Form>
    </Modal>
  );
};

export default Form.create()(UpdateStock);
