import React, { forwardRef, useCallback, useState , useEffect } from "react";
import activate from "../Images/activate.png";
import { Blueback , AlignCenter } from "../Component/layout";
import PasswordAuthority from "../Component/PasswordAuthority";
import styled from "styled-components";
import { Form, Input , Spin , Modal } from "antd";
import axios from "axios";

const P = styled.p`
   {
    width: 230px;
    line-height: 30px;
    font-size: 16px;
    color: #333;
    text-align: center;
    margin-top: 30px;
    margin-bottom: 30px !important;
  }
`;
function About(props, ref) {
  const { form: { getFieldDecorator, validateFields , setFieldsValue } } = props;
  const [isSpining, setIsSpining] = useState(true);
  const [ authorityValBox , setAuthorityValBox ] = useState(false);
  const [ authorityVal , setAuthorityVal ] = useState(undefined);
  const [ authorityValFlag , setAuthorityValFlag ] = useState(false);
  //0: 标识未开启devops
  //1: 标识用户已填写了云服务器相关信息，但并未开启认证
  const [step, setStep] = useState(undefined);
  // step大于1时：为true，不能再修改服务器信息
  const owner = props.match.params.owner;
  const projectsId = props.match.params.projectsId;


  const AuthorLogin = props.author && props.author.login;
  const CurrentLogin = props.current_user && props.current_user.login;
  useEffect(()=>{
    if(CurrentLogin === AuthorLogin){
      auth('get');
    }else{
      setIsSpining(false);
    }
  },[AuthorLogin,CurrentLogin])

  function auth(type){
    const url = `/${owner}/${projectsId}/ci_authorize.json`;
    axios({
      method:`${type}`,
      url
    }).then(result=>{
      if(result && result.data ){
        setIsSpining(false);
        setStep(result.data.step);
        setFieldsValue({...result.data.cloud_account});
      }
    }).catch(error=>{
      console.log(error);
    })
  }

  const helper = useCallback(
    (label, name, rules, widget, isRequired) => (
      <React.Fragment>
        <span className={isRequired ? "required" : ""}>{label}</span>
        <Form.Item>
          {getFieldDecorator(name, { rules, validateFirst: true })(widget)}
        </Form.Item>
      </React.Fragment>
    ),
    []
  );
  // 下一步
  function goStep() {
    validateFields((error, values) => {
      if (!error) {
        if(step > 0){
          setAuthorityValBox(true);
        }else{
          setIsSpining(true);
          const url = `/${owner}/${projectsId}/cloud_accounts.json`;
          axios.post(url, {...values,ip_num:values.ip}).then((result) => {
            setIsSpining(false);
            if (result && result.data.redirect_url) {
              props.showNotification("服务器信息配置完成！");
              setStep(1);
              setAuthorityValBox(true);
            }
          })
          .catch((error) => {
            console.log(error);
            setIsSpining(false);
          });
        }
      }
    });
  }

  // 开始激活
  function startActive(){
    setIsSpining(true);
    const url = `/${owner}/${projectsId}/activate.json`;
    axios.post(url).then(result=>{
      setIsSpining(false);
      if(result && result.data.status === 0){
        props.history.push(`/projects/${owner}/${projectsId}/devops/dispose`);
        // 需要将顶部的open_devops修改
        let { changeOpenDevops } = props;
        changeOpenDevops && changeOpenDevops(true);
      }
    }).catch(error=>{
      console.log(error);
      setIsSpining(false);
    })
  }
  // 取消授权-登录密码的输入
  function cancelAuthority(){
    setAuthorityValBox(false);
  }
  // 确认授权
  function okAuthority(step){
    setAuthorityValBox(false);
    setStep(step);
  }
  return (
    <Spin spinning={isSpining}>
      <PasswordAuthority authorityValBox={authorityValBox} successFunc={okAuthority} cancelFunc={cancelAuthority}></PasswordAuthority>
      <div className="activatePanel">
        <img src={activate} alt="" width="250px" />
        <P>定义DevOps工作流，帮助您检测bug、发布代码…</P>
        {
          CurrentLogin !== AuthorLogin &&  (step === undefined || (step && step < 1)) &&
          <div className="noOperation">DevOps开启功能暂未对项目创建者以外的角色开放，可以联系项目创建者进行开启，开启后便可查看构建信息。</div>
        }
        <a href={"https://forum.trustie.net/forums/3080/detail"} target="_blank" style={{ color: "#5091FF"}}>
          了解什么是DevOps？
        </a>
        <a href={"https://forum.trustie.net/forums/3110/detail"} target="_blank" style={{ color: "#5091FF"}}>
          如何使用DevOps？
        </a>
        {
          AuthorLogin === CurrentLogin ?
          <React.Fragment>
            { step <=1 ?
            <React.Fragment>
              <Input.Password style={{display:'none'}} size="large" />
              <Form style={{marginTop:"20px"}}>
                <p className="mb20" style={{width:"370px"}}>请仔细核对您的服务器信息，一旦确认提交将无法修改</p>
                {helper(
                  "服务器IP地址：",
                  "ip",
                  [{ required: true, message: "请输入服务器IP地址" }],
                  <Input
                    placeholder="请输入服务器IP地址"
                    style={{ width: "368px" }}
                    size="large"
                    disabled={step > 0}
                  />,
                  true
                )}
                {helper(
                  "服务器用户名：",
                  "account",
                  [{ required: true, message: "请输入服务器用户名" }],
                  <Input placeholder="请输入服务器用户名" size="large" disabled={step > 0}/>,
                  true
                )}
                {helper(
                  "服务器密码：",
                  "secret",
                  [{ required: true, message: "请输入服务器密码" }],
                  <Input.Password placeholder="请输入服务器密码" size="large" disabled={step > 0}/>,
                  true
                )}
              </Form>
              <Blueback onClick={goStep}>下一步</Blueback>
            </React.Fragment>
            :""}
            {step > 1 &&
              <div style={{textAlign:'center',marginTop:"20px"}}>
                <Blueback onClick={startActive} className="mt20">开始激活</Blueback>
              </div>
            }
          </React.Fragment>
          :""
        }
      </div>
    </Spin>
  );
}
export default Form.create()(forwardRef(About));
