<template>
  <div class="bigbox">
    <div class="img">
      <div class="login">
        <div class="header">
          <h1 id="welcom">欢迎使用家政预约平台</h1>
        </div>

        <el-tabs v-model="activeTab" @tab-change="handleClick" class="demo-tabs">
          <el-tab-pane label="手机号登陆" name="first"></el-tab-pane>
          <el-tab-pane label="邮箱登陆" name="second"></el-tab-pane>
          <el-tab-pane label="账号密码登陆" name="third"></el-tab-pane>
        </el-tabs>
        <div v-if="this.loginMethod.usePhone">
          <input type="text" placeholder="手机号" required v-model="phone" />

          <br />
          <input class="verificationCode" type="text" placeholder="验证码" required v-model="validateCode" />
          <input @click="getValidateCode('1')" class="verificationButton" type="button" value="获取验证码" />
          <div class="radio">
            <label class="lable">家政工作人员</label>
            <input class="rad" type="radio" value="1" v-model="usertype" />
            &nbsp;&nbsp;
            <label class="lable">雇主</label>
            <input class="rad" type="radio" value="2" v-model="usertype" />
          </div>

          <br />
          <input type="submit" @click.prevent="login($event, '1')" value="Login" @keyup.enter.native="login($event, '1')" />
          <p class="regis" @click="regis">没有账户?</p>
        </div>
        <div v-if="this.loginMethod.useEmail">
          <input type="text" placeholder="邮箱" required v-model="email" />

          <br />
          <input class="verificationCode" type="text" placeholder="验证码" @keyup.enter.native="login" required
            v-model="validateCode" />
          <input @click="getValidateCode('2')" class="verificationButton" type="button" value="获取验证码" />
          <div class="radio">
            <label class="lable">家政工作人员</label>
            <input class="rad" type="radio" value="1" v-model="usertype" />
            &nbsp;&nbsp;
            <label class="lable">雇主</label>
            <input class="rad" type="radio" value="2" v-model="usertype" />
          </div>
          <div class="bigerror" v-if="vali.unvali || vali.pwdvali"></div>
          <br />
          <input type="submit" @click.prevent="login($event, '2')" value="Login" @keyup.enter.native="login($event, '2')" />
          <p class="regis" @click="regis">没有账户?</p>
        </div>
        <div v-if="this.loginMethod.useName">
          <input type="text" placeholder="账户名" required v-model="username" />

          <input type="password" placeholder="密码" required v-model="password" />
          <div class="radio">
            <label class="lable">家政工作人员</label>
            <input class="rad" type="radio" value="1" v-model="usertype" />
            &nbsp;&nbsp;
            <label class="lable">雇主</label>
            <input class="rad" type="radio" value="2" v-model="usertype" />
          </div>
          <div class="bigerror" v-if="this.v">
            <div class="error" v-html="errormsg"></div>
          </div>
          <br />
          <input type="submit" @click.prevent="login($event, '3')" value="Login" @keyup.enter.native="login($event, '3')" />
          <p class="regis" @click="regis">没有账户?</p>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { mapMutations } from "vuex";
import popmessage from "@/components/tip/index.js";

import { phoneValidate, phoneLogin, emailValidate, emailLogin, UserLogin } from "@/api";
export default {
  name: "AdminLogin",
  data() {
    return {
      v: false,
      activeTab: "first",
      usertype: "",
      username: "",
      password: "",
      phone: "",
      validateCode: "",
      email: "",
      errorList: [],
      errormsg: "",
      vali: {
        unvali: true,
        pwdvali: "",
      },
      loginMethod: {
        usePhone: true,
        useEmail: false,
        useName: false,
      },
    };
  },
  computed: {
    ...mapState("LoginStore", ["login_name", "tokenStore"]),
  },
  created(){
  },
  methods: {
    ...mapMutations("LoginStore", ["setLoginName"]),
    validate3() {
      this.errormsg = "";
      if (this.username == "" || this.password == "" || this.usertype == "") {
        this.errormsg += "请填写完整信息";
        this.v = true;
        return false;
      }
      if (this.username.length < 4) {
        this.errormsg += "账户名长度不得小于四位";
        this.v = true;
        return false;
      }
      var pPattern =
        /^.*(?=.{6,})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/;
      if (!pPattern.test(this.password)) {
        this.errormsg +=
          "密码最少6位，包括至少1个大写字母，<BR/>1个小写字母，1个数字，1个特殊字符<br/>";
        this.v = true;
        return false;
      }
      return true;
    },
    //切换登陆方式
    handleClick(tag) {
      if (tag === "first") {
        this.loginMethod.usePhone = true;
        this.loginMethod.useEmail = false;
        this.loginMethod.useName = false;
      } else if (tag === "second") {
        this.loginMethod.usePhone = false;
        this.loginMethod.useEmail = true;
        this.loginMethod.useName = false;
      } else if (tag === "third") {
        this.loginMethod.usePhone = false;
        this.loginMethod.useEmail = false;
        this.loginMethod.useName = true;
      }
    },

    //获取验证码
    getValidateCode(i) {
      if (i === "1") {
        //电话号码格式验证
        const phoneRegx =
          /^1[3456789]\d{9}$/;
        if (!phoneRegx.test(this.phone)) {
          popmessage({ type: "error", str: "手机号不正确" });
          return;
        } else if (this.usertype == "") {
          popmessage({ type: "error", str: "请选择你的角色" });
          return;
        }
        popmessage({ type: "success", str: "正在发送验证码" });
        const parmas = {
          phone: this.phone,
          userType: this.usertype,
        };
        phoneValidate(parmas).then((response) => {
          if (response.data.code === 200) {
          } else {
            popmessage({ type: "error", str: response.data.msg });
          }
        });
      } else if (i === "2") {
        //邮箱格式验证
        const eamilRegx =
          /^[\w\-]+(\.[\w\-]+)*@[\w\-]+(\.[\w\-]+)+$/;
        if (!eamilRegx.test(this.email)) {
          popmessage({ type: "error", str: "请填写正确邮箱" });
          return;
        } else if (this.usertype == "") {
          popmessage({ type: "error", str: "请选择你的角色" });
          return;
        }
        popmessage({ type: "success", str: "正在发送验证码" });
        const parmas = {
          email: this.email,
          userType: this.usertype,
        };
        emailValidate(parmas).then((response) => {
          if (response.data.code == 200) {
          } else {
            popmessage({ type: "error", str: response.data.msg });
          }
        });
      }
    },

    login(e, i) {
      e.currentTarget.style.backgroundColor = "#39566e";
      e.currentTarget.value = "Logining";
      this.setLoginName(this.username);
      let params = {}
      if (i == "1") {
        params = {
          object: this.phone,
          userType: this.usertype,
          code: this.validateCode,
        };
        phoneLogin(params)
          .then((response) => {
            this.$store.commit("changeType", params.userType);
            if (response.data.code === 200 && this.usertype === "1") {
              console.log(response.data.data)
              this.phone = "";
              this.validateCode = "";
              this.userType = "";
              //传到本地
              if (response.data.data.token) {
                localStorage.setItem("token", response.data.data.token);
              }
              localStorage.setItem("userType", this.usertype);
              popmessage({ type: "success", str: "登录成功" });
              setTimeout(() => {
                this.$router.go(0);
              }, 500);
              this.$router.push({
                name: "thehome",
                params: {
                  username: this.login_name,
                },
              });
            }else if(response.data.code === 200 && this.usertype === "2"){
              localStorage.setItem("token", response.data.data.token);
              localStorage.setItem("userType", this.usertype);
              this.phone = "";
              this.validateCode = "";
              this.userType = "";
              popmessage({ type: "success", str: "登录成功" });
              setTimeout(() => {
                this.$router.go(0);
              }, 500);
              this.$router.push({
                name: "introduce",
              });
            }
            else {
              this.phone = "";
              this.validateCode = "";
              this.usertype = "";
              popmessage({ type: "error", str: "验证码错误" });
              this.$router.replace("/loginview");
            }
          })
          .catch((error) => {
            this.phone = "";
            this.validateCode = "";
            this.usertype = "";
            this.$router.go(0);
            console.log("错误信息：", error);
            alert("登陆失败请重试！");
          });
      } else if (i == "2") {
        params = {
          object: this.email,
          userType: this.usertype,
          code: this.validateCode,
        };
        emailLogin(params)
          .then((response) => {
            this.$store.commit("changeType", params.userType);

            if (response.data.code === 200 && this.usertype == "1") {
              this.email = "";
              this.validateCode = "";
              this.userType = "";
              //传到本地
              if (response.data.data.token) {
                localStorage.setItem("token", response.data.data.token);
              }
              localStorage.setItem("userType", this.usertype);
              popmessage({ type: "success", str: "登录成功" });
              setTimeout(() => {
                this.$router.go(0);
              }, 500);
              this.$router.push({
                name: "thehome",
                params: {
                  username: this.login_name,
                },
              });
            } else if (response.data.code === 200 && this.usertype === "2") {
              localStorage.setItem("token", response.data.data.token);
              localStorage.setItem("userType", this.usertype);
              this.email = "";
              this.validateCode = "";
              this.userType = "";
              popmessage({ type: "success", str: "登录成功" });
              setTimeout(() => {
                this.$router.go(0);
              }, 500);
              this.$router.push({
                name: "introduce",
              });
            } else {
              this.email = "";
              this.validateCode = "";
              this.userType = "";
              popmessage({ type: "error", str: "验证码错误" });
              this.$router.replace("/loginview");
            }
          })
          .catch((error) => {
            this.email = "";
            this.validateCode = "";
            this.usertype = "";
            this.$router.go(0);
            console.log("错误信息：", error);
            alert("登陆失败请重试！");
          });
      } else if (i == "3") {
        var v = this.validate3();
        console.log("validate3", v);
        if (!this.validate3()) {
          return;
        }

        const parm = {
          userName: this.username,
          password: this.password,
          userType: this.usertype,
        };
        UserLogin(parm)
          .then((response) => {
            this.$store.commit("changeType", parm.userType);
            if (response.data.code === 200 && this.usertype == "1") {
              this.username = "";
              this.password = "";
              this.userType = "";
              //传到本地
              if (response.data.data.token) {
                localStorage.setItem("token", response.data.data.token);
              }
              localStorage.setItem("userType", this.usertype);
              popmessage({ type: "success", str: "登录成功" });
              setTimeout(() => {
                this.$router.go(0);
              }, 500);
              this.$router.push({
                name: "thehome",
                params: {
                  username: this.login_name,
                },
              });
            } else if (response.data.code === 200 && this.usertype == "2") {
              localStorage.setItem("token", response.data.data.token);
              localStorage.setItem("userType", this.usertype);
              this.username = "";
              this.password = "";
              this.userType = "";
              popmessage({ type: "success", str: "登录成功" });
              setTimeout(() => {
                this.$router.go(0);
              }, 500);
              this.$router.push({
                name: "introduce",
              });
            } else {
              this.username = "";
              this.password = "";
              this.userType = "";
              alert("账户密码错误！");
              this.$router.replace("/loginview");
            }
          })
          .catch((error) => {
            this.username = "";
            this.password = "";
            this.$router.go(0);
            console.log("错误信息：", error);
            alert("登陆失败请重试！");
          });
      }
    },
    regis() {
      this.$router.push("/userreg");
    },
  },
};
</script>

<style scoped>
img {
  width: 100%;
}

.img {
  height: 43rem;
  width: 80rem;
  position: absolute;
  top: 55%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: url("../../assets/2.png");
  background-size: contain;
}

.login {
  position: relative;
  width: 40rem;
  height: 35rem;
  right: 0rem;
  top: 7rem;
  left: 40rem;
}

#welcom {
  color: #272727;
  font-weight: 700;
  font-size: 1.5rem;
  border-bottom: 0.0556rem solid #e7e0e0;
  margin-top: -0.7222rem;
  padding-bottom: 1.1111rem;
}

input {
  width: 50%;
  height: 2.6rem;
  margin-top: 1rem;
  font-size: 1rem;
}

.logintitle {
  font-size: 1.5rem;
  margin-bottom: 2.2222rem;
}

.regis {
  font-size: 0.8333rem;

  cursor: pointer;
}

input[type="submit"] {
  font-size: 0.8889rem;
  width: 13rem;
  background-color: #3e81b8;
  color: white;
  font-weight: bold;
}

input[type="submit"]:hover {
  background: #2e2d2d;
  color: #fff;
}

.error {
  color: #e45252;
  text-align: start;
  margin-left: 8rem;
  margin-top: 0.75rem;
  margin-bottom: -0.05rem;
  font-size: 0.875rem;
}

.radio {
  margin: 0 auto;
  width: 55%;
  margin-top: 1.15rem;
  box-sizing: border-box;
  margin-bottom: 0.4rem;
}

.rad {
  margin-top: -0.1rem;
  margin-bottom: 0.05rem;
  width: 1.125rem;
  height: 1.125rem;
  vertical-align: middle;
}

.lable {
  display: inline-block;
}

/* 选择登陆方式页头 */
::v-deep .el-tabs__item.is-active {
  color: #557c70;
}

::v-deep .el-tabs__item:hover {
  color: #557c70;
  cursor: pointer;
}

::v-deep .el-tabs__active-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 2px;
  background-color: #557c70;
  z-index: 1;
  transition: width var(--el-transition-duration) var(--el-transition-function-ease-in-out-bezier),
    transform var(--el-transition-duration) var(--el-transition-function-ease-in-out-bezier);
  list-style: none;
}

::v-deep .el-tabs__nav-next,
.el-tabs__nav-prev {
  position: absolute;
  cursor: pointer;
  line-height: 44px;
  font-size: 1rem;
  color: var(--el-text-color-secondary);
  width: 20px;
  text-align: center;
  left: 0.5rem;
}

::v-deep .el-tabs__item {
  padding: 0 20px;
  height: 3.5rem;
  box-sizing: border-box;
  line-height: var(--el-tabs-header-height);
  display: inline-block;
  list-style: none;
  font-size: 1rem;
  font-weight: 530;
  color: var(--el-text-color-primary);
  position: relative;
  left: 3rem;
}

::v-deep .el-tabs {
  --el-tabs-header-height: 3rem;
  width: 26rem;
  margin-left: 6rem;
}

::v-deep .el-tabs__nav-wrap::after {
  content: "";
  position: absolute;
  left: 3rem;
  bottom: 0;
  width: 79%;
  height: 2px;
  background-color: var(--el-border-color-light);
  z-index: var(--el-index-normal);
}

.verificationCode {
  width: 12rem;
  margin-left: 0rem;
}

.verificationButton {
  margin-left: 1rem;
  width: 7rem;
  font-size: 0.8rem;
  background-color: #ecf5ff;
  color: #52a7f8;
  border: #6c9ecc;
  border-radius: 0.5rem;
  cursor: pointer;
}
</style>
