<template>
  <div class="register">
    <login-top></login-top>
    <div class="registerMain">
      <h2>
        <span>
          <img src="../../../../assets/img/login/圆形图标.png" alt />
        </span> 电梯管家管理后台
      </h2>
      <h5>中国电梯行业维保服务标准化执行工具</h5>
      <div>
        <span>
          <h3>注册</h3>
          <el-form :model="RegData" ref="RegData" :rules="rules" :validate-on-rule-change="false">
            <el-form-item prop="userID">
              <el-input v-model="RegData.userID" placeholder="请输入账号名"></el-input>
            </el-form-item>
            <el-form-item prop="PassWord">
              <el-input v-model="RegData.PassWord" placeholder="请输入密码" :type="passw"></el-input>
            </el-form-item>
            <el-form-item prop="PassWords">
              <el-input v-model="RegData.PassWords" placeholder="请再次输入密码" :type="passw"></el-input>
            </el-form-item>
            <el-form-item prop="UserName">
              <el-input v-model="RegData.UserName" placeholder="请输入真实姓名"></el-input>
            </el-form-item>
            <el-form-item class="PhoneCode" prop="isNUM">
              <el-input v-model="RegData.isNUM" placeholder="请输入验证码"></el-input>
              <!-- <span class="ffright ImgNum" :style="{'background-color':`url(${imgSrc})no-repeat top center`}">
                
              </span>-->
              <span
                class="ffright ImgNum"
                :style="{'background-image':`url(${imgSrc})`}"
                @click="getImgCode"
              >{{errText}}</span>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input v-model="RegData.phone" placeholder="请输入手机号码"></el-input>
            </el-form-item>
            <el-form-item prop="checkcode" class="PhoneCode">
              <el-input v-model="RegData.checkcode" placeholder="请输入短信验证码"></el-input>
              <span @click="GetVCode" class="VerificationCode ffright">{{dateSecond}}</span>
            </el-form-item>
            <!-- <p class="el-icon-warning">请输入真实姓名便于加入团队</p> -->
          </el-form>
          <div class="regsiterButton">
            <el-button @click="register('RegData')" :loading="isloading">注册</el-button>
            <router-link to="login">使用已有帐户登录</router-link>
          </div>
        </span>
      </div>
    </div>
    <login-bottom></login-bottom>
  </div>
</template>

<script>
import logintop from "../../components/common/logintop.vue";
import loginbottom from "../../components/common/loginbottom.vue";
import { setInterval } from "timers";
import md5 from "js-md5";
// import { promises } from 'dns';
export default {
  components: {
    loginTop: logintop,
    loginBottom: loginbottom
  },
  name: "register",
  created() {},
  mounted() {
    this.getImgCode();
  },
  data() {
    var checkPhone = (rule, value, callback) => {
      var that = this;
      var p1 = new Promise(function(resolve, reject) {
        var url = "system/login/checkMobile?mobile=" + value;
        that.axios.get(url).then(res => {
          resolve(res);
        });
      });
      p1.then(res => {
        console.log(res);
        if (value === "") {
          return callback(new Error("手机号码不能为空"));
        } else if (!/^1[3,4,5,7,8,9]\d{9}$/.test(value)) {
          return callback(new Error("手机号码格式不对"));
        } else if (res.statusCode == "0") {
          return callback(res.message);
        } else {
          return callback();
        }
      });
    };
    var checkPassw = (rule, value, callback) => {
      if (value.length < 8) {
        return callback(new Error("密码长度不能低于八位数"));
      } else {
        return callback();
      }
    };
    var checkPasss = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.RegData.PassWord) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    var Not_null = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("账户号不能为空"));
      } else {
        callback();
      }
    };
    var chekisNUM = (rule, value, callback) => {
      var that = this;
      var getverify = function(resolve, reject) {
        var url = "system/login/checkImagCode?inputStr=" + value;
        that.axios.get(url).then(res => {
          resolve(res);
        });
      };
      var p1 = new Promise(getverify);
      p1.then(function(res) {
        if (!value) {
          return callback(new Error("验证码不能为空"));
        } else if (res.statusCode == "0") {
          return callback(new Error(res.message));
        } else {
          return callback();
        }
      });
    };
    var checkcode = (rule, value, callback) => {

      if (!value) {
        return callback(new Error("短信验证码不能为空"));
      } else {
        callback();
      }
    };
    var checkName = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("姓名不能为空"));
      } else {
        callback();
      }
    };
    return {
      RegData: {
        phone: "",
        PassWord: "",
        PassWords: "",
        checkcode: "",
        UserName: "",
        UserID: "",
        isNUM: ""
      },
      imgSrc: null,
      passw: "password",
      canClick: true,
      dateSecond: "获取验证码",
      rules: {
        phone: [{ validator: checkPhone, trigger: "blur" }],
        PassWord: [{ validator: checkPassw, trigger: "blur" }],
        PassWords: [{ validator: checkPasss, trigger: "blur" }],
        userID: [{ validator: Not_null, trigger: "blur" }],
        isNUM: [{ validator: chekisNUM, trigger: "blur" }],
        checkcode: [{ validator: checkcode, trigger: "blur" }],
        UserName: [{ validator: checkName, trigger: "blur" }]
      },
      setIn: null,
      isloading: false,
      ConditionNum: 0,
      regimg: true,
      errText: ""
    };
  },
  methods: {
    // 获取验证码
    GetVCode() {
      var _this = this;
      this.$refs.RegData.validateField("phone", phoneError => {
        if (!phoneError) {
          var num = 60;
          if (this.canClick) {
            var url = "system/login/smsCode?mobile=" + this.RegData.phone;
            _this.setIn = window.setInterval(() => {
              if (num > 0 && num <= 60) {
                num--;
                _this.dateSecond = num + "s";
              } else {
                window.clearInterval(_this.setIn);
                _this.dateSecond = "获取验证码";
                _this.canClick = true;
              }
            }, 1000);

            this.axios.get(url).then(result => {
              if (result.statusCode == "0") {
                // 弹框
                _this.$alert("网络错误", {
                  confirmButtonText: "确定",
                  callback: action => {
                    window.clearInterval(_this.setIn);
                    _this.dateSecond = "获取验证码";
                    _this.canClick = true;
                  }
                });
              } else if (result.statusCode == "9") {
                _this.$alert("无数据", {
                  confirmButtonText: "确定",
                  callback: action => {
                    window.clearInterval(_this.setIn);
                    _this.dateSecond = "获取验证码";
                    _this.canClick = true;
                  }
                });
              }
            });
          } else {
            _this.canClick = false;
          }
        }
      });
    },
    getImgCode() {
      var url = "system/login/getImagCode";
      if (this.ConditionNum > 10) {
        this.regimg = false;
        this.$message({
          message: "点击频率过快,请休息两分钟",
          type: "warning"
        });
      }
      if (this.regimg) {
        this.ConditionNum++;
        clearTimeout(ConditiNum);
        this.axios.get(url, { responseType: "arraybuffer" }).then(result => {
          if (result.statusCode == "0") {
            this.errText = "网络错误";
            return;
          }
          this.imgSrc =
            "data:image/png;base64," +
            btoa(
              new Uint8Array(result).reduce(
                (result, bytes) => result + String.fromCharCode(bytes),
                ""
              )
            );
        });
      } else {
        var ConditiNum = setTimeout(() => {
          this.ConditionNum = 0;
          this.regimg = true;
        }, 2000);
      }
    },

    // 验证
    register(RegData) {
      var that = this;
      this.$refs.RegData.validate(valid => {
        if (valid) {
          var url =
            "system/login/checkSmsCode?inputSmsCode=" + this.RegData.checkcode;
          that.axios.get(url).then(res => {
            if (res.statusCode == "1") {
              that.userLogin();
            }else if(res.statusCode == "9"){
               that.$alert("无数据", "提示", {
                confirmButtonText: "确定"
              });
            } else {
              that.$alert(res.message, "提示", {
                confirmButtonText: "确定"
              });
            }
          });
        } else {
          console.log("error submit!!");
        }
      });
    },

    // 注册
    userLogin() {
      var that = this;
      var reg_url = "system/login/register";
      var RegParam = {
        account: this.RegData.userID,
        mobile: this.RegData.phone,
        password: md5(this.RegData.PassWord),
        name: this.RegData.UserName,
        inputSmsCode:this.RegData.checkcode
      };
      this.axios.post(reg_url, RegParam).then(result => {
        if (result.Success) {
          this.$message.success(result.message);
          this.$router.replace("/login");
        }else{
          this.$message.error(result.message);
        }
      });
    }
  },
  beforeDestroy: function() {
    // document.body.removeAttribute("class", "body_back");
    window.clearInterval(this.setIn);
  }
};
</script>
