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

} 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,//是否已经发送验证码
      mobilePhone: props.mobilePhone,
    };
  }

  componentDidMount() {
    this.props.reef(this);
  }

  clearValue = () => {
    const { setFieldsValue } = this.props.form;
    setFieldsValue({
      code: '',
      changePassword: '',
      changeRepassword: '',
    });
  }
  //发送按钮改变
  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) {
      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);
    }
  };

  //获取验证码
  getNewsCode = () => {
    const mobile = this.props.form.getFieldValue("mobile");
    systemPlatNewsSendVerificationCode({ t: "", sign: "", mobile })
      .then((data) => {
        console.log(data);
      }, (err) => {
        console.log(err);
      });
  };

  //验证手机号码
  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("changeRepassword")) {
      const { setFieldsValue } = this.props.form;
      setFieldsValue({
        changeRepassword: '',
      });
    }
  }

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

  // 表单提交
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFields((err, { mobile, changePassword, code }) => {
      const password = changePassword;
      if (!err) {
        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) => {
              this.props.logout();
            }, (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" style={{ background: "#fff", padding: 0 }}>
        <div className="password-content" style={{ padding: 0, height: "auto" }}>
          <Form onSubmit={this.handleSubmit} >
            <FormItem
              {...formItemLayout}
              label="手机号码:"
            >
              {getFieldDecorator('mobile', {
                initialValue: this.state.mobilePhone,
                rules: [{
                  required: true, message: '请输入手机号码!',
                }, {
                  validator: this.checkPhone
                }],
              })(
                <Input disabled 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('changePassword', {
                rules: [{
                  required: true, message: '请输入您的新密码!',
                }, {
                  validator: this.checkPasswordRule
                }],
              })(
                <Input type="password" placeholder="请输入" style={{ width: 400 }} />
              )}
            </FormItem>
            <FormItem
              {...formItemLayout}
              label=" 确认密码:"
            >
              {getFieldDecorator('changeRepassword', {
                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.cancelChangePasswordModal();
                this.clearValue();
              }}>取消</Button>
              <Button type="primary" htmlType="submit">确定</Button>
            </FormItem>
          </Form>
        </div>
      </div>
    );
  }
}

