import React, { useState } from 'react';
import { Form, Button, Col, Drawer, Row, Input } from 'antd';

import { TableListItem } from '../data';


export interface FormValueType extends Partial<TableListItem> {
  id?: number,
  levelName?: string,
}

export interface UpdateFormProps {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => void;
  updateModalVisible: boolean;
  values: Partial<TableListItem>;
}

const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  const [formVals, setFormVals] = useState<FormValueType>({
    id: props.values.id,
    levelName: props.values.levelName
  });

  const [form] = Form.useForm();

  const {
    onSubmit: handleUpdate,
    onCancel: handleUpdateModalVisible,
    updateModalVisible,
    values,
  } = props;

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields();

    setFormVals({ ...formVals, ...fieldsValue });
    
    handleUpdate({ ...formVals, ...fieldsValue });
  };

  return (
    <Drawer
      title={values.id?`编辑`:`添加`}
      width={520}
      onClose={() => handleUpdateModalVisible(false, values)}
      visible={updateModalVisible}
      bodyStyle={{ paddingBottom: 80 }}
      footer={
        <div
          style={{
            textAlign: 'right',
          }}
        >
          <Button onClick={() => handleUpdateModalVisible(false, values)} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button onClick={handleSubmit} type="primary">
            保存
          </Button>
        </div>
      }
    >
      <Form layout="vertical" form={form} initialValues={formVals}>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name="levelName"
              label="级别"
              rules={[{ required: true, message: '请填写级别' }]}
            >
              <Input />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Drawer>
  );
};

export default UpdateForm;
