import React, { forwardRef, useCallback, useState , useEffect } from "react";
import activate from "../Images/activate.png";
import { AlignCenter, Blueback } from "../Component/layout";
import PasswordAuthority from "../Component/PasswordAuthority";
import styled from "styled-components";
import { Form, Input , Spin , Button } from "antd";
import ServiceModal from './ServiceModal';
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 [ authorityVal , setAuthorityVal ] = useState(undefined);
  const [ authorityValFlag , setAuthorityValFlag ] = useState(false);

  //0: 标识未开启devops
  //1: 标识用户已填写了云服务器相关信息，但并未开启认证
  const [step, setStep] = useState(0);
  
  const owner = props.match.params.owner;
  const { user } = props;
  const projectsId = props.match.params.projectsId;
  const [ disabled, setDisabled ] = useState(false);
  const [ typeFlag, setTypeFlag] = useState(false);

  const isPermission = props.projectDetail && props.projectDetail.permission && props.projectDetail.permission!=="Reporter";
  const CurrentLogin = props.current_user && props.current_user.login;
  useEffect(()=>{
    if(isPermission){
      auth('get');
    }else{
      setIsSpining(false);
    }
  },[isPermission,CurrentLogin])

  function auth(type){
    const url = `/${owner}/${projectsId}/ci_authorize.json`;
    axios({
      method:`${type}`,
      url
    }).then(result=>{
      setIsSpining(false);
      if(result && result.data ){
        setStep(result.data.step);
      }
    }).catch(error=>{
      setIsSpining(false);
      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(disabled){
          setStep(1);
        }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);
            }
          })
          .catch((error) => {
            console.log(error);
            setIsSpining(false);
          });
        }
      }
    });
  }

  // 选择服务器后调用接口，点击下一步（1是自有服务器，2是trustie服务器）
  function sureModal(type){
    if(type === 2){
      setTypeFlag(false);
      setIsSpining(true);
      const url = `/users/ci/cloud_account/trustie_bind.json`;
      axios.post(url,{
        account:user && user.login
      }).then(result=>{
        setIsSpining(false);
        if(result && result.data){
          setStep(result.data.step);
        }
      }).catch(error=>{setIsSpining(false)})
    }else{
      setTypeFlag(true);
    }
  }

  // 上一步
  function goUpStep(step){
    setTypeFlag(false);
    setStep(step);
  }

  // 输入用户密码后下一步
  function authStep(){
    if(!authorityVal){
      setAuthorityValFlag(true);
      return;
    }
    setAuthorityValFlag(false);
    setIsSpining(true);
    const url = `/users/ci/oauth_grant.json`;
    axios.get(url,{
      params:{password:authorityVal}
    }).then(result=>{
      setIsSpining(false);
      if(result && result.data.status === 0){
        setStep(result.data.step);
      }
    }).catch(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({ 
          pathname: `/${owner}/${projectsId}/devops`, 
          state:{open_devops:true} 
        });
        // 需要将顶部的open_devops修改
        let { changeOpenDevops } = props;
        changeOpenDevops && changeOpenDevops(true);
      }
    }).catch(error=>{
      console.log(error);
      setIsSpining(false);
    })
  }

  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>
        {
          !isPermission ?
          <div className="noOperation">DevOps开启功能暂未对项目创建者以外的角色开放，可以联系项目创建者进行开启，开启后便可查看构建信息。</div>:""
        }
        <a href={"https://forum.trustie.net/forums/3110/detail"} target="_blank" style={{ color: "#5091FF"}}>
          了解什么是DevOps？
        </a>
        <a href={"https://forum.trustie.net/forums/3080/detail"} target="_blank" style={{ color: "#5091FF"}}>
        如何使用引擎（Engine）功能？
        </a>
        {
          isPermission ?
          <React.Fragment>
            {
              step === 0 && !typeFlag ?
                <ServiceModal sureModal={sureModal}></ServiceModal>
              :""
            }
            { step === 0 && typeFlag ?
              <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={disabled}
                    />,
                    true
                  )}
                  {helper(
                    "服务器用户名：",
                    "account",
                    [{ required: true, message: "请输入服务器用户名" }],
                    <Input placeholder="请输入服务器用户名" size="large" disabled={disabled}/>,
                    true
                  )}
                  {helper(
                    "服务器密码：",
                    "secret",
                    [{ required: true, message: "请输入服务器密码" }],
                    <Input.Password placeholder="请输入服务器密码" size="large" disabled={disabled}/>,
                    true
                  )}
                </Form>
                <AlignCenter>
                  { !disabled && <Button className="mr20" onClick={()=>goUpStep(0)}>上一步</Button>}
                  <Blueback onClick={goStep}>下一步</Blueback>
                </AlignCenter>
              </React.Fragment>
              :""
            }
            {
              step === 1 ?
              <div>
                <AlignCenter style={{justifyContent:"center",marginTop:"20px"}}>
                  <span style={{marginBottom:"42px"}}>密码：</span>
                  <div>
                    <Input.Password value={authorityVal} className={authorityValFlag===true && "flags"} onChange={(e)=>setAuthorityVal(e.target.value)} style={{width:"220px"}}></Input.Password>
                    <p className="color-grey-9" style={{textAlign:"left",lineHeight:'21px'}}>您已保存相关服务器信息，请输入密码，<br/>确认授权DevOps应用</p>
                  </div>
                </AlignCenter>
                <AlignCenter style={{justifyContent:'center'}}>
                  <Blueback onClick={authStep} className="mt20">下一步</Blueback>
                </AlignCenter>
              </div>:""
            }
            { step === 2 ?
              <div style={{textAlign:'center',marginTop:"20px"}}>
                <Blueback onClick={startActive} className="mt20">开始激活</Blueback>
              </div>:""
            }
          </React.Fragment>
          :""
        }
      </div>
    </Spin>
  );
}
export default Form.create()(forwardRef(About));
