import PropTypes from 'prop-types';
import { Modal, Input, Form, Button, message, Row, Col } from 'antd';
import md5 from 'blueimp-md5';
import User from '@/core/user';
import { resolve } from 'url';
const FormItem = Form.Item;

export default class PasswordModal extends BaseComponent {
  constructor(props) {
    super(props);
    this.state = {
      newpwd: "",
      renewpwd: "",
      verifyCode: "",
      phone: Number(LS.get("uPhone")) || Number(LS.get("bindingPhone")),
      openEye: false,
      showTip: false,
      isSetPwd: window.currentUserInstInfo.isSetPwd,
      openSetForm: false,
    };
  }

  handleChange = e => {
    let newState = {};
    newState[e.target.name] = e.target.value.trim();
    this.setState(newState);
  };

  //点击保存
  handleSave = () => {
    let newpwd = this.state.newpwd,
      renewpwd = this.state.renewpwd,
      verifyCode = this.state.verifyCode,
      phone = this.state.phone;
    if (verifyCode == "" && this.state.isSetPwd) {
      message.warning("验证码不能为空!");
      return new Promise((resolve, reject) => { });
    }
    if (newpwd == "") {
      message.error("请输入密码");
      return new Promise((resolve, reject) => { });
    }
    if (newpwd.match(/^[0-9]*$/) || newpwd.match(/^[a-zA-Z]*$/)) {
      message.warning("密码不能为纯数字或纯字母!");
      return new Promise((resolve, reject) => { });
    }
    else if (!newpwd.match(/^[a-zA-Z0-9]{6,16}$/)) {
      message.warning("密码为6-16位数字与字母!");
      return new Promise((resolve, reject) => { });
    } else {
      if (newpwd.length < 6 || newpwd.length > 20) {
        message.error("密码长度为6-20个字符");
        return new Promise((resolve, reject) => { });
      }
      return axios.post("api-b/b/changePassword", {
        phone: phone,
        newpwd: md5(newpwd),
        code: verifyCode
      })
        .then(res => {
          if (res.resultCode == 0) {
            message.success("修改成功, 即将退出重新登录~");
            setTimeout(() => {
              User.logout();
            }, 500);
          } else {
            message.error(res.resultMsg);
          }
        });
    }
  };

  sendVoiceCode() {
    let phone = Number(LS.get("uPhone")) || Number(LS.get("bindingPhone"));
    return window.axios.post('api-b/b/send/voiceAuthCode', { phone }).then(() => {
      message.warning('验证码将以电话的形式通知到您，请注意接听');
    });
  }

  //获取验证码
  getVerifyCode = () => {
    const self = this;
    let phone = Number(LS.get("uPhone")) || Number(LS.get("bindingPhone"));
    axios
      .post("api-b/b/changePassword/authcode", {
        phone: phone
      })
      .then(() => {
        message.success("验证码已发送");
      });
    let haveSend = $(".sendVerifyCodes");
    if (haveSend.hasClass("wait")) return;

    let timer;
    let timeSub = (waitTime, unit) => {
      clearTimeout(timer);
      timer = setTimeout(function () {
        if (waitTime == 0) {
          haveSend.removeClass("wait").text("发送验证码");
          clearTimeout(timer);
        } else {
          if (waitTime < 40) {
            if (!self.state.showTip) {
              self.setState({ showTip: true });
              setTimeout(() => self.setState({ showTip: false }), 40000);
            }
          }
          haveSend.addClass("wait").text(waitTime + "秒后重发");
          timeSub(--waitTime, 1000);
        }
      }, unit || 0);
    };

    if (true) {
      timeSub(60);
    }
  };

  render() {
    const { phone, openEye, showTip, isSetPwd, openSetForm } = this.state;
    return (
      <Form>
        <FormItem
          label="手机号"
          labelCol={{ span: 2 }}
        >
          <span>{phone}</span>
        </FormItem>
        {openSetForm ?
          [isSetPwd && <FormItem
            label="验证码"
            labelCol={{ span: 2 }}
          >
            <Input
              id="verify_code_input"
              type="text"
              name="verifyCode"
              value={this.state.verifyCode}
              placeholder="请输入验证码"
              onChange={this.handleChange}
              style={{ width: 240 }}
            />
            <Button
              id="send_verify_codes_btn"
              type="button"
              className='sendVerifyCodes'
              style={{ marginLeft: 8 }}
              onClick={this.getVerifyCode}
            >
              获取验证码
              </Button>
            {showTip && <div style={{ fontSize: '12px' }}>
              <span style={{ color: "#686868" }}>收不到短信?</span>
              <span
                style={{ color: "#FFAB1A", cursor: "pointer" }}
                id="sendRegVoiceVerifyCode"
                onClick={this.sendVoiceCode}
              >
                使用语音验证码
                </span>
            </div>}
          </FormItem>,
          <FormItem
            label={!isSetPwd ? '登录密码' : '新密码'}
            labelCol={{ span: 2 }}
          >
            <input style={{ display: 'none' }} />
            <Input
              id="new_password_input"
              type={openEye ? 'string' : 'password'}
              value={this.state.newpwd}
              name="newpwd"
              style={{ width: 240 }}
              onChange={this.handleChange}
              placeholder="6-16位数字或字母，区分大小写"
              suffix={openEye ?
                <span
                  className="icon iconfont"
                  onClick={() => this.setState({ openEye: false })}
                  style={{ cursor: 'pointer', color: '#999' }}
                >&#xe6b5;</span>
                : <span
                  className="icon iconfont"
                  onClick={() => this.setState({ openEye: true })}
                  style={{ cursor: 'pointer', color: '#999' }}
                >&#xe6dc;</span>
              }
            />
          </FormItem>,
          <Row>
            <Col span={2}>
            </Col>
            <Col span={18}>
            <div style={{ display: 'block', lineHeight: 2.5 }}>
              <Button
                id="save_new_password_btn"
                type="primary"

                onClick={() => {
                  this.handleSave().then(() => {
                    this.setState({ isSetPwd: true, openSetForm: false });
                  });
                }}
              >
                保存
              </Button>
              <Button
                id="cancel_new_password_btn"
                type=""
                style={{ marginLeft: 16 }}
                onClick={() => {
                  this.setState({ openSetForm: false })
                }}
              >
                取消
              </Button>
            </div>
            </Col>
          </Row>
        ]
          : <FormItem
            label="登录密码"
            labelCol={{ span: 2 }}
          >
            {!isSetPwd ?
              <Button id="edit_password_btn"  onClick={() => this.setState({ openSetForm: true })}>
                设置密码
                </Button>
              : <div>
                ******
                <Button
                  id="reedit_password_btn"
                  style={{ marginLeft: 8 }}
                  onClick={() => this.setState({ openSetForm: true })}
                >
                  重设密码
                </Button>
              </div>
            }
          </FormItem>
        }
      </Form>
    );
  }
}

PasswordModal.propTypes = {
};