import React, { useState, useEffect } from 'react';
import { Button, Checkbox, Card, Form, Input, notification } from 'antd';
import { addPackage, updataPackage } from '@/services/package';

export default (props) => {
  const { current, onChange } = props;

  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);

  const onFinish = (values) => {
    setLoading(true);

    const data = current.id ? { ...current, ...values } : values;
    const func = current.id ? updataPackage : addPackage;
    
    func(data, current.id).then(res => {
      setLoading(false);
      onChange(res);
      notification.success({ message: '操作成功' })
    }).catch(() => {
      setLoading(false);
    });
  }

  useEffect(() => {
    form.setFieldsValue({
      name: current.name,
      unit: current.unit,
    });
  }, [form, current])

  return (
    <Card>
      <Form
        form={form}
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="套餐名称"
          name="name"
          rules={[{ required: true, message: '请输入套餐名称' }]}
        >
          <Input placeholder='请输入套餐名称' />
        </Form.Item>

        <Form.Item
          label="套餐单位"
          name="unit"
        >
          <Input placeholder='请输入套餐单位' />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit" loading={loading}>
            保存
          </Button>
        </Form.Item>
      </Form>
    </Card>
  )
}
