import React, { PureComponent } from 'react';
// import { connect } from 'dva';
import style from 'styled-components';
import { Form, Input, Button, message } from 'antd';
import {
  systemPlatNewsSendVerificationCode,
  systemPlatNewsSendVerificationCode2,
  // systemPlatNewsVerificationCode,
  // systemPerAccountInfoUpdatePassword,
  systemPerAccountInfoUpdatePasswordRequest,
  systemPerAccountInfoUpdatePasswordRequest2
} from '../../../services/api';
import bcx_utils from '../../../common/bcx_utils';
// @connect(state => ({
//   monitor: state.monitor,
// }))

const FormItem = Form.Item;
@Form.create()

/**
 * 修改密码
 */
export default class InitialPasswordModification extends PureComponent {
  constructor(props, context) {
    super(props, context);
    this.state = {
      count: 60, //短信发送时间限制
      ifSendCode: false, //是否已经发送验证码
      companyInfo: this.props.companyInfo,
      confirmDirty: false //是否第一次检验
    };
  }

  /******************************生命周期******************************/

  componentDidMount = () => {
    this.setState({ companyInfo: this.props.companyInfo });
    console.log('this.state', this);
  };

  componentWillUnmount = () => {
    if (this.codeTime) {
      clearInterval(this.codeTime);
    }
  };

  componentWillReceiveProps = (nextProps, newState) => {
    console.log('InitialPasswordModification', nextProps);
    console.log('InitialPasswordModification', this.props);
    this.setState({ companyInfo: nextProps.companyInfo });
  };
  /******************************ajax请求******************************/
  //获取手机验证码
  systemPlatNewsSendVerificationCode = () => {
    const mobile = this.props.form.getFieldValue('mobile');
    bcx_utils.preventRepeatAsync(callback =>
      callback(resolve => {
        systemPlatNewsSendVerificationCode2({ t: '', sign: '', mobile }).then(
          data => {
            console.log(data);
            resolve(false);
          },
          err => {
            console.log(err);
            resolve(false);
          }
        );
      })
    );
  };
  // 初始化密码修改
  // systemPerAccountInfoUpdatePassword = (ajaxPara) => {
  //   //验证码通过再 修改密码
  //   systemPerAccountInfoUpdatePassword(ajaxPara).then(
  //     (data) => {
  //       console.log(data);
  //       message.success(data.msg);
  //       this.props.nextStep();
  //     },
  //     (err) => {
  //       console.log(err);
  //     }
  //   );
  // }

  //记录是否修改过密码
  handleConfirmBlur = e => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  };
  //确认管理密码   验证2次输入的密码
  compareToFirstPassword = (rule, value, callback) => {
    if (!this.checkPasswordRule(value)) {
      callback('请输入6~20位数字、英文');
    }
    const form = this.props.form;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次密码输入不一致!');
    } else {
      callback();
    }
  };
  //新管理密码     验证2次输入的密码
  validateToNextPassword = (rule, value, callback) => {
    if (!this.checkPasswordRule(value)) {
      callback('请输入6~20位数字、英文');
    }
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(['confirm'], { force: true });
    }
    callback();
  };

  //密码规则正则验证
  checkPasswordRule = value => {
    const reg = /^([a-zA-Z0-9]{6,20})$/;
    if (!reg.test(value)) {
      return false;
    } else {
      return true;
    }
  };

  /******************************相关事件******************************/
  //表单提交
  handleSubmit = e => {
    e.preventDefault();
    this.props.form.validateFields((err, { mobile, password, code }) => {
      if (!err) {
        console.log("I'm coming");
        // console.log('Received values of form: ', values);
        //判断验证码, preventRepeatAsync导致只能进行一次提交
        // bcx_utils.preventRepeatAsync(callback => callback((resolve) => {
        // systemPerAccountInfoUpdatePassword({ mobile, password, code }).then((data) => {
        systemPerAccountInfoUpdatePasswordRequest2({
          mobile,
          password,
          code
        }).then(
          data => {
            console.log('忘记密码，修改密码成功', data);
            this.props.addStep();
            // resolve();
          },
          errs => {
            console.log('忘记密码，修改密码成功', errs);
          }
        );
        // systemPlatNewsVerificationCode({ mobile, code })
        //   .then(
        //     (data) => {
        //       resolve(false);
        //       return systemPerAccountInfoUpdatePassword({ mobile, password });
        //     },
        //     (err) => {
        //       resolve(false);
        //       return false;
        //     }
        //   )
        //   .then(data => {
        //     if (!data) {
        //       return;
        //     }
        //     console.log(data);
        //     this.props.nextStep();
        //   }, err => {
        //     console.log(err);
        //   });
        // }));
      }
    });
  };

  //发送验证码
  sendCode = () => {
    const { ifSendCode } = this.state;
    const mobile = this.props.form.getFieldValue('mobile');
    const mobileError = this.props.form.getFieldError('mobile');
    //判断是否正确的手机号码，然后开始计时
    if (mobile !== undefined && mobileError === undefined) {
      if (ifSendCode) {
        return;
      } else {
        this.setState({ ifSendCode: true });
        this.systemPlatNewsSendVerificationCode();
        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);
      }
    } else {
      bcx_utils.preventRepeat(() => {
        message.error('请输入正确的手机号码', 1.8);
      }, 2000);
    }
  };

  /******************************render******************************/
  //验证码
  renderValidButton = () => {
    const { ifSendCode, count } = this.state;
    return (
      <Button
        type='primary'
        disabled={ifSendCode}
        className='getCaptcha'
        onClick={this.sendCode}
      >
        {ifSendCode ? `${count} s` : '验证码'}
      </Button>
    );
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 6 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 12 },
        sm: { span: 12 }
      }
    };
    const { comName = '', adminPhone = '' } = this.state.companyInfo;
    return (
      <Container>
        <header className='password-header'>初始密码修改</header>
        <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
          {/* <FormItem {...formItemLayout} label='当前企业'>
            <span>{comName}</span>
          </FormItem> */}
          <FormItem
            {...formItemLayout}
            label='绑定手机号码'
            extra={
              !adminPhone ? (
                <span style={{ color: 'red' }}>
                  注：管理员手机号修改成功后，旧百保盾账号将废弃，请使用管理员手机号登录系统；初始化完成后，可在企业管理-企业设置中，修改管理员信息。
                </span>
              ) : (
                ''
              )
            }
          >
            {getFieldDecorator('mobile', {
              initialValue: adminPhone,
              rules: [
                {
                  pattern: /^1[0-9]{10}$/,
                  message: '请输入正确手机号码!'
                },
                { required: true, message: '请输入您的手机号码' }
              ]
            })(
              <Input
                maxLength={20}
                placeholder='请输入您的手机号码'
                disabled={!!adminPhone}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label='验证码'>
            <div style={{ display: 'flex' }}>
              <div style={{ flex: 1 }}>
                {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.validateToNextPassword }
              ]
            })(<Input maxLength={30} placeholder='请输入' type='password' />)}
          </FormItem>
          <FormItem {...formItemLayout} label='确认管理密码'>
            {getFieldDecorator('confirm', {
              rules: [
                { required: true, message: '请再次输入密码' },
                { validator: this.compareToFirstPassword }
              ]
            })(
              <Input
                maxLength={30}
                placeholder='请再次输入密码'
                type='password'
                onBlur={this.handleConfirmBlur}
              />
            )}
          </FormItem>
          <FormItem {...formItemLayout} label=' ' colon={false}>
            {/*<Button style={{marginRight: "8px"}}>取消</Button>*/}
            <Button className='submit' type='primary' htmlType='submit'>
              确定并下一步
            </Button>
          </FormItem>
        </Form>
      </Container>
    );
  }
}

/*********************样式*************************** */
const Container = style.div`{
    .password-header{
        font-size: 20px;
        color: #333333;
        padding-bottom:16px;
        border-bottom:1px solid #e9e9e9;
    }
    .getCaptcha{
        top:4px;
        margin-left:8px;
         &:disabled{
          background:rgb(204, 204, 204);
          color:#fff;
        }
    }
    .ant-btn-primary{
        background-color: #0F71FF;
    }
}`;
