import React, { useState } from 'react';
import { Form, Button, Input, Col, Drawer, Row } from 'antd';
import { TableListItem } from '../data.d';

export interface FormValueType extends Partial<TableListItem> {
  id?: number,
  userName?: string,
  userNo?: string,
  password?: 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,
    userNo: props.values.userNo,
    userName: props.values.userName,
    password: props.values.password,
  });

  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={12}>
            <Form.Item
              name="userNo"
              label="员工编号"
              rules={[{ required: true, message: '请输入员工编号' }]}
            >
              <Input placeholder="请输入员工编号" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="userName"
              label="姓名"
              rules={[{ required: true, message: '请输入姓名' }]}
            >
              <Input placeholder="请输入姓名" />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={16}>
          <Col span={24}>
            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
          </Col>
        </Row>
      </Form>
    </Drawer>
  );
};

export default UpdateForm;
