<template>
  <div class="login-container">
    <el-form
      ref="loginForm"
      :model="loginForm"
      :rules="loginRules"
      class="login-form"
      auto-complete="on"
      label-position="left"
    >
      <div class="image-container">
        <img src="@/assets/login/image.png" alt="" />
      </div>
      <div class="right-container">
        <div class="empty-height" />
        <div class="form-container">
          <div class="title">家电商城后台管理</div>
          <el-form-item prop="username">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input
              ref="username"
              v-model="loginForm.username"
              placeholder="请输入用户名"
              name="username"
              type="text"
              tabindex="1"
              auto-complete="on"
            />
          </el-form-item>

          <el-form-item prop="password">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="请输入密码"
              name="password"
              tabindex="2"
              auto-complete="off"
              @keyup.enter.native="handleLogin"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
              />
            </span>
          </el-form-item>

          <el-form-item prop="codeValue">
            <span class="svg-container">
              <svg-icon icon-class="password" />
            </span>
            <el-input
              ref="codeValue"
              v-model="loginForm.codeValue"
              placeholder="请输入验证码"
              name="codeValue"
              type="text"
              tabindex="3"
              auto-complete="off"
              @keyup.enter.native="handleLogin"
            />
            <div class="code" @click="getCode">
              <img :src="'data:image/jpeg;base64,' + codeImage" alt="" />
            </div>
          </el-form-item>

          <el-checkbox v-model="isRemenberPw">记住密码</el-checkbox>

          <div class="button-container">
            <el-button
              :loading="loading"
              type="primary"
              @click.native.prevent="handleLogin"
              >登录</el-button
            >
          </div>
        </div>
      </div>
    </el-form>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import Cookies from "js-cookie";
import { getCode } from "@/api/user";

export default {
  name: "Login",
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length <= 0) {
        callback(new Error("请输入用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length <= 0) {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      if (value.length <= 0) {
        callback(new Error("请输入验证码"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        password: "",
        code: "",
        codeValue: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "change", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "change", validator: validatePassword },
        ],
        codeValue: [
          { required: true, trigger: "change", validator: validateCode },
        ],
      },
      loading: false,
      passwordType: "password",
      redirect: undefined,
      isRemenberPw: false,
      codeImage: "",
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    // 获取缓存信息
    if (localStorage.getItem("greemall_login")) {
      let storageData = JSON.parse(localStorage.getItem("greemall_login"));
      this.loginForm.username = storageData.username;
      this.isRemenberPw = storageData.isRemenberPw;
    }
    if (this.isRemenberPw) {
      this.getCookie();
    }

    this.getCode();
  },
  methods: {
    // 获取验证码
    getCode() {
      getCode().then((res) => {
        console.log(res);
        this.loginForm.code = res.data.code;
        this.codeImage = res.data.pic;
      });
    },

    // 显示隐藏密码
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },

    // 登录
    handleLogin() {
      console.log(this.loginForm);
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store
            .dispatch("user/login", this.loginForm)
            .then(() => {
              console.log(this.redirect);
              this.$router.push({ path: this.redirect || "/" });
              this.saveUnAndPw();
              this.loading = false;
            })
            .catch(() => {
              this.getCode();
              this.loginForm.codeValue = "";
              this.loading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 处理账号密码的储存
    saveUnAndPw() {
      let storageData = {
        username: this.loginForm.username,
        isRemenberPw: this.isRemenberPw,
      };
      localStorage.setItem("greemall_login", JSON.stringify(storageData));

      if (this.isRemenberPw) {
        this.setCookie(this.loginForm.username, this.loginForm.password, 7);
      }
    },

    //设置cookie
    setCookie(c_name, c_pwd, exdays) {
      var exdate = new Date(); //获取时间
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exdays); //保存的天数
      //字符串拼接cookie
      window.document.cookie =
        "greemall_username" +
        "=" +
        c_name +
        ";path=/;expires=" +
        exdate.toGMTString();
      window.document.cookie =
        "greemall_password" +
        "=" +
        c_pwd +
        ";path=/;expires=" +
        exdate.toGMTString();
    },

    //读取cookie
    getCookie: function () {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split("; "); //这里显示的格式需要切割一下自己可输出看下
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split("="); //再次切割
          //判断查找相对应的值
          if (arr2[0] == "greemall_username") {
            this.loginForm.username = arr2[1]; //保存到保存数据的地方
          } else if (arr2[0] == "greemall_password") {
            this.loginForm.password = arr2[1];
          }
        }
      }
    },

    //清除cookie
    clearCookie: function () {
      this.setCookie("", "", -1); //修改2值都为空，天数为负1天就好了
    },
  },
};
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

$bg: #283443;
$light_gray: #fff;
$cursor: #fff;
$back: #333;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  background: url("~@/assets/login/background.png") center center;
  background-size: cover;
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 0px;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      color: $back;
      height: 47px;
      caret-color: $back;
      border-bottom: 1px solid #eaeaea;
      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $cursor inset !important;
        -webkit-text-fill-color: $back !important;
      }
    }
  }

  .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    // background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
    margin-bottom: 10px;
  }

  .el-checkbox {
    margin-top: 10px;
    margin-left: 6px;
  }

  .el-form-item__error {
    left: 30px;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #889aa4;
$light_gray: #eee;

.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 1070px;
    max-width: 100%;
    padding: 0 35px 0;
    padding-top: calc(50vh - 230px);
    margin: 0 auto;
    overflow: hidden;
    display: flex;
  }

  .image-container {
    img {
      width: 560px;
      height: 460px;
    }
  }

  .right-container {
    width: 440px;
    height: 460px;
    .empty-height {
      height: 77px;
    }
    .form-container {
      padding: 20px 30px 27px 40px;
      background: #fff;
      border-radius: 0 15px 15px 0;
      .title {
        font-size: 24px;
        font-weight: bold;
        letter-spacing: 4px;
        text-align: center;
        padding: 10px 0 13px;
        color: #3a8ee6;
      }
    }
  }

  .tips {
    font-size: 14px;
    color: #fff;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 16px;
      }
    }
  }

  .svg-container {
    padding: 6px 5px 6px 5px;
    color: #33aef7;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    border-radius: 15px 15px 0 0;
    overflow: hidden;
    img {
      width: 100%;
      display: block;
    }
  }

  .show-pwd {
    position: absolute;
    right: 30px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }

  .code {
    position: absolute;
    right: 30px;
    top: 7px;
    cursor: pointer;
    img {
      height: 30px;
    }
  }

  .button-container {
    text-align: center;
    margin-top: 20px;
    button {
      font-size: 16px;
      width: 100%;
      height: 45px;
      border-radius: 45px;
      background: #33aef7;
      box-shadow: 2px 3px 8px 0px rgba(5, 155, 245, 0.75);
    }
  }
}

@media only screen and (max-width: 600px) {
  .image-container {
    display: none;
  }
  .form-container {
    border-radius: 15px !important;
  }
}
</style>
