<template>
  <div class="login-container">
    <div class="login-form-main">
      <el-form
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        autocomplete="on"
        label-position="left"
      >
        <div class="title-container">
          <h3 class="title">
            阳光会务
            <div style="font-size: 20px; margin-top: 5px">{{ ver }}</div>
          </h3>
        </div>

        <el-form-item prop="username">
          <span class="svg-container">
            <i class="el-icon-user" />
          </span>
          <el-input
            ref="username"
            v-model="loginForm.username"
            placeholder="手机号"
            name="username"
            type="text"
            tabindex="1"
            maxlength="11"
            autocomplete="on"
          />
        </el-form-item>

        <el-tooltip
          v-model="capsTooltip"
          content="Caps lock is On"
          placement="right"
          manual
        >
          <el-form-item prop="password">
            <span class="svg-container">
              <i class="el-icon-unlock" />
            </span>
            <el-input
              :key="passwordType"
              ref="password"
              v-model="loginForm.password"
              :type="passwordType"
              placeholder="密码"
              name="password"
              tabindex="2"
              autocomplete="on"
              maxlength="16"
              @keyup.native="checkCapslock"
              @blur="capsTooltip = false"
              @keyup.enter.native="handleLogin"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
            </span>
          </el-form-item>
        </el-tooltip>

        <el-form-item prop="code">
          <div style="display: flex">
            <span class="svg-container" style="margin-left: 10px">
              <i class="el-icon-key" />
            </span>
            <el-input
              v-model="loginForm.code"
              placeholder="验证码"
              style="line-height: 54px"
            />

            <div @click="refreshCode">
              <Identify
                content-height="52"
                :identify-code="identifyCode"
                style="cursor: pointer"
              />
            </div>
          </div>
        </el-form-item>

        <el-button
          :loading="loading"
          :disabled="loading"
          type="primary"
          style="width: 100%; margin-top: 5px"
          @click.native.prevent="handleLogin()"
          >登&nbsp;&nbsp;录</el-button
        >

        <div style="position: relative; padding: 12px 0 0 0">
          <!-- <div class="tips" style="float: left">
            <el-popover
              placement="top"
              title="初始密码："
              width="200"
              trigger="click"
              content="dingding123"
            >
              <i slot="reference" class="el-icon-info" />
            </el-popover>
          </div> -->
          <router-link to="/forget-password">
            <div class="tips" style="float: right">
              <span>忘记密码</span>
            </div>
          </router-link>
        </div>
      </el-form>
    </div>

    <div v-if="loginBeian !== ''" class="beian">
      <div v-if="loginBeian !== ''" class="beian">
        <span>{{ loginTitle }}</span>
        <a target="_blank" :href="loginBeianUrl">{{ loginBeian }}</a>
        <span />
      </div>
    </div>
  </div>
</template>

<script>
import { isnumber, isAlphanumeric, validAlphabets, isMobile } from "@/utils/validate";
import asyncRequest from "@/apis/service/user";
import Identify from "@/components/identify";
import urlConfig from "@/apis/url-config";
import resToken from "@/mixins/resToken";

export default {
  name: "Login",
  components: { Identify },
  mixins: [resToken],
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("用户名不能为空！"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("密码不能为空！"));
      } else {
        if (!isAlphanumeric(value)) {
          callback(new Error("密码为6-18位数字字母组合！"));
        } else if (value.length < 6 || value.length > 18) {
          callback(new Error("密码为6-18位数字字母组合！"));
        } else if (isnumber(value)) {
          callback(new Error("密码不能为纯数字！"));
        } else if (validAlphabets(value)) {
          callback(new Error("密码不能为纯字母！"));
        } else {
          callback();
        }
      }
    };

    const validateCode = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("验证码不能为空!"));
      } else {
        if (value !== this.identifyCode) {
          callback(new Error("请输入正确的验证码"));
        } else {
          callback();
        }
      }
    };

    return {
      ver: "",
      show: false,
      loginTitle: urlConfig.loginTitle,
      loginBeian: urlConfig.loginBeian,
      loginBeianUrl: urlConfig.loginBeianUrl,
      loginForm: {
        username: "admin",
        password: "admin123",
        code: "",
      },
      loginRules: {
        username: [{ required: true, trigger: "blur", validator: validateUsername }],
        password: [{ required: true, trigger: "blur", validator: validatePassword }],
        code: [{ required: true, trigger: "blur", validator: validateCode }],
      },
      identifyCode: "",
      identifyCodes: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"],
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  mounted() {
    this.refreshCode();
    this.bindEnterEvent();
    // this.getversion();
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
  },
  beforeDestroy() {
    this.removeEnterEvent();
  },
  methods: {
    bindEnterEvent() {
      window.addEventListener("keydown", this.listener);
    },
    removeEnterEvent() {
      window.removeEventListener("keydown", this.listener);
    },
    listener(e) {
      e.keyCode === 13 && this.handleLogin();
    },
    async getversion() {
      const { code, data } = await asyncRequest.version({});
      if (code === 0) {
        const { version } = data;
        this.ver = version;
      } else {
        this.ver = "";
      }
    },
    setVisible(val) {
      this.show = val;
    },
    handleClick() {
      this.show = true;
    },
    handleSuccess() {
      this.show = false;
      this.handleLogin();
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    showPwd() {
      if (this.passwordType === "password") {
        this.passwordType = "";
      } else {
        this.passwordType = "password";
      }
      this.$nextTick(() => {
        this.$refs.password.focus();
      });
    },
    // 生成随机数
    randomNum(min, max) {
      max = max + 1;
      return Math.floor(Math.random() * (max - min) + min);
    },
    // 更新验证码
    refreshCode() {
      this.identifyCode = "";
      this.makeCode(this.identifyCodes, 4);
    },
    makeCode(data, len) {
      for (let i = 0; i < len; i++) {
        this.identifyCode += this.identifyCodes[
          this.randomNum(0, this.identifyCodes.length - 1)
        ];
      }
    },
    async handleLogin() {
      try {
        await this.$refs.loginForm.validate();
        const response = await this.$store.dispatch("user/login", this.loginForm);
        const { code } = response;
        if (Number(code) === 1) this.getMenu();
        this.loading = false;
      } catch (e) {
        console.log(e);
        this.loading = false;
      }
    },
    getMenu() {
      this.$store
        .dispatch("user/getMenuList", this)
        .then((res) => {
          window.vm.$router.push({
            path: "/welcome/dashboard/",
            query: this.otherQuery,
          });
          this.loading = false;
        })
        .catch((err) => {
          this.loading = false;
        });
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
  },
};
</script>

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

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

@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: #232323;
      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 #e9e9e9;
    // background: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #232323;
  }
}
</style>

<style lang="scss" scoped>
$bg: #2d3a4b;
$dark_gray: #38c1e7;
$light_gray: #f2f2f2;

.login-container {
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  line-height: 1;
  text-align: center;
  background: #ecf5ff;;
  position: relative;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  // background-image: url("~@/assets/design/bg-pc.jpg");
  zoom: 1;
  background-repeat: no-repeat;
  background-size: 100% 100%;
  // background-position: center 0;
  text-align: center;
  .login-form-main {
    height: 500px;
    width: 450px;
    display: inline-block;
    margin:  0 auto;
    box-shadow: 0 0 6px #fdf6ec;
    margin-top: calc(50vh - 300px);
    background: #fdf6ec;
    border:1px solid #faecd8;
    border-radius: 20px;
    overflow: hidden;
  
    // position: absolute;
    // right: 200px;
    // top: 50%;
    // transform: translateY(-50%);
    // transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);

    img {
      width: 400px;
      height: 350px;
    }

    .main-title {
      // position: absolute;
      // top: 0;
      // left: 0;
      // z-index: 2;
      // left: 170px;
      // top: 125px;
      text-align: left;
      color: #fff;
      h1 {
        padding: 0 0 13px 0;
      }
      h3 {
        font-size: 22px;
      }
    }

    .login-form {
      width: 400px;
      top: -40px;
      right: 100px;
      // z-index: 3;
      max-width: 100%;
      padding: 65px 28px 35px 28px;
      margin: 0 auto;
      overflow: hidden;
      border-radius: 20px;

      .el-form-item {
        border: 1px solid transparent;
        border-bottom: 1px solid #e1e1e1;
        border-radius: 0px;
      }

      .el-button--primary {
        background:linear-gradient(rgb(250, 170, 110), rgb(249, 138, 54));;
        border:0px solid #087af5;
        color: #fff;
        height: 46px;
        font-size: 16px;
        margin: 5px 0 0 0;
        text-align: center;
        border-radius: 15px;
      }
    }
  }
  // min-height: 100%;
  // width: 100%;
  // background-color: $bg;
  // overflow: hidden;
  .beian {
    position: absolute;
    width: 100%;
    bottom: 30px;
    color: #343434;
    font-size: 12px;
    left: 50%;
    transform: translateX(-50%);
    span {
      padding: 0 10px;
    }
    a {
      display: inline-block;
      color: #343434;
      vertical-align: top;
      font-size: 12px;
      &:hover {
        text-decoration: underline;
        text-decoration-color: #343434;
      }
    }
  }
  .tips {
    font-size: 14px;
    color: #04a2ce;
    margin-bottom: 10px;

    span {
      &:first-of-type {
        margin-right: 8px;
      }
    }
    i {
      font-size: 20px;
      margin: 0 0 0 7px;
    }
  }
  .puzzle-box {
    position: absolute;
    top: 200px;
  }

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

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: #087af5;
      margin: 0px auto 30px auto;
      text-align: center;
      font-weight: bold;
      span {
        display: inline-block;
        font-size: 18px;
        vertical-align: top;
        padding: 10px 0 0 4px;
      }
    }
  }

  .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;
    }
  }
}

.s-canvas {
  margin: 0px;
  height: 38px;
}

.el-icon-key,
.el-icon-user,
.el-icon-unlock {
  color: #087af5 !important;
  font-weight: 700;
}

// @media screen and (max-width: 1800px) {
//   .login-container {
//     .login-form-main {
//       right: 100px;
//     }
//   }
// }

// @media screen and (max-width: 1200px) {
//   .login-container {
//     .login-form-main {
//       right: 50px;
//     }
//   }
// }

// @media screen and (max-width: 1024px) {
//   .login-container {
//     background-image: url("~@/assets/design/bg-pad.jpg");
//     .login-form-main {
//       right: 50px;
//       width: 300px;
//     }
//   }
// }

// @media screen and (max-width: 992px) {
//   .login-container {
//     background-image: url("~@/assets/design/bg-pad.jpg");
//     .login-form-main {
//       right: 20px;
//       width: 360px;
//     }
//   }
// }

// @media screen and (max-width: 840px) {
//   .login-container {
//     background-image: url("~@/assets/design/bg-pad.jpg");
//     .login-form-main {
//       right: 5px;
//     }
//   }
// }

// @media screen and (max-width: 768px) {
//   .login-container {
//     background-image: url("~@/assets/design/bg-phone.jpg");
//     .login-form-main {
//       right: 20px;
//       width: 95%;
//       background: #fff;
//       left: 50%;
//       transform: translate(-50%, -50%);
//       border-radius: 20px;
//       height: auto;
//     }
//   }

//   .beian {
//     position: fixed;
//     left: 50%;
//     transform: translateX(-50%);
//     padding: 0px !important;

//     a {
//       color: #fff !important;
//     }
//   }
// }
</style>
