import React, {
   useContext
} from 'react';
import { Form, Input, Button,  message, Space } from 'antd';
import apiObj from '@api/index';
import { getCookie,setCookie } from '@utils/index';
import DrugContext from './Drug-context';
const { post, api } = apiObj;

function AddDrug(props) {
  
  const [form] = Form.useForm();
  const { type, formData} = useContext(DrugContext);
  const initialValues = formData;

  const onFinish = values => {
    let params = values
    if (type == 3) {
	  params.id=initialValues.id
      upDrugById(params)
    } else {
      addDrug(params)
    }

  };
  function addDrug(param) {
    const hisId = getCookie("hospitalId");
	const params ={
		hospitalId:hisId,
		...param
	}
	post(api.addDrug, params).then((res) => {
      if (res.data.code === 200) {
        props.DrugChange()
        message.success(res.data.message);
      } else {
        message.error(res.data.message);
      }
    })
  }
  function upDrugById(param) {
	  const hisId = getCookie("hospitalId");
	  const params ={
	  	hospitalId:hisId,
	  	...param
	  }
    post(api.upDrugById, params).then((res) => {
      if (res.data.code === 200) {
        props.DrugChange()
        message.success(res.data.message);
      } else {
        message.error(res.data.message);
      }
    })
  }
  function cancel() {
  	props.cancel()
  }
  
  function onValuesChange() {
  	props.isChange(form.isFieldsTouched())
  }

  return (
    <>
      <Form
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 16 }}
        form={form}
        name="register"
        onFinish={onFinish}
        initialValues={initialValues}
		onValuesChange={onValuesChange}
      >

        <Form.Item
          name="name"
          label="医院药品名称"
          rules={[
            {
              required: true,
              message: '请输入医院药品名称',
            },
          ]}
        >
          {type == 3 ?
		    <Input  autoComplete='off'/>
            :
            <Input placeholder="请输入" autoComplete='off'/>
          }

        </Form.Item>
		<Form.Item
		  name="approvalNum"
		  label="国药准字"
		>
		  {type == 3 ?
		    <Input  autoComplete='off'/>
		    :
		    <Input placeholder="请输入" autoComplete='off'/>
		  }
		
		</Form.Item>
          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Space size="middle">
              <Button htmlType="button" onClick={e => cancel()}>
                取消
            </Button>
              <Button type="primary" htmlType="submit">
                保存
            </Button>
            </Space>
          </Form.Item>

      </Form>
    </>
  );
}

export default AddDrug;