import React, { useState , forwardRef, useEffect } from 'react';
import { Form , Modal , Input , Radio } from 'antd';
import Axios from 'axios';
import CheckProfile from '../Component/ProfileModal/Profile';
function AddProjectModal(props){
  const { getFieldDecorator, validateFields , setFieldsValue } = props && props.form;
  const [ visible , setVisible ] = useState(false);

  useEffect(()=>{
    if(!visible){
      setFieldsValue({
        code:undefined,
        role:"developer"
      })
    }
  },[visible])

  function onOk() {
    validateFields((error,values)=>{
      console.log(error)
      if(!error){
        const url = `/applied_projects.json`;
        Axios.post(url,{
          applied_project:{
            ...values
          }
        }).then(result=>{
          if(result && result.data){
            setVisible(false);
            props.showNotification("申请加入项目成功，等待审核!");
          }
        }).catch(error=>{})
      }
    })
  }
  function checkValue(rule, value, callback){
    if(!value){
      callback("请输入6位数的邀请码");
    }else{
      if(value.length < 6 || value.length > 6){
        callback("请输入6位数的邀请码");
      }
    }
    callback();
  }       

  return(
    <React.Fragment>
      <Modal
        title="加入项目"
        width="480px"
        visible={visible}
        centered={true}
        onOk={onOk}
        onCancel={()=>setVisible(false)}
      >
        <Form layout={'inline'} className="inviteForm">
          <Form.Item label="项目邀请码">
            {getFieldDecorator("code",{
              rules:[
                {required:true,message:" "},
                {validator:checkValue}
              ]
            })(
              <Input placeholder="请输入6位项目邀请码" autoComplete={"off"} maxLength={6} style={{width:"300px"}}/>
            )}
          </Form.Item>
          <Form.Item label="选择角色">
            {getFieldDecorator("role",{
              rules:[{required:true,message:"请选择角色"}]
            })(
              <Radio.Group>
                <Radio value="manager">管理员</Radio>
                <Radio value="developer">开发者</Radio>
                <Radio value="reporter">报告者</Radio>
              </Radio.Group>
            )}
          </Form.Item>
        </Form>
      </Modal>
      <CheckProfile {...props} sureFunc={()=>setVisible(true)}>加入项目</CheckProfile>
    </React.Fragment>
  )
}
export default Form.create()(forwardRef(AddProjectModal));