import React, { PureComponent } from 'react';
import { Form, Input, Button, message } from 'antd';
import IconS from "../../components/IconS";
import {
  systemPlatNewsSendVerificationCode,
  // systemPlatNewsVerificationCode,
  systemPerAccountInfoUpdatePassword,
  // systemPerBaseInfoCheckAdmin,
  systemPerBaseInfoCheckPer,
  systemPerAccountInfoCheckUserAccountExist

} from "../../services/api";
import "./ForgetPassword.less";

const FormItem = Form.Item;
@Form.create()
export default class ForgetPassword extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      count: 60,//短信发送时间限制
      ifSendCode: false,//是否已经发送验证码
    };
  }

  //发送按钮改变
  renderValidButton = () => {
    const { ifSendCode, count } = this.state;
    return (
      <Button type="primary"
        disabled={ifSendCode}
        className="getCaptcha"
        onClick={this.sendCode}
        style={{ marginLeft: 6, marginTop: 4 }}
      >
        {ifSendCode ? `${count} s` : '获取验证码'}
      </Button>
    );
  };

  //发送验证
  sendCode = () => {
    // const { ifSendCode } = this.state;
    //获取手机号是否正确
    const mobile = this.props.form.getFieldValue('mobile');
    const mobileErro = this.props.form.getFieldError('mobile');
    if (mobile === '' || mobile === undefined) {
      message.error('请填写企业管理员手机号码!');
      return;
    }
    if (mobile !== undefined && mobileErro === undefined) {
      // systemPerAccountInfoCheckUserAccountExist({ mobile }).then((data) => {
        this.setState({ ifSendCode: true });
        this.getNewsCode();
        this.codeTime = window.setInterval(() => {
          const { count } = this.state;
          if (count !== 1) {
            this.setState(preState => ({
              count: preState.count - 1,
            }));
          } else {
            clearInterval(this.codeTime);
            this.setState({ ifSendCode: false, count: 60 });
          }
        }, 1000);
      // }, (errs) => {
      //   console.log("查询手机号码是否存在用户账号", errs);
      // });
    }
  };

  //获取验证码
  getNewsCode = () => {
    const mobile = this.props.form.getFieldValue("mobile");
    systemPlatNewsSendVerificationCode({ t: "", sign: "", mobile })
      .then((data) => {
        console.log(data);
      }, (err) => {
        console.log(err);
      });
  };
  //检验手机号是否存在
  // checkMobile = () => {
  //   const mobilePhone = this.props.form.getFieldValue("mobile");
  //   systemPerBaseInfoCheckPer({ mobilePhone }).then((data) => {
  //     if (data) {
  //       console.log('chaekMobile>>>>>>>>>>>>', data);
  //       this.setState({
  //         checkPhone: true
  //       });
  //     }
  //   }, (err) => {
  //     console.log(err);
  //     this.setState({
  //       checkPhone: false
  //     });
  //   });
  // };

  // // 检验是否管理员
  // checkAdmin = () => {
  //   const mobilePhone = this.props.form.getFieldValue("mobile");
  //   console.log(mobilePhone);
  //   systemPerBaseInfoCheckAdmin({ mobilePhone })
  //     .then((data) => {
  //       console.log('checkAdmin>>>>>>>>>>>>', data);
  //     }, (err) => {
  //       console.log(err.retType);
  //       return false;
  //     });
  // }

  //判断验证码是否正确
  // checkCode = () => {
  //   const code = this.props.form.getFieldValue("code");
  //   const mobile = this.props.form.getFieldValue("mobile");
  //   systemPlatNewsVerificationCode({ mobile, code })
  //     .then((data) => {
  //       console.log(data);
  //       this.setState({
  //         checkCode: true
  //       });
  //     }, (err) => {
  //       console.log('111', err);
  //       this.setState({
  //         checkCode: false
  //       });
  //     });
  // };

  //验证手机号码
  checkPhone = (rule, value, callback) => {
    if (value && !(/^1[0-9]{10}$/).test(value)) {
      callback('请输入正确的手机号码！');
    } else {
      callback();
    }
  };

  //判断密码中是否存在跟用户名部分字符（连续4个字符）重叠的情况
  //重叠返回1否则0
  isOverlap=(username,password)=>{
    //var username='18965192006';
    //var password='Test@9651_0a';
    const len = username.length;
    for(var i=0;i<=len-4;i++){
        if(password.indexOf(username.substring(i,i+4))>0){
            //密码中不出现与用户名相关的字符
            return 1;
        }
    }
    return 0;
  }

  //判断密码中是否存在关键字
  //重叠返回1否则0
  isSpecialStr=(password)=>{
    const passwordc = password.toLowerCase();
    let list = ['pss','daxing','huodong','zhejiang','saas','baibaodun','baoan','xitong'];
    for(let i=0;i<=list.length;i++){
        if(passwordc.indexOf(list[i])>0){
            //密码中不出现与相关的字符，如：pss,daxing,huodong,zhejiang,saas,baibaodun,baoan,xitong
            return 1;
        }
    }
    return 0;
  }

  //密码规则正则验证
  checkPasswordRule = (rule, value, callback) => {
    // const reg = /^([a-zA-Z0-9]{6,20})$/;
    const reg = /(?!^(\d+|[a-zA-Z]+|[~!@#$%^&*()_.]+)$)^[\w~!@#$%^&*()_.]{8,18}$/;
    const userName=this.props.form.getFieldValue('mobile');//获取手机号码
    if (!reg.test(value)) {
      callback('密码应为字母，数字，特殊符号(~!@#$%^&*()_.)，两种及以上组合，8-18位字符串，如：xyl37@baa');
    }else if(this.isSpecialStr(value)==1){
      callback('密码中不出现与相关的字符，如：pss,daxing,huodong,zhejiang,saas,baibaodun,baoan,xitong')
    }else if(this.isOverlap(userName,value)==1){
      callback('密码中不出现与手机号相关的字符')
    }    
    else {
      callback();
    }
    if (!value && this.props.form.getFieldValue("repassword")) {
      const { setFieldsValue } = this.props.form;
      setFieldsValue({
        repassword: '',
      });
    }
  }

  //判断密码是否一致
  checkPassword = (rule, value, callback) => {
    //password 第一次密码
    const password = this.props.form.getFieldValue("password");
    //repassword 第2次密码
    const repassword = this.props.form.getFieldValue("repassword");
    if (password !== repassword) {
      callback('两次密码输入不一致');
    } else {
      callback();
    }
    // if (value && !password) {
    //   const { setFieldsValue } = this.props.form;
    //   setFieldsValue({
    //     repassword: '',
    //   });
    // }
  };

  // 表单提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, { mobile, password, code }) => {
      if (!err) {
        // this.checkAdmin();
        // this.checkMobile();
        // this.checkCode();//不需要，2018-9-13

        // const promise = new Promise((resolve, reject) => {
        //   const mobilePhone = mobile;
        //   systemPerBaseInfoCheckPer({ mobilePhone }).then((data) => {
        //     console.log('验证手机号码是否存在', data);
        //     if (data.data) {
        //       const checkPhone = true;
        //       resolve(checkPhone);
        //     }
        //   }, (errr) => {
        //     console.log(errr);
        //     reject(errr);
        //   });
        // });
        // promise.then((val) => {
        //   if (val) {
        //     systemPerAccountInfoUpdatePassword({ mobile, password, code }).then((data) => {
        //       this.props.history.push("LogOn");
        //     }, (errs) => {
        //       console.log("忘记密码，修改密码成功", errs);
        //     });
        //   }
        // });

        systemPerAccountInfoUpdatePassword({ mobile, password, code }).then((data) => {
          this.props.history.push("LogOn");
        }, (errs) => {
          console.log("忘记密码，修改密码成功", errs);
        });
      }
    }, err => {
      console.log(err);
    });
  };



  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 17,
          offset: 7,
        },
      },
    };
    return (
      <div className="password-wrap" >
        <div className="password-header">
          <div className="head-portrait">
            <IconS type="logo-" />
            <span className="head-portrait-text">
              <span style={{ fontSize: "18px" }}>百保盾</span>
              <br />
              <span style={{ fontSize: "12px" }}>改变工作 改变你</span>
            </span>
          </div>
          {/*<div className="head-portrait-register">*/}
          {/*<span*/}
          {/*style={{ cursor: "pointer" }}*/}
          {/*onClick={() => this.props.history.push("Enroll")}*/}
          {/*>*/}
          {/*注册*/}
          {/*</span>*/}
          {/*</div>*/}
        </div>
        <div className="password-content">
          <h1 className="password-title">忘记密码</h1>
          {/*<p className="password-text">当前企业: <span>百川信（厦门）网络信息服务有限公司</span></p>*/}
          <Form onSubmit={this.handleSubmit} >
            <FormItem
              {...formItemLayout}
              label="手机号码:"
            >
              {getFieldDecorator('mobile', {
                rules: [{
                  required: true, message: '请输入手机号码!',
                }, {
                  validator: this.checkPhone
                }],
              })(
                <Input placeholder="请输入" style={{ width: 400 }} />
              )}
            </FormItem>
            <FormItem {...formItemLayout} label="验证码">
              <div style={{ display: 'flex' }}>
                <div style={{ width: 290 }}>
                  {getFieldDecorator('code', {
                    rules: [{
                      pattern: /^[0-9]{6}$/, message: '请输入正确验证码!',
                    }, {
                      required: true, message: '请输入验证码！',
                    }],
                  })(
                    <Input placeholder="请输入" maxLength={6} />
                  )}
                </div>
                {this.renderValidButton()}
              </div>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label=" 新密码:"
            >
              {getFieldDecorator('password', {
                rules: [{
                  required: true, message: '请输入您的新密码!',
                }, {
                  validator: this.checkPasswordRule
                }],
              })(
                <Input type="password" placeholder="请输入" style={{ width: 400 }} />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label=" 确认密码:"
            >
              {getFieldDecorator('repassword', {
                rules: [{
                  initialValue: '',
                  required: true,
                  message: '请输入您的确认密码!'
                },
                { validator: this.checkPassword, }
                ],
              })(
                <Input type="password" placeholder="请输入" style={{ width: 400 }} />
              )}
            </FormItem>
            <p style={{ cursor: "pointer" }}
              className="password-goLogin"
              onClick={() => this.props.history.push("LogOn")}
            >
              去登录
            </p>
            <FormItem {...tailFormItemLayout}>
              <Button style={{ marginRight: 16 }} onClick={() => {
                this.props.history.push("LogOn");
              }}>取消</Button>
              <Button type="primary" htmlType="submit">确定</Button>
            </FormItem>
          </Form>
        </div>
      </div>
    );
  }
}

