<template>
  <div class="login_backg">
    <div class="login_all">
      <div class="headercontainer">
        <div class="center-logo" style="width:100%;">
          <img class="logo" src="@/assets/imgs/ic_fuwuzs_navy.png" alt />
        </div>
      </div>
      <el-card v-if="active == 'login'" class="box-card login">
        <!-- <div slot="header" class="clearfix">
          <span class="login_head">用户登录</span>
        </div>-->
        <div v-if="msgShow" :class="msgShow==true?'login_msg':''">{{msg}}</div>
        <el-form :model="form" ref="form1" @submit.native.prevent class="login_forms">
          <el-form-item>
            <el-input v-model="form.username" autofocus="autofocus" placeholder="请输入用户名或邮箱"></el-input>
          </el-form-item>
          <el-form-item>
            <el-input
              v-if="visible"
              :type="visible ? 'password':'text'"
              v-model="form.password"
              placeholder="请输入密码"
            >
              <i
                slot="suffix"
                title="显示密码"
                @click="changePass()"
                style="cursor:pointer;"
                :class="visible ? 'el-icon-view':'el-icon-view icon_blue'"
              ></i>
            </el-input>
          </el-form-item>
        </el-form>
        <el-form>
          <el-form-item class="rembme">
            <el-checkbox v-model="checked">记住我</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button
              class="btn_sub sub1"
              type="primary"
              @click.prevent="login_remember_info()"
            >登 录</el-button>
          </el-form-item>
          <el-form-item>
            <el-button class="btn_sub sub2" @click.prevent="register">
              还没有账户？立即注册&nbsp;&nbsp;
              <i class="el-icon-arrow-right"></i>
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
      <el-card v-else-if="active == 'register'" class="box-card login">
        <div slot="header" class="clearfix">
          <span class="login_head">用户注册</span>
        </div>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
          <el-form-item prop="username" :class="ruleFormIcon.username?'':'icon_show'">
            <el-input v-model.trim="ruleForm.username" placeholder="账号为字母、数字、下划线或其组合"></el-input>
          </el-form-item>
          <el-form-item prop="email" :class="ruleFormIcon.email?'':'icon_show'">
            <el-input v-model.trim="ruleForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>
          <el-form-item prop="cname" :class="ruleFormIcon.cname?'':'icon_show'">
            <el-input v-model.trim="ruleForm.cname" placeholder="请输入中文名"></el-input>
          </el-form-item>
          <el-form-item prop="password" :class="ruleFormIcon.password?'':'icon_show'">
            <el-input
              auto-complete="new-password"
              autocomplete="off"
              v-model.trim="ruleForm.password"
              :type="pwdCheck?'text':'password'"
              placeholder="密码为大小写字母及数字组合，不少于6位"
            >
              <i
                slot="suffix"
                :title="truePwdCheck?'隐藏密码':'显示密码'"
                :class="pwdCheck?'el-icon-view icon_blue':'el-icon-view'"
                @click="pwdCheck=!pwdCheck"
              ></i>
            </el-input>
          </el-form-item>
          <el-form-item prop="truePassword" :class="ruleFormIcon.truePassword?'':'icon_show'">
            <el-input
              auto-complete="new-password"
              autocomplete="off"
              v-model.trim="ruleForm.truePassword"
              :type="truePwdCheck?'text':'password'"
              placeholder="请确认密码"
            >
              <i
                slot="suffix"
                :title="truePwdCheck?'隐藏密码':'显示密码'"
                :class="truePwdCheck?'el-icon-view icon_blue':'el-icon-view'"
                @click="truePwdCheck=!truePwdCheck"
              ></i>
            </el-input>
          </el-form-item>
        </el-form>
        <el-form :model="yzms" :rules="yzmRules" ref="yzms" class="demo-ruleForm">
          <el-form-item prop="yzm" class="yzm" :class="ruleFormIcon.yzm?'':'icon_show'">
            <el-input v-model.trim="yzms.yzm" placeholder="请输入验证码"></el-input>
            <img class="yzm_img" title="看不清？换一张" :src="imgSrc" @click="getImg()" />
          </el-form-item>
        </el-form>
        <el-form class="demo-ruleForm">
          <el-form-item>
            <el-button class="btn_sub sub1" type="primary" @click.prevent="submitForm()">注 册</el-button>
          </el-form-item>
          <el-form-item>
            <el-button class="btn_sub sub2" @click.prevent="login">
              <i class="el-icon-arrow-left"></i>&nbsp;&nbsp;登录已有账号
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>
<script>
import { getCookie, clearCookie, setCookie } from "@/services/cookie.js";
export default {
  data() {
    var validatePass = (rule, value, callback) => {
      if (value !== this.ruleForm.password) {
        this.ruleFormIcon.truePassword = false;
        callback(new Error("密码和确认密码不一致"));
      } else {
        this.ruleFormIcon.truePassword = true;
        callback();
      }
    };
    var validateUser = (rule, value, callback) => {
      let reg = new RegExp(/^[a-zA-Z0-9-_]{0,50}$/);
      if (value == "") {
        this.ruleFormIcon.username = false;
        callback(new Error("请输入账号"));
      } else if (!reg.test(value)) {
        this.ruleFormIcon.username = false;
        callback(new Error("支持大小写字母，数字，-_ ，长度不超过50个字符"));
      } else {
        let url = `/awecloud/dex/user/${value}`;
        this.$http
          .get(url)
          .then(response => {
            if (response.data.success == 1) {
              this.ruleFormIcon.username = true;
              callback();
            } else {
              this.ruleFormIcon.username = false;
              callback(new Error(response.data.errMsg));
            }
          })
          .catch(function(response) {});
      }
    };
    var validateEmail = (rule, value, callback) => {
      let reg = new RegExp(
        /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/
      );
      if (value == "") {
        this.ruleFormIcon.email = false;
        callback(new Error("请输入邮箱"));
      } else if (!reg.test(value)) {
        this.ruleFormIcon.email = false;
        callback(new Error("请输入正确的邮箱格式"));
      } else {
        let url = `/awecloud/dex/email/${value}`;
        this.$http
          .get(url)
          .then(response => {
            if (response.data.success == 1) {
              this.ruleFormIcon.email = true;
              callback();
            } else {
              this.ruleFormIcon.email = false;
              callback(new Error(response.data.errMsg));
            }
          })
          .catch(function(response) {});
      }
    };
    var validatePassword = (rule, value, callback) => {
      let reg = new RegExp(
        /^.*(?=.{6,50})(?=.*\d)(?=.*[A-Z]{1,})(?=.*[a-z]{1,}).*$/
      );
      if (value == "") {
        this.ruleFormIcon.password = false;
        callback(new Error("请输入密码"));
      } else if (!reg.test(value)) {
        this.ruleFormIcon.password = false;
        callback(new Error("密码包含大小写字母、数字，长度不小于6位"));
      } else {
        this.ruleFormIcon.password = true;
        callback();
      }
    };
    var validateCname = (rule, value, callback) => {
      if (value == "") {
        this.ruleFormIcon.cname = false;
        callback(new Error("请输入中文姓名"));
      } else {
        this.ruleFormIcon.cname = true;
        callback();
      }
    };
    var validateYzm = (rule, value, callback) => {
      if (value == "") {
        this.ruleFormIcon.yzm = false;
        this.yzmState = false;
        callback(new Error("请输入验证码"));
      } else {
        let url = `/awecloud/dex/verifyCaptcha?id=${this.imgId}&value=${value}`;
        this.$http
          .get(url)
          .then(response => {
            if (response.data.success == 1) {
              this.ruleFormIcon.yzm = true;
              this.yzmState = true;
              callback();
            } else {
              this.ruleFormIcon.yzm = false;
              this.yzmState = false;
              callback(new Error(response.data.errMsg));
            }
          })
          .catch(function(response) {});
      }
    };
    return {
      form: {
        username: "",
        password: ""
      },
      visible: true,
      checked: false,
      msg: "",
      msgShow: false,
      active: "login",
      pwdCheck: false,
      truePwdCheck: false,
      ruleForm: {
        username: "",
        cname: "",
        password: "",
        truePassword: "",
        email: ""
      },
      yzms: {
        yzm: ""
      },
      yzmRules: {
        yzm: [{ validator: validateYzm, trigger: "blur" }]
      },
      yzmState: false,
      ruleFormIcon: {
        username: true,
        cname: true,
        password: true,
        truePassword: true,
        email: true,
        yzm: true
      },
      rules: {
        username: [{ validator: validateUser, trigger: "blur" }],
        cname: [{ validator: validateCname, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        truePassword: [{ validator: validatePass, trigger: "blur" }],
        email: [{ validator: validateEmail, trigger: "blur" }]
      },
      imgSrc: "",
      imgId: ""
    };
  },
  mounted() {
    this.init();
  },
  created() {
    if (getCookie("username") && getCookie("password")) {
      this.checked = true;
      this.form.username = window.atob(getCookie("username"));
      this.form.password = window.atob(getCookie("password"));
    } else {
      this.checked = false;
    }
  },
  methods: {
    init() {
      if (this.$route.params.username != undefined) {
        this.form.username = this.$route.params.username;
        this.form.password = this.$route.params.password;
      }
    },
    //登录请求
    login_request() {
      let url = `/awecloud/dex/login`;
      let query = this.form;
      this.$http
        .post(url, JSON.stringify(query), {
          headers: {
            "Content-Type": "application/json;charset=UTF-8"
          }
        })
        .then(response => {
          if (response.data.success == 1) {
            window.location.href = "/awecloud/ui/";
          } else if (response.data.success == 0) {
            this.msg = response.data.errMsg;
            this.msgShow = true;
            // if (errCode.indexOf("invalid_login") != -1) {
            //   this.hint = "帐号或密码错误";
            // }
            // if (errCode.indexOf("too_many_errors1") != -1) {
            //   this.hint = "该账号已被冻结";
            // }
            // if (errCode.indexOf("no_user") != -1) {
            //   this.hint = "未注册此用户";
            // }
            // if (errCode.indexOf("no_pass") != -1) {
            //   this.hint = "该账户未审批";
            // }
            // if (errCode.indexOf("too_many_errors2") != -1) {
            //   var num = errCode.split("|")[1].split("_")[0];
            //   var time = errCode.split("|")[1].split("_")[1];
            //   this.hint =
            //     "该账号密码连续错误次数达到" +
            //     num +
            //     "次，系统自动冻结" +
            //     time +
            //     "分钟";
            // }
            // if (errCode.indexOf("new_login") != -1) {
            //   this.hint =
            //     "您的账户已经在其他地方登陆，点击确定重新登录。如果不是您自己操作，您的密码可能已经丢失，请尽快修改密码。";
            // }
          }
        })
        .catch(function(response) {
          console.log(response);
        });
    },
    login_remember_info() {
      // console.log(this.checked);
      if (this.checked) {
        setCookie("username", window.btoa(this.form.username));
        setCookie("password", window.btoa(this.form.password));
      } else {
        clearCookie("username");
        clearCookie("password");
      }
      this.login_request();
    },
    changePass() {
      this.visible = !this.visible;
    },
    register() {
      this.active = "register";
      this.getImg();
    },
    getImg() {
      let url = `/awecloud/dex/getCaptcha?width=240&height=60`;
      this.$http
        .get(url)
        .then(response => {
          if (response.data.success == 1) {
            // console.log(response.data.data.captcha);
            this.imgId = response.data.data.id;
            this.imgSrc = response.data.data.captcha;
            // this.$router.push({
            //   path: "/login",
            //   query: {
            //     username: this.ruleForm.username,
            //     password: this.ruleForm.password
            //   }
            // });
          }
        })
        .catch(function(response) {});
    },
    submitForm() {
      let self = this;
      let setI = setInterval(function() {
        // console.log(self.yzmState);
        if (self.yzmState) {
          clearInterval(setI);
          self.submitAll();
        }
      }, 50);
    },
    submitAll() {
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          let url = `/awecloud/dex/register`;
          let query = {
            name: this.ruleForm.username,
            alias: this.ruleForm.cname,
            password: this.ruleForm.password,
            email: this.ruleForm.email,
            phone: "",
            avatar: ""
          };
          this.$http
            .post(url, query)
            .then(response => {
              if (response.data.success == 1) {
                // console.log(response.data.data);
                this.$message({
                  message: "注册成功",
                  type: "success",
                  duration: 1000
                });
                let self = this;
                self.$router.push({
                  name: "Login"
                });
                // self.$router.push({
                //   name: "Login",
                //   params: {
                //     username: self.ruleForm.username,
                //     password: self.ruleForm.password
                //   }
                // });
              }
            })
            .catch(function(response) {});
        } else {
          return false;
        }
      });
    },
    login() {
      this.active = "login";
    }
  }
};
</script>
<style scoped>
.login_backg {
  height: 100vh;
  background: url("~@/assets/imgs/shop_img_banner_test.png") center center;
  background-size: 100% 100%;
  overflow: auto;
}
.login_all {
  width: 500px;
  height: 100%;
  padding-top: 20vh;
  margin: 0 auto;
}
.login {
  min-width: 500px;
  font-size: 16px;
}
.login .el-card__header {
  padding: 10px;
}
.login_head {
  display: block;
  width: 100%;
  font-size: 16px;
  font-weight: bold;
  text-align: center;
  color: #1a2236;
}
.login .el-form-item {
  margin-bottom: 22px;
}
.warning_icon_div {
  display: inline-block;
  width: 9%;
}
.login .el-input {
  width: 80%;
  margin-left: 10%;
}
.login .el-input__inner {
  height: 40px;
  border-radius: 20px;
  padding-left: 20px;
  padding-right: 38px;
  border: solid 1px #9cb5f8;
}
.login .el-input__suffix {
  right: 15px;
  font-size: 18px;
}
.login .rembme {
  padding-left: 14%;
  margin-bottom: 10px;
}
.login .el-button {
  width: 80%;
  margin-left: 10%;
  height: 40px;
  border-radius: 20px;
}
.sub1 {
  background-color: #264dd9;
  color: #fff;
}
.sub2 {
  background-color: #dde4ff;
  color: #264dd9;
}

.headercontainer {
  max-width: 960px;
  margin: 10px 0px 15px 0px;
  margin-right: auto;
  margin-left: auto;
}

.center-logo {
  /* margin: 8px 0; */
  text-align: center;
}

.el-form--label-top .el-form-item__label {
  padding: 0px;
}

.logo {
  width: 160px;
  height: 36px;
}
.login_forms {
  margin-top: 20px;
}
.login_msg {
  width: 100%;
  height: 30px;
  margin-top: 10px;
  color: #c62249;
  text-align: center;
  position: relative;
  top: 0;
  opacity: 1;
  animation: login_in 1s;
}

@keyframes login_in {
  0% {
    top: 100%;
    opacity: 0;
  }
  100% {
    top: 0;
    opacity: 1;
  }
}
.icon_show {
  position: relative;
}
.icon_show::before {
  content: "";
  width: 20px;
  height: 20px;
  position: absolute;
  top: 10px;
  left: 15px;
  background: url("~@/assets/imgs/ic_warning.png") no-repeat center center;
}
.icon_blue {
  color: #5c82ff;
}
.login .yzm .el-input {
  width: 40%;
  margin-left: 10%;
}
.yzm {
  position: relative;
}
.yzm .yzm_img {
  position: absolute;
  width: 30%;
  margin-left: 5%;
  cursor: pointer;
}
</style>
<style>
.login .el-input__suffix {
  font-size: 20px;
  right: 10px;
}
.login .el-form-item__error {
  left: 14%;
}
</style>