<template>
  <div>
    <header id="header">
      <div class="container">
        <div id="logo" class="pull-left">
          <a :href="portalUrl"><img src="@/assets/img/logo.png" style="margin: 20px!important;" alt="" title="" /></a>
        </div>
      </div>
    </header>
    <main id="main" >
      <section id="login" class="wow fadeInUp">
        <div class="container" style="height: 40px!important;">
          <h4>系统登录</h4>
          <div class="tab">
            <ul class="login-menu">
              <li id="a1" @click="cur = true" :class="{ active: cur == true }" style="font-size: 18px;">密码登录</li>
              <!-- <li id="a2" @click="cur = false" :class="{ active: cur == false }" style="font-size: 18px;">短信登录</li> -->
            </ul>
            <div class="cl"></div>
          </div>
        </div>
      </section>
    </main>
    <div class="login-container">
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="cur?nameRules:phoneRules"
        class="login-form"
        auto-complete="on"
        label-position="left"
      >
        <div v-show="cur == true" class="Cbody_item">
          <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"
              maxlength="30"
            />
          </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"
              maxlength="16"
              :type="passwordType"
              placeholder="请输入密码"
              name="password"
              tabindex="2"
              auto-complete="on"
              @keyup.enter.native="handleLogin"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon
                :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
              />
            </span>
          </el-form-item>
        </div>

        <div v-show="cur == false" class="Cbody_item">
          <el-form-item prop="mobile">
            <span class="svg-container">
              <svg-icon icon-class="user"/>
            </span>
            <el-input
              ref="mobile"
              v-model="loginForm.mobile"
              placeholder="请输入手机号"
              name="mobile"
              type="text"
              tabindex="1"
              auto-complete="on"
            />
          </el-form-item>
          <el-form-item prop="code">
            <span class="svg-container">
              <svg-icon icon-class="password"/>
            </span>
            <el-input
              ref="code"
              v-model="loginForm.code"
              type="text"
              placeholder="请输入验证码"
              name="code"
              abindex="2"
              maxlength="6"
              auto-complete="on"
              @keyup.enter.native="handleLogin"
            />
            <span class="show-pwd">
              <el-button
                :loading="sending"
                :disabled="sendDisabled"
                size="small"
                class="btn-blue"
                style="color: #ffff!important;"
                @click="onSendSms"
              >{{ sendButtonText }}</el-button
              >
            </span>
          </el-form-item>
        </div>
        <div>
          <el-button :loading="loading" class="btn btn-primary btn-blue" style="width: 100%; margin: 30px auto; font-size: 18px;color: #ffff"
                     @click.native.prevent="handleLogin">登&nbsp;&nbsp;录
          </el-button>
          <!-- <p><a href="/register" style="color: #0969bd!important; font-size: 16px!important;">注册新用户</a> <a href="/retrieve" style="color: #0969bd!important;font-size: 16px!important;">找回密码?</a></p> -->
        </div>
    </el-form>
    </div>

    <footer id="footer" style="width:100%;line-height: 30px;">
      <div class="container">
        <div>
          <table style="text-align: left;line-height: 30px;width:1200px;margin-left: auto;margin-right: auto;">
            <tr>
              <td>
                <img src="@/assets/pic/code.png">
              </td>
              <td>
                <p><a href="">联系我们</a></p>
                <p><a href="">咨询热线：13911064391</a></p>
                <p><a href="">电邮：89705132@qq.com</a></p>
              </td>
              <td>
                <p><a href="http://www.lovecode.cc/about.html">关于我们</a></p>
              </td>
              <td>
                <p><a href="http://www.lovecode.cc/join-us.html">加入我们</a></p>
                <p><a href="http://www.lovecode.cc/job-offers.html">招聘信息</a></p>
              </td>
            </tr>
          </table>
        </div>
        <div class="copyright">
          海南关键科技有限公司 版权所有 琼ICP备2023014024号 琼公网安备 46010002000162号
        </div>
        <div class="credits">
        </div>
      </div>
    </footer>
  </div>
</template>

<script>
  import {getCodeUserLogin} from "@/api/login";
  import Cookie from "js-cookie";
  import moment from "moment";
  import store from "@/store";

  export default {
    name: "Login",
    data() {
      return {
        loginForm: {
          username: "",
          mobile: "",
          password: "",
          rememberMe: false,
          code: "",
          uuid: ""
        },
        portalUrl: '',
        cur: true, //true代表密码, false代表短信
        sending: false,
        sendDisabled: false,
        loading: false,
        timer: 0,
        passwordType: "password",
        redirect: undefined,
      // name表单校验
      nameRules: {
        username: [
          { required: true, message: "用户名称不能为空", trigger: "blur" },
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" },
          { min: 6, max: 16, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ],
      },
      // phone表单校验
      phoneRules: {
        mobile: [
          { required: true, message: "手机号码不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        code: [
          { required: true, message: "短信验证码不能为空", trigger: "blur" },
          {
            pattern: /^\d{6}$/,
            message: "请输入正确的手机短信验证码",
            trigger: "blur",
          },
        ],
      },
      };
    },
    computed: {
      sendButtonText() {
        if (this.timer === 0) {
          return "发送验证码";
        } else {
          return `${this.timer}秒后重发`;
        }
      },
    },
    watch: {
      $route: {
        handler: function (route) {
          this.redirect = route.query && route.query.redirect;
        },
        immediate: true,
      },
      timer(num) {
        if (num > 0) {
          this.sendDisabled = true;
          setTimeout(() => {
            this.timer = --num;
          }, 1000);
        } else {
          this.sendDisabled = false;
        }
      },
    },
    created() {
      const lastSendTime = Cookie.get("last-send-time");
      if (lastSendTime) {
        const timer = 60 - moment().diff(moment(lastSendTime), "seconds");
        this.timer = timer > 0 ? timer : 0;
      }
      this.getClientConfigKey("website.homepage").then((response) => {
        this.portalUrl = response.msg;
      });
      this.getClientConfigKey("website.domain").then((response) => {
        if(response.msg && response.msg != '') {
          store.commit('SET_WEBSITE_DOMAIN', response.msg);
        }
      });
      this.getCookie();
    },

    methods: {
      getCode() {
        // getCodeImg().then(res => {
        //   this.codeUrl = "data:image/gif;base64," + res.img;
        //   this.loginForm.uuid = res.uuid;
        // });
      },
      getCookie() {
        const username = Cookie.get("username");
        const password = Cookie.get("password");
        const rememberMe = Cookie.get('rememberMe')
        this.loginForm = {
          username: username === undefined ? this.loginForm.username : username,
          password: password === undefined ? this.loginForm.password : decrypt(password),
          rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
        };
      },
      onSendSms() {
        this.loginWay = false;
        this.$refs.loginForm.validateField("mobile", (err) => {
          if (!this.sending && !err) {
            this.sending = true;
            getCodeUserLogin(this.loginForm.mobile)
              .then(res => {
                this.loginForm.uuid = res.uuid;
                this.$message.success("短信发送成功，请注意查收");
                Cookie.set("last-send-time", new Date());
                this.timer = 60;
              })
              .catch((e) => {
                // this.$message.error("网络异常");
                console.log(e);
              })
              .finally(() => (this.sending = false));
          }
        });
      },
      showPwd() {
        this.loginWay = true;
        if (this.passwordType === "password") {
          this.passwordType = "";
        } else {
          this.passwordType = "password";
        }
        this.$nextTick(() => {
          this.$refs.password.focus();
        });
      },
      handleLogin() {
        if (this.cur) {
          this.handleNameLogin();
        } else {
          this.handlePhoneLogin();
        }
      },
      handleNameLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            // console.log('this.loginForm',this.loginForm)
            this.loading = true;
            if (this.loginForm.rememberMe) {
              Cookie.set("username", this.loginForm.username, {expires: 30});
              Cookie.set("password", encrypt(this.loginForm.password), {expires: 30});
              Cookie.set('rememberMe', this.loginForm.rememberMe, {expires: 30});
            } else {
              Cookie.remove("username");
              Cookie.remove("password");
              Cookie.remove('rememberMe');
            }
            this.$store.dispatch("NameLogin", this.loginForm).then(() => {
              // console.log('登录成功',)
              this.$router.push({path: this.redirect || "/"}).catch(() => {});
            }).catch(() => {
              
              this.loading = false;
              this.getCode();
            });
          }
        });
      },
      handlePhoneLogin() {
        this.$refs.loginForm.validate(valid => {
          if (valid) {
            this.loading = true;
            if (this.loginForm.rememberMe) {
              Cookie.set("username", this.loginForm.username, {expires: 30});
              Cookie.set("password", encrypt(this.loginForm.password), {expires: 30});
              Cookie.set('rememberMe', this.loginForm.rememberMe, {expires: 30});
            } else {
              Cookie.remove("username");
              Cookie.remove("password");
              Cookie.remove('rememberMe');
            }
            this.$store.dispatch("PhoneLogin", this.loginForm).then(() => {
              this.$router.push({path: this.redirect || "/"}).catch(() => {
              });
            }).catch(() => {
              this.loading = false;
              this.getCode();
            });
          }
        });
      }
    },
  };
</script>

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

  $bg: #fff;
  $light_gray: #021826;
  $cursor: #021826;

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

  /* reset element-ui css */
  .login-container {
    .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: $light_gray;
        height: 47px;
        caret-color: $cursor;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !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;
    }
  }
</style>

<style lang="scss" scoped>
  $bg: #fff;
  $dark_gray: #021826;
  $light_gray: #444444;

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

    .login-form {
      position: relative;
      width: 520px;
      max-width: 100%;
      padding: 10px 35px 0;
      margin: 0 auto;
      overflow: hidden;
    }

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

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

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

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

    .thirdparty-button {
      position: absolute;
      right: 0;
      bottom: 6px;
    }

    @media only screen and (max-width: 470px) {
      .thirdparty-button {
        display: none;
      }
    }
  }
</style>

<style lang="scss" scoped>
  a {
    color: #444;
    margin: 50px;
  }

  .login_header {
    margin-bottom: 30px;
    text-align: center;
  }

  .login_header span {
    margin-right: 20px;
    cursor: pointer;
  }

  .Cbody_item {
    border: 0px solid #999;
    overflow: hidden;
  }

  .active {
    color: #444;
    padding-bottom: 10px;
    border-bottom: 4px solid #0969bd;
    font-weight: bold;
  }
  #login .login-menu .curr {
    font-weight: bold;
    position: relative;
  }
  #login .login-menu .curr:after {
    content: " ";
    width: 210px;
    height: 3px;
    background: #0969bd;
    position: absolute;
    bottom: -13px;
    left: 50%;
    transform: translateX(-50%);
  }
</style>

<style type="text/css">
  #header {
    position: relative;
    padding: 0;
    height: 84px;
    transition: all 0.5s;
    z-index: 997;
    background: #fff;
    box-shadow: 0px 6px 9px 0px rgba(0, 0, 0, 0.06);
  }

  #header #logo h1 {
    position: absolute;
    font-size: 28px;
    margin: 6px 0 0 0;
    padding: 0;
    line-height: 1;
    font-weight: 700;
    top: -20px;
  }

  #header #logo h1 a {
    line-height: 1;
    display: inline-block;
    color: #a4a2a3;
  }
</style>



