import React,{ forwardRef , useCallback , useEffect, useState } from 'react';
import './Index.scss';
import { Form , Input , Radio , Checkbox , Button } from "antd";
import UploadImage from './Component/UploadImage';
import axios from 'axios';
const port = window.location.port;
const hostname = window.location.hostname;
export default Form.create()(
  forwardRef(({ form , showNotification , history })=>{
    const [ image , setImage ] = useState(undefined);
    const [ imageFlag , setImageFlag] = useState(false);
    const [ descNum ,setDescNum ] = useState(0);

    const { getFieldDecorator, validateFields , setFieldsValue } = form;
    const radioStyle = {
      display: 'block',
      height: '30px',
      lineHeight: '30px',
    }
    const helper = useCallback(
      (label, name, rules, widget, isRequired = true) => (
        <React.Fragment>
          <span className={isRequired ? "lables must ": "lables"}>{label}</span>
          <Form.Item>
            {getFieldDecorator(name, { rules, validateFirst: true })(widget)}
          </Form.Item>
        </React.Fragment>
      ),
      []
    );

    // 获取上传的图片
    function getImage(image){
      setImage(image);
      setImageFlag(false);
    }

    // 创建组织
    function createOrganize(){
      validateFields((error,values)=>{
        if(!error){
          if(!image){
            setImageFlag(true);
            return;
          }
          const url = `/organizations.json`;
          axios.post(url,{
            ...values,image
          }).then(result=>{
            if(result && result.data){
              showNotification("组织创建成功！");
              history.push(`/organize/${result.data.name}`);
            }
          }).catch(error=>{})
        }
      })
    }

    useEffect(()=>{
      setFieldsValue({
        visibility:"common"
      })
    },[])

    function checkname(rule, value, callback){
      if(!value){
        callback();
      }
      if(value && !value.match(/^[a-zA-Z][a-zA-Z0-9_-]{3,19}$/)){
        callback("只能使用以字母开头，包含字母、数字、下划线、横杠等，长度4到20个字符");
      }
      callback();
    }

    return(
        <div className="main" style={{padding:"0px",border:"none"}}>
          <div className="teamBox">
            <p className="teamBox-title">新建组织</p>
            <Form className="teamBox-form">
              {helper(
                <span>组织账号：</span>,
                "name",
                [
                  { required: true, message: "请输入组织账号" },
                  {
                    validator:checkname
                  }
                ],
                <Input
                  addonBefore={`https://`+ port ? `${hostname}:${port}/organize`:`${hostname}/organize`}
                  placeholder="组织账号" maxLength={100}
                />
              )}
              {helper(
                <span>组织名称：</span>,
                "nickname",
                [{ required: true, message: "请输入组织名称" }],
                <Input
                  placeholder="请输入组织名称" maxLength={100}
                />
              )}
              <div className="pr">
                <span className="toprightNum">{descNum}/200</span>
                {helper(
                  '组织描述',
                  "description",
                  [{ required: true, message: "请输入组织描述" }],
                  <Input.TextArea 
                    autoSize={{ minRows: 3, maxRows: 5 }}
                    placeholder="请输入组织描述" maxLength={200} 
                    onChange={(e)=>{setDescNum(e.target.value ? e.target.value.length :0)}}
                  />
                )}
              </div>
              
              {helper(
                '所在地区',
                "location",
                [],
                <Input placeholder="请输入地址" maxLength={50}/>,false
              )}
              {helper(
                '可见性',
                "visibility",
                [{ required: true, message: "请选择可见性" }],
                <Radio.Group name="exposure">
                  <Radio style={radioStyle} value="common" key={1}>公开</Radio>
                  <Radio style={radioStyle} value="limited" key={2}>受限<span className="color-grey-8">（仅对登录用户可见）</span></Radio>
                  <Radio style={radioStyle} value="privacy" key={3}>私有<span className="color-grey-8">（仅对组织成员可见）</span></Radio>
                </Radio.Group>
              )}
              
              <p className="font-16 lables must">选择头像</p>
              <UploadImage getImage={getImage}/>
              {imageFlag && <p className="color-red" style={{marginTop:"-10px"}}>请上传头像</p> }
              
              {helper(
                '权限',
                "repo_admin_change_team_access",
                [],
                <Checkbox value="1" key={1}>项目管理员可以添加或移除团队的访问权限</Checkbox>,false
              )}
            </Form>
          </div>
          <p className="mt20">
            <Button type="primary" className="mr30" onClick={createOrganize}>创建组织</Button>
            <Button className="grey">取消</Button>
          </p>
        </div>
    )
  })
)