import React, { useEffect } from 'react';
import { Form, InputNumber, Modal, notification } from 'antd';
import { isCheckPriceTwoDecimal } from '@/utils/validator';
import { apiMealInfoUpdate } from '../service';

const SaleDateModal = props => {
  const [form] = Form.useForm();

  const layout = {
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
  };

  // 关闭弹窗
  const handleCancel = () => {
    props.handleClose(false);
  };

  // 提交
  const handleConfirm = async () => {
    const res = await form.validateFields();
    if (props.id) {
      const params = {
        id: props.id,
        enterprisePrice: res.price,
      };
      await apiMealInfoUpdate(params);
      notification.success({ message: '保存成功' });
    }
    handleCancel();
    props.handleRefresh(res.price);
  };

  useEffect(() => {
    if (props.visible) {
      const price = props.item?.enterprisePrice || props.item?.activityPrice || null;
      form.setFieldsValue({ price });
    }
  }, [props.visible]);

  return (
    <Modal
      title="修改企业商品价格"
      open={props.visible}
      destroyOnClose
      maskClosable={false}
      width="400px"
      okText="保存"
      onOk={handleConfirm}
      onCancel={handleCancel}
    >
      <Form name="basicInfo" {...layout} form={form}>
        <Form.Item
          label="企业商品价格"
          name="price"
          rules={[
            { required: true, message: '请输入企业商品价格!' },
            { validator: isCheckPriceTwoDecimal, message: '请输入正确的价格' },
          ]}
        >
          <InputNumber addonAfter="元" max={99999.99} />
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default SaleDateModal;
