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


export default Form.create()(
  forwardRef((props)=>{
    const { getFieldDecorator, validateFields, resetFields, getFieldsValue } = props && props.form;
    const { current_user, resetUserInfo} = props;
    const [ passMap, setPassMap] = useState({logpassword: undefined, phone: undefined, mescode: undefined});
    const [ countDown, setCountDown] = useState(undefined);
    const [ phoneValue, setphoneValue] = useState(undefined);
    const [ visible, setVisible] = useState(false);

    // 校验用户密码是否正确
    function checkPsd(rule, value, callback){
      const map = passMap;
      if(value){
        current_user && value.length > 7 && Axios.post(`/v1/${current_user.login}/check_password.json`,{
          password: value
        }).then(res=>{
          if(res && !res.data.status){
            map.logpassword = value;
            setPassMap(map);
            callback();
          }else{
            map.logpassword = undefined;
            setPassMap(map);
            callback(res.data.message);
          }
        })
      }else{
        map.logpassword = undefined;
        setPassMap(map);
        callback();
      }
    }
    // 校验用户填写验证码是否正确
    function checkCode(rule, value, callback){
      const map = passMap;
      const {phone, logpassword} = getFieldsValue();
      if(!phone){
        callback("请先输入手机号");
      }
      if(!logpassword){
        callback("请先输入登录密码");
      }
      if(value){
          current_user && value && value.length > 5 && Axios.post(`/v1/${current_user.login}/check_phone_verify_code.json`,{
            code_type: 4,
            phone: phoneValue,
            code: value
          }).then(res=>{
            if(res && !res.data.status){
              map.mescode = value;
              setPassMap(map);
              callback();
            }else{
              map.mescode = undefined;
              setPassMap(map);
              callback(res.data.message);
            }
          })
      }else{
        map.mescode = undefined;
        setPassMap(map);
        callback();
      }
    }
    // 校验用户手机号是否正确
    function checkPhone(rule, value, callback){
      const map = passMap;
      if(value){
        if(/^([1][3456789])\d{9}$/.test(value)){
          current_user && Axios.get(`/accounts/valid_email_and_phone.json`,{
            params: {
              login: value,
              type: 3
            }
          }).then(res=>{
            if(res && !res.data.status){
              map.phone = value;
              setPassMap(map);
              setphoneValue(value);
              callback();
            }else{
              setphoneValue(undefined);
              map.phone = undefined;
              setPassMap(map);
              callback(res.data.message);
            }
          })
        }else{
          map.phone = undefined;
          setPassMap(map);
          callback("请输入正确的手机号");
        }
      }else{
        setphoneValue(undefined);
        map.phone = undefined;
        setPassMap(map);
        callback();
      }
    }

    //获取验证码
    function getCaptcha() {
      // 给用户发送邮件https://testforgeplus.trustie.net/api/accounts/get_verification_code.json
      current_user && Axios.get(`/accounts/get_verification_code`,{params: {
        type: 3,
        login: phoneValue,
        smscode: setmiyah(phoneValue)
      }}).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 confirmUpdatePhone(){
      validateFields((error,values)=>{
        if(!error){
          setVisible(true);
        }
      })
    }

    function updateEmailOrPsd(){
      const {mescode, phone, logpassword} = getFieldsValue();
      if(mescode && phone && logpassword){
        current_user && Axios.patch(`/v1/${current_user.login}/update_phone.json`,{
          code:mescode, phone, password:logpassword
        }).then(res=>{
          if(res && !res.data.status){
            setPassMap({logpassword: undefined, phone: undefined, code: undefined});
            resetFields();
            resetUserInfo();
            setVisible(false);
            message.success('更新成功');
          }else{
            setVisible(false);
            message.error(res.data.message || '更新失败');
          }
        })
      }
    }

    return(
      <div>
        <Modals
          visible={visible}
          onCancel={()=>{setVisible(false)}}
          title={'更改手机号'}
          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>确认更改手机号？</AlignCenter>
              <p>更改手机号后，您在GitLink的登录账号将同步变更。请再次确认。</p>
          </div>
        </Modals>
        <div className='tipsBox mb15'><img src={img1} alt="" width={16} className='mr10'/>更改手机号后，您在<span className='spanTil'>GitLink</span> 的登录账号将同步变更。请谨慎更改!</div>
        {current_user && current_user.phone && <div className='tipsBox mb20 emailBox'>现手机号码<span className='ml10 email spanTil'>{current_user.phone}</span></div> }
        <div className='updateEmail mb20'>更改手机号</div>
        <Form layout={'inline'} className="formBase passMan personalUpdateInfoForm">
          <Form.Item label="登录密码" className={`${passMap.logpassword ? 'hasSuccess' : ''}`}>
            {getFieldDecorator("logpassword",{
              rules:[
                {required:true,message:"请输入登录密码"},
                {validator:(rule, value, callback)=>checkPsd(rule, value, callback)}
              ],
              validateTrigger:"onChange",
            })(
              <Input.Password placeholder="请输入登录密码" autoComplete={"new-password"} style={{width:"400px"}}/>
            )}
          </Form.Item>
          <Form.Item label="新手机号码" className={`${passMap.phone ? 'hasSuccess' : ''}`}>
            {getFieldDecorator("phone",{
              rules:[
                {required:true,message:"请输入新手机号码"},
                {validator:(rule, value, callback)=>checkPhone(rule, value, callback)}
              ],
              validateTrigger:"onChange",
            })(
              <Input placeholder="请输入新手机号码" style={{width:"400px"}} autoComplete={"off"}/>
            )}
          </Form.Item>
          <div>
            <Form.Item label="短信验证码" className={`${passMap.mescode ? 'hasSuccess' : ''}`}>
              {getFieldDecorator("mescode",{
                rules:[
                  {required:true,message:"请输入短信验证码"},
                  {validator:(rule, value, callback)=>checkCode(rule, value, callback)}
                ],
                validateTrigger:"onChange",
              })(
                <Input placeholder="请输入短信验证码" style={{width:"400px"}}/>
              )}
            </Form.Item>
            {countDown ? <Button className='getCaptchaBut ml50' disabled>重发 ({countDown})</Button> : <Button className='getCaptchaBut ml50' onClick={getCaptcha} disabled={!phoneValue}>获取验证码</Button>}
          </div>
          <AlignCenter style={{marginTop:"20px"}}>
            <span className="ant-form-item-label mr10"></span>
            <Button onClick={confirmUpdatePhone}  className={`${passMap.logpassword && passMap.phone && passMap.mescode ? 'but25' : ''}`} type={"primary"} disabled={!(passMap.logpassword && passMap.phone && passMap.mescode)}>确认更改</Button>
          </AlignCenter>
        </Form>
      </div>
    )
  })
)