import React , { useEffect , useState , forwardRef , useCallback } from 'react';
import { Button , Modal , Form , Input } from 'antd';
import { AlignCenter } from '../Component/layout';
import axios from 'axios';
import Modals from '../Component/Modal';
import PasswordAuthority from '../Component/PasswordAuthority';
import Service from './Service';

const TIPS = "解除CI服务器绑定后，您所有的项目构建数据将被清空。确定解除绑定？";
function CIdispose(props){
  const [ CIData , setCIData ] = useState(undefined);
  const [ step , setStep ] = useState(0);
  const [ visible, setVisible ] = useState(false);
  const [ serviceVisible , setServiceVisible ] = useState(false);
  const [ bindVisible, setBindVisible ] = useState(false);
  const [ ci_certification, setCi_certification ] = useState(false);
  const [ btnLoading , setBtnLoading ] = useState(false);

  const [ authorityValBox , setAuthorityValBox] = useState(false);
  const { user } = props;

  const { form: { getFieldDecorator, validateFields , setFieldsValue } } = props;
  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>
    ),
    []
  );

  useEffect(()=>{
    getInit();
  },[])

  function getInit(){
    const url = `/users/ci/cloud_account.json`;
    axios.get(url).then(result=>{
      if(result && result.data){
        setCIData(result.data.cloud_account);
        setStep(result.data.step);
        setCi_certification(result.data.ci_certification);
      }
    }).catch(error=>{
      console.log(error);
    })
  }

  // 解除绑定
  function cancelBind(){
    const url = `/users/ci/cloud_account/unbind.json`;
    axios.delete(url).then(result=>{
      if(result && result.data){
        props.showNotification("成功解除绑定！");
        setVisible(false);
        getInit();
      }
    }).catch(error=>{
      setBindVisible(false);
    })
  }

  function onCancel(){
    setVisible(false);
  }

  // 确定绑定服务器信息
  function sureBindInfo(){
    validateFields((error, values) => {
      if (!error) {
        setBtnLoading(true);
        const url = `/users/ci/cloud_account/bind.json`;
        axios.post(url,{
          ...values
        }).then(result=>{
          setBtnLoading(false);
          if(result && result.data){
            setBindVisible(false);
            setCIData(result.data.cloud_account);
            setStep(result.data.step);
            props.showNotification("服务器绑定成功！");
          }
        }).catch((error)=>{
          setBtnLoading(false);
        })
      }
    })
  }
  // 取消绑定服务器信息
  function cancelBindInfo(){
    setBindVisible(false);
    setFieldsValue({
      ip_num:undefined,
      secret:undefined,
      account:undefined
    })
  }

  function okAuthority(){
    setAuthorityValBox(false);
    getInit();
  }

  function cancelAuthority(){
    setAuthorityValBox(false);
  }

  // 确认选择服务器
  function SureBtn(type){
    if(type === 1){
      setServiceVisible(false);
      setBindVisible(true);
    }else{
      const url = `/users/ci/cloud_account/trustie_bind.json`;
      axios.post(url,{
        account:user && user.login
      }).then(result=>{
        if(result && result.data){
          setServiceVisible(false);
          setAuthorityValBox(true);
          getInit();
        }
      }).catch(error=>{setServiceVisible(false)})
    }
  }

  return(
    <div className="disposeInfo">
      <Service visible={serviceVisible} SureBtn={SureBtn} CancelBtn={()=>{setServiceVisible(false)}}></Service>
      <PasswordAuthority authorityValBox={authorityValBox} successFunc={okAuthority} cancelFunc={cancelAuthority}></PasswordAuthority>
      <Modal
        className="modalsStyle"
        visible={bindVisible}
        title={"绑定CI服务器地址"}
        onCancel={cancelBindInfo}
        closable={true}
        centered={true}
        footer={
          <div>
            <Button onClick={cancelBindInfo}>取消</Button>
            <Button loading={btnLoading} type={"primary"} style={{marginLeft:"20px"}} onClick={sureBindInfo}>确定</Button>
          </div>
        }
      >
        <Form style={{marginTop:"20px"}}>
          {helper(
            "服务器IP地址：",
            "ip_num",
            [{ required: true, message: "请输入服务器IP地址" }],
            <Input
              placeholder="请输入服务器IP地址"
              style={{ width: "368px" }}
              size="large"
            />,
            true
          )}
          {helper(
            "服务器用户名：",
            "account",
            [{ required: true, message: "请输入服务器用户名" }],
            <Input placeholder="请输入服务器用户名" size="large" />,
            true
          )}
          {helper(
            "服务器密码：",
            "secret",
            [{ required: true, message: "请输入服务器密码" }],
            <Input.Password placeholder="请输入服务器密码" size="large" />,
            true
          )}
        </Form>
      </Modal>
      <Modals visible={visible} title={"解除绑定"} content={TIPS} onOk={cancelBind} onCancel={onCancel}/>
      <div className="disposeItem">
        <AlignCenter>
          <span>CI服务器地址</span>
          {CIData && CIData.ip && step >= 1 ? <span className="ml10">{CIData.ip}</span> :""}
          { step === 0 && <span className="ml10 authTag red">未绑定</span> }
          { step === 1 && !ci_certification && <span className="ml10 authTag red">未认证</span> }
          { ci_certification && <span className="ml10 authTag green">已认证</span> }
        </AlignCenter>
        <AlignCenter>
          { step === 0 && <Button type={'primary'} onClick={()=>setServiceVisible(true)} >马上绑定</Button> }
          { step === 1 && !ci_certification && <Button type={'primary'} style={{color:"#fff"}} onClick={()=>setAuthorityValBox(true)} target="_blank">马上认证</Button> }
          { step >= 1 && <Button type={'danger'} className="ml20" onClick={()=>setVisible(true)}>解除绑定</Button> }
        </AlignCenter>
      </div>
    </div>
  )
}
export default Form.create()(forwardRef(CIdispose));;
