import React, { forwardRef , useCallback , useEffect, useState } from 'react';
import { Form , Input , Radio ,Checkbox , Divider , Button , InputNumber } from 'antd';
import { WhiteBack , FlexAJ } from '../../Component/layout';
import Title from '../../Component/Title';
import styled from 'styled-components';
import UploadImage from '../Component/UploadImage';
import axios from 'axios';
import Modals from '../Component/Modals';

import { getImageUrl } from 'educoder';
const TextArea = Input.TextArea;

const Div = styled.div`{
  padding:20px 30px;
}`
const radioStyle = {
  display: 'block',
  height: '30px',
  lineHeight: '30px',
};
export default Form.create()(
  forwardRef(({ form , organizeDetail , showNotification , history , current_user , updateFunc })=>{
    const [ image , setImage ] = useState(undefined);
    const [ imageFlag , setImageFlag ] = useState(false);
    const [ password , setPassword ] = useState(undefined);
    const [ passwordFlag , setPasswordFlag ] = useState(false);
    const [ visible , setVisible ] = useState(false);
    const [ descNum , setDescNum ] = useState(0);
    const { getFieldDecorator , validateFields , setFieldsValue } = form;

    useEffect(()=>{
      if(organizeDetail){
        setFieldsValue({
          ...organizeDetail,
          max_repo_creation:organizeDetail.max_repo_creation===-1 ? "":organizeDetail.max_repo_creation
        })
        setImage(organizeDetail.avatar_url);
        setDescNum(organizeDetail.description ? organizeDetail.description.length : 0);
      }
    },[organizeDetail])

    const helper = useCallback(
      (label, name, rules, widget , isRequired , flag , help ) => (
        <div>
          <span className={isRequired?"required":""}>{label}</span>
          <Form.Item help={help}>
            {getFieldDecorator(name, { rules, validateFirst: true , valuePropName:flag ? "checked":"value"  })(widget)}
          </Form.Item>
        </div>
      ),
      []
    );

    // 更新
    function updateDetail(){
      validateFields((error,values)=>{
        if(!error){
          const url = `/organizations/${organizeDetail.id}.json`;
          axios.patch(url,{
            ...values,image:imageFlag ? image : undefined
          }).then(result=>{
            if(result && result.data){
              showNotification("组织信息更新成功！");
              if(values.name !== organizeDetail.name){
                console.log("false111");
                history.push(`/${values.name}/setting`);
              }
              updateFunc && updateFunc(values.name,values.description);
            }
          }).catch(error=>{})
        }
      })
    }
    function getImage(image){
      setImageFlag(true);
      setImage(image);
    }

    // 删除组织
    function deleteOrganize(){
      if(!password){
        setPasswordFlag(true);
      }else{
        setPasswordFlag(false);
        setVisible(true);
      }
    }

    function onOk(password){
      const url = `/organizations/${organizeDetail.id}.json`;
      axios.delete(url,{
        params:{ password }
      }).then(result=>{
        if(result && result.data){
          // 删除后跳转到个人中心的组织页面
          history.push(`/${current_user && current_user.login}/organizes`);
        }
      })
      setVisible(false);
    }
    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>
        <WhiteBack>
          <Title>基本设置</Title>
          <Div>
            <Form>
              {helper(
                "组织账号：",
                "name",
                [
                  { required: true, message: "请输入组织账号" },
                  {
                    validator:checkname
                  }
                ],
                <Input placeholder="请输入组织账号" disabled/>,true
              )}
              {helper(
                "组织名称：",
                "nickname",
                [{ required: true, message: "请输入组织名称" }],
                <Input placeholder="请输入组织名称" maxLength={100}/>,true
              )}
              <div className="pr">
                <span className="toprightNum">{descNum}/200</span>
                {helper(
                  "组织描述：",
                  "description",
                  [],
                  <TextArea 
                    placeholder="请输入组织名称" 
                    maxLength={200}
                    onChange={(e)=>{setDescNum(e.target.value ? e.target.value.length :0)}}
                  />
                )}
              </div>
              {helper(
                "官方网站：",
                "website",
                [],
                <Input placeholder="请输入官方网站" />
              )}
              {helper(
                '所在地区：',
                "location",
                [],
                <Input placeholder="请输入城市"/>
              )}
              {helper(
                '可见性：',
                "visibility",
                [],
                <Radio.Group>
                  <Radio value="common" style={radioStyle}>公开</Radio>
                  <Radio value="limited" style={radioStyle}>受限<span>（仅对登录用户可见）</span></Radio>
                  <Radio value="privacy" style={radioStyle}>私有<span>（仅对组织成员可见）</span></Radio>
                </Radio.Group>
              )}
              {helper(
                '权限：',
                "repo_admin_change_team_access",
                [],
                <Checkbox style={radioStyle}>项目管理员可以添加或移除团队的访问权限</Checkbox>,false,true
              )}
              <Divider/>
              {helper(
                '最大仓库数：',
                "max_repo_creation",
                [],
                <InputNumber value="-1" style={{width:"350px"}}/>,false,false,
                "当输入栏为空时，默认数量无限制"
              )}
              <p>选择头像:</p>
              <UploadImage url={getImageUrl(`/${image}`)} getImage={getImage}/>
              <Button type={"primary"} onClick={updateDetail}>更新仓库设置</Button>
            </Form>
          </Div>
        </WhiteBack>
        <WhiteBack className="padding20 mt20">
          <div className="warningBox">
            <div className="warningTitle">删除当前组织</div>
            <div className="warningContent">
              <p className="font-16 mb15">删除操作会永久清除该组织的信息，并且不可恢复！</p>
              <FlexAJ>
                <div>
                  <span className="required">密码：</span>
                  <Input type="password" placeholder="请输入当前用户的登录密码" style={{width:"350px"}} value={password} onChange={(e)=>setPassword(e.target.value)}/>
                  { passwordFlag && <span className="color-red ml10">请输入密码</span>}
                </div>
                <a className="warningDelete" onClick={deleteOrganize}>删除组织</a>
                <Modals visible={visible} okText={"确定"} cancelText={"取消"} onCancel={()=>setVisible(false)} onOk={()=>onOk(password)}> 
                  <p className="font-16 edu-txt-center">确定要删除当前组织吗？</p>
                </Modals>
              </FlexAJ>
            </div>
          </div>
        </WhiteBack>
      </div>
    )
  })
)