import React , { forwardRef, Fragment, useState } from 'react';
import { Form , Input , Button, message } from 'antd';
import { AlignCenter } from '../../Component/layout';
import Modals from '../../Component/PublicModal/Index';
import Axios from 'axios';
import img1 from '../../Images/personalInfo3.png';
import { setmiyah } from '../../../common/Component';
import { useEffect } from 'react';
import Phone from './Phone';

export default Form.create()(
  forwardRef((props)=>{
    const { getFieldDecorator, validateFields, resetFields, getFieldsValue } = props && props.form;
    const { current_user, type, resetUserInfo} = props;

    const [ NewPass , setNewPass ] = useState(undefined);
    const [ NewPassRepeat , setNewPassRepeat ] = useState(undefined);
    const [ countDown, setCountDown] = useState(undefined);
    const [ emailValue, setEmailValue] = useState(undefined);
    const [ passMap, setPassMap] = useState({password: undefined, email: undefined, code: undefined});
    const [ updatePsdMap, setUpdatePsdMap] = useState({oldPassword: undefined, password: undefined, password1: undefined});
    const [ visible, setVisible] = useState(false);

    useEffect(()=>{
      setPassMap({password: undefined, email: undefined, code: undefined});
      setUpdatePsdMap({oldPassword: undefined, password: undefined, password1: undefined});
      document.title = type === '0' ? '邮箱管理' : type === '1' ? '密码管理' : type === '2' ? '账号注销' : '手机号管理';
    }, type)

    function submit() {
      validateFields((error,values)=>{
        if(!error){
          setVisible(true);
        }
      })
    }

    // 判断两次输入的密码是否一致
    var reg = /(?!.*\s)(?!^[\u4e00-\u9fa5]+$)^.{8,16}$/;
    function checkIdentifier(rule, value, callback , inputValue){
      const map = updatePsdMap;
      if (value && !inputValue && !reg.test(value)) {
        map.password1 = undefined;
        setUpdatePsdMap(map);
        callback("请输入8-16位密码，区分大小写、不能使用空格");
      }else if (value && inputValue && value !== inputValue) {
        map.password1 = undefined;
        setUpdatePsdMap(map);
        callback("两次输入的密码不一致");
      }else{
        map.password1 = value;
        setUpdatePsdMap(map);
        callback();
      }
    }

    function checkNewPass(rule, value, callback,newpassrepeat) {
      const map = updatePsdMap;
      if (!reg.test(value)) {
        map.password = undefined;
        setUpdatePsdMap(map);
        callback("请输入8-16位密码，区分大小写、不能使用空格");
      }else if(newpassrepeat && newpassrepeat!==value){
        map.password = undefined;
        setUpdatePsdMap(map);
        callback("两次输入的密码不一致");
      }else{
        map.password = value;
        setUpdatePsdMap(map);
        callback();
      }
    }

    //获取验证码
    function getCaptcha() {
      // 给用户发送邮件
      current_user && Axios.get(`/v1/${current_user.login}/send_email_vefify_code.json`,{params: {
        code_type: 10,
        email: emailValue,
        smscode: setmiyah(emailValue)
      }}).then(res=>{
        if(res && !res.data.status){
          message.success('发送成功')
        }
      })
      // 获取验证码
      startCountDown();
    }

    // 开始倒计时
    function startCountDown(){
      let countDownNum = 60;
      const timer = setInterval(() => {
        countDownNum -= 1;
        setCountDown(countDownNum);
        if(countDownNum <= -1){
          clearInterval(timer);
          setCountDown(undefined)
        }
      }, 1000);
    }

    // 校验用户密码是否正确
    function checkPsd(rule, value, callback){
      const map = type === '0' ? passMap : updatePsdMap;
      if(value){
        current_user && Axios.post(`/v1/${current_user.login}/check_password.json`,{
          password: value
        }).then(res=>{
          if(res && !res.data.status){
            if(type === '0'){
              map.password = value;
              setPassMap(map);
            }else{
              map.oldPassword = value;
              setUpdatePsdMap(map);
            }
            callback();
          }else{
            if(type === '0'){
              map.password = undefined;
              setPassMap(map);
            }else{
              map.oldPassword = undefined;
              setUpdatePsdMap(map);
            }
            callback(res.data.message);
          }
        })
      }else{
        if(type === '0'){
          map.password = undefined;
          setPassMap(map);
        }else{
          map.oldPassword = undefined;
          setUpdatePsdMap(map);
        }
        callback();
      }
    }

    // 校验用户邮箱是否正确
    function checkEmail(rule, value, callback){
      const map = passMap;
      if(value){
        current_user && Axios.post(`/v1/${current_user.login}/check_email.json`,{
          email: value
        }).then(res=>{
          if(res && !res.data.status){
            map.email = value;
            setPassMap(map);
            setEmailValue(value);
            callback();
          }else{
            setEmailValue(undefined);
            map.email = undefined;
            setPassMap(map);
            callback(res.data.message);
          }
        })
      }else{
        setEmailValue(undefined);
        map.email = undefined;
        setPassMap(map);
        callback();
      }
    }

    // 校验用户填写验证码是否正确
    function checkCode(rule, value, callback){
      const map = passMap;
      if(value){
        current_user && value && value.length > 4 && Axios.post(`/v1/${current_user.login}/check_email_verify_code.json`,{
          code_type: 10,
          email: emailValue,
          code: value
        }).then(res=>{
          if(res && !res.data.status){
            map.code = value;
            setPassMap(map);
            callback();
          }else{
            map.code = undefined;
            setPassMap(map);
            callback(res.data.message);
          }
        })
      }else{
        map.code = undefined;
        setPassMap(map);
        callback();
      }
    }

    // 提交更改邮箱表单
    function confirmUpdateEmail(e){
      validateFields((error,values)=>{
        if(!error){
          setVisible(true);
        }
      })
    }

    function updateEmailOrPsd(){
      if(type === '0'){
        const {code, email, password1} = getFieldsValue();
        if(code && email && password1){
          current_user && Axios.patch(`/v1/${current_user.login}/update_email.json`,{
            code, email, password: password1
          }).then(res=>{
            if(res && !res.data.status){
              setPassMap({password: undefined, email: undefined, code: undefined});
              resetFields();
              resetUserInfo();
              setVisible(false);
              message.success('更新成功');
            }else{
              setVisible(false);
              message.error(res.data.message || '更新失败');
            }
          })
        }
      }else{
        const values = getFieldsValue();
        const url = `/accounts/change_password.json`;
        Axios.post(url,{
          login:current_user && current_user.login,
          ...values
        }).then(result=>{
          if(result && result.data){
            resetFields();
            setUpdatePsdMap({oldPassword: undefined, password: undefined, password1: undefined});
            setVisible(false);
            setNewPass(undefined);
            setNewPassRepeat(undefined);
            message.success('密码重置成功!');
          }
        }).catch(error=>{})
        }
    }
  // type: 0邮箱管理 1密码管理 2账号注销
  return(
    <Fragment>
      {type === '0' ? 
      <div>
        <div className='tipsBox mb15'><img src={img1} alt="" width={16} className='mr10'/>更改邮箱后，您在<span className='spanTil'>GitLink</span> 的登录账号、接收通知的邮件地址将同步变更。请谨慎更改!</div>
        <div className='tipsBox mb20 emailBox'>现邮箱地址<span className='ml10 email spanTil'>{current_user && current_user.email}</span></div>
        <div className='updateEmail mb20'>更改邮箱</div>
        <Form layout={'inline'} className="formBase passMan personalUpdateInfoForm">
          <Form.Item label="登录密码" className={`${passMap.password ? 'hasSuccess' : ''}`}>
            {getFieldDecorator("password1",{
              rules:[
                {required:true,message:"请输入登录密码"},
                {validator:(rule, value, callback)=>checkPsd(rule, value, callback)}
              ],
              validateTrigger:"onBlur",
            })(
              <Input.Password placeholder="请输入登录密码" autoComplete={"new-password"} style={{width:"400px"}}/>
            )}
          </Form.Item>
          <Form.Item label="新邮箱地址" className={`${passMap.email ? 'hasSuccess' : ''}`}>
            {getFieldDecorator("email",{
              rules:[
                {required:true,message:"请输入新邮箱地址"},
                {type: 'email',message: '请输入正确的邮箱格式'},
                {validator:(rule, value, callback)=>checkEmail(rule, value, callback)}
              ],
              validateTrigger:"onBlur",
            })(
              <Input placeholder="请输入新邮箱地址" style={{width:"400px"}} autoComplete={"off"}/>
            )}
          </Form.Item>
          <div>
            <Form.Item label="邮箱验证码" className={`${passMap.code ? 'hasSuccess' : ''}`}>
              {getFieldDecorator("code",{
                rules:[
                  {required:true,message:"请输入邮箱验证码"},
                  {validator:(rule, value, callback)=>checkCode(rule, value, callback)}
                ],
                validateTrigger:"onBlur",
              })(
                <Input placeholder="请输入邮箱验证码" style={{width:"400px"}}/>
              )}
            </Form.Item>
            {countDown ? <Button className='getCaptchaBut ml50' disabled>重发 ({countDown})</Button> : <Button className='getCaptchaBut ml50' onClick={getCaptcha} disabled={!emailValue}>获取验证码</Button>}
          </div>
          <AlignCenter style={{marginTop:"20px"}}>
            <span className="ant-form-item-label mr10"></span>
            <Button className={`${passMap.password && passMap.email && passMap.code ? 'but25' : ''}`} type={"primary"} onClick={confirmUpdateEmail} disabled={!(passMap.password && passMap.email && passMap.code)}>确认更改</Button>
          </AlignCenter>
        </Form>
      </div> : 
      type === '1' ? 
      <Form layout={'inline'} className="formBase passMan personalUpdateInfoForm mt30">
        <Form.Item label="旧密码" className={`${updatePsdMap.oldPassword ? 'hasSuccess' : ''}`}>
          {getFieldDecorator("old_password",{
            rules:[
              {required:true,message:"请输入旧密码"},
              {validator:(rule, value, callback)=>checkPsd(rule, value, callback)}
            ],
            validateTrigger:"onBlur",
          })(
            <Input.Password placeholder="请输入旧密码" autoComplete={"new-password"} style={{width:"400px"}}/>
          )}
        </Form.Item>
        <Form.Item label="新密码" className={`${updatePsdMap.password ? 'hasSuccess' : ''}`}>
          {getFieldDecorator("password",{
            rules:[
              {required:true,message:"请输入新密码"},
              {validator:(rule, value, callback)=>checkNewPass(rule, value, callback, NewPassRepeat)}
            ],
            validateFirst: true,
            validateTrigger:"onBlur",
          })(
            <Input.Password placeholder="请输入新密码" style={{width:"400px"}} onChange={(e)=>{setNewPass(e.target.value)}}/>
          )}
        </Form.Item>
        <Form.Item label="确认新密码" className={`${updatePsdMap.password1 ? 'hasSuccess' : ''}`}>
          {getFieldDecorator("new_password_repeat",{
            rules:[
              {required:true,message:"请重新输入新密码"},
              {validator:(rule, value, callback)=>checkIdentifier(rule, value, callback, NewPass)}
            ],
            validateFirst: true,
            validateTrigger:"onBlur",
          })(
            <Input.Password placeholder="请重新输入新密码" style={{width:"400px"}} onChange={(e)=>{setNewPassRepeat(e.target.value)}}/>
          )}
        </Form.Item>
        <AlignCenter style={{marginTop:"20px"}}>
          <span className="ant-form-item-label mr10"></span>
          <Button className={`${updatePsdMap.oldPassword && updatePsdMap.password && updatePsdMap.password1 ? 'but25' : ''}`} type={"primary"} onClick={submit} disabled={!(updatePsdMap.oldPassword && updatePsdMap.password && updatePsdMap.password1)}>确认更改</Button>
        </AlignCenter>
      </Form> 
      : type === '2' ?
        <div>
          <div className='tipsBox mb15'><img src={img1} alt="" width={16} className='mr10'/>请您谨慎操作，注销后帐号内所有数据都会被清空，且无法恢复帐号!</div>
          <div className='tipCont'>
            GitLink目前提供邮件渠道帐号注销服务。如需注销帐号，请通过发送邮件注销申请邮件到 <span className='orange'>gitlink@ccf.org.cn</span>。<br/>
            相关注意事项如下:<br/>
            <span className='oneTipBox mt10'>必须使用要注销的 GitLink 帐号所绑定的邮箱地址发送邮件。</span>
            <span className='oneTipBox mt5'>发送注销申请邮件之前确认帐号下无创建/加入组织，帐号名下无仓库信息。</span>
            <span className='oneTipBox mt5'>邮件标题: 注销 GitLink 帐号，邮件正文请注明要注销帐号的邮箱和昵称。</span>
            <span className='oneTipBox mt5'>发送邮件后，我们会积极处理，请耐心等候我们的邮件回复。</span>
          </div>
        </div>
        :<Phone {...props}/>
      }
      <Modals
        visible={visible}
        onCancel={()=>{setVisible(false)}}
        title={type==='0'? '更改邮箱' : '更改密码'}
        btn={
          <div>
            <Button size={'large'} onClick={()=>{setVisible(false)}}>取消</Button>
            <Button size={"large"} type={"primary"} onClick={updateEmailOrPsd}>确认更改</Button>
          </div>
        }
      >
        <div className="desc">
          <AlignCenter className="descMain">
            <i className="iconfont icon-jinggao1 mr10 font-20 red"></i>确认更改{type === '0' ? '邮箱' : '密码'}？</AlignCenter>
            <p>{type === '0' ? '更改邮箱后，您在GitLink的登录账号、接收通知的邮件地址将同步变更。请再次确认。' : '更改密码后，您在GitLink的登录密码将同步变更。请再次确认。'}</p>
        </div>
      </Modals>
    </Fragment>
  )})
)