import React, { PureComponent } from 'react';
import { Form, Input, Button, message } from 'antd';
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) {
  //       this.setState({
  //         checkPhone: true
  //       });
  //     }
  //   }, (err) => {
  //     console.log(err);
  //     this.setState({
  //       checkPhone: false
  //     });
  //   });
  // };

  // // 检验是否管理员
  // checkAdmin = () => {
  //   const mobilePhone = this.props.form.getFieldValue("mobile");
  //   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();
    }
  };

  //密码规则正则验证
  checkPasswordRule = (rule, value, callback) => {
    const reg = /^([a-zA-Z0-9]{6,20})$/;
    if (!reg.test(value)) {
      callback('请输入6~20位数字、英文');
    } 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 => {
                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 => {
                  console.log('忘记密码，修改密码成功', data);
                },
                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='pss-password-wrap'>
        <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>
            <FormItem {...tailFormItemLayout}>
              {/* <Button
                style={{ marginRight: 16 }}
                onClick={() => {
                  this.props.history.push('LogOn');
                }}
              >
                取消
              </Button> */}
              <Button type='primary' htmlType='submit'>
                确定
              </Button>
            </FormItem>
          </Form>
        </div>
      </div>
    );
  }
}
