<template>
  <div
    class="login-container"
    style="display: flex;
    align-items: center;flex-direction: column;
    justify-content: center;"
  >
    <div class="systemTitle">
      <i class="login_titleLine_left" />壤塘家园定点服务系统
      <i
        class="login_titleLine_left"
        style="transform: rotate(180deg);margin-left:29px"
      />
    </div>
    <div
      style="background: white;
    width: 1053px;
    border-radius:16px;
    margin: 0 auto;"
    >
      <el-row>
        <el-col :span="12"
          ><img
            src="./img/loginImg.png"
            style="padding: 70px 0px 70px 72px;width:100%"
            alt=""
        /></el-col>

        <el-col :span="12">
          <el-form
            ref="loginForm"
            :model="loginForm"
            :rules="loginRules"
            class="login-form"
            autocomplete="on"
            label-position="left"
          >
            <div class="title-container">
              <h3 class="title">管理员登录</h3>
            </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"
                autocomplete="on"
              />
            </el-form-item>

            <el-form-item prop="username">
              <span class="svg-container">
                <svg-icon icon-class="lock" />
              </span>
              <el-input
                ref="password"
                v-model="loginForm.captcha"
                placeholder="请输入密码"
                name="captcha"
                type="password"
                tabindex="2"
                autocomplete="on"
              />
            </el-form-item>

            <!-- <el-form-item prop="captcha">
              <span class="svg-container">
                <svg-icon icon-class="email" />
              </span>
              <el-input
                ref="password"
                v-model="loginForm.captcha"
                placeholder="请输入验证码"
                name="captcha"
                tabindex="2"
                @keyup.enter.native="handleLogin"
              />
              style="width:290px"
              <el-button @click="handleSms">获取验证码</el-button>
              <button
                class="btn_getCode"
                type="button"
                :disabled="getCodeDisabled"
                @click="handleSms"
              >
                {{ codeText }}
              </button>
            </el-form-item> -->

            <el-button
              :loading="loading"
              type="primary"
              style="width:100%;margin-bottom:30px;border-radius:10px;height:54px"
              @click.native.prevent="handleLogin"
              >登录</el-button
            >
          </el-form>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import { getGuestToken, getSms } from "@/api/user";
import Axios from "axios";

export default {
  name: "Login",
  // components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      // if (!validUsername(value)) {
      //   callback(new Error('账号格式错误，不能为空或小于4位'))
      // } else {
      //   callback()
      // }
      if (value.length < 4) {
        callback(new Error("账号格式错误，不能为空或小于11位"));
      } else {
        callback();
      }
    };
    const validateCaptcha = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("验证码格式错误，不能为空或小于6位"));
      } else {
        callback();
      }
    };
    return {
      // loginForm: {
      //   username: 'admin',
      //   password: '111111'
      // },
      loginForm: {
         username: process.env.NODE_ENV==='development'?"18882564006":'', //18882564006
        captcha: process.env.NODE_ENV==='development'?"111111":'',
        // username: "18882564006", //18882564006
        // captcha: "111111",
        appVersion: "1.0.0",
        system: "PC",
        device: navigator.userAgent,
        extra: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername }
        ],
        captcha: [
          { required: true, trigger: "blur", validator: validateCaptcha }
        ]
      },
      passwordType: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      codeText: "获取验证码",
      time: 60,
      getCodeDisabled: false
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true
    }
  },
  created() {
    // console.log(process.env.NODE_ENV);
    // window.addEventListener('storage', this.afterQRScan)
    const { appVersion, system, device, extra } = this.loginForm;
    const payload = {
      appVersion,
      system,
      device,
      extra
    };
    Axios({
      method: "POST",
      url: `${process.env.VUE_APP_BASE_API}api/auth/guest`,
      data: payload,
      headers: {
        Authorization: "basic YW5kcm9pZC1jbGllbnQ6YW5kcm9pZC1zZWNyZXQtMjAyMA=="
      }
    }).then(res => {
      // console.log(res);
      sessionStorage.setItem("token", res.data.d.access_token);
    });
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.captcha === "") {
      this.$refs.password.focus();
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    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()
    //   })
    // },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          Axios({
            method: "POST",
            url: `${process.env.VUE_APP_BASE_API}api/auth/sms`,
            data: this.loginForm,
            headers: {
              Authorization:
                "basic YW5kcm9pZC1jbGllbnQ6YW5kcm9pZC1zZWNyZXQtMjAyMA=="
            }
          }).then(res => {
            // console.log(res);
            if (res.data.c === 200) {
              this.$store.dispatch("user/setToken", res.data.d.access_token);
              this.$router.push({
                path: this.redirect || "/",
                query: this.otherQuery
              });
              // if (res.data.c === 200) {
              //   this.$notify({
              //     title: "成功",
              //     message: "登录成功",
              //     type: "success",
              //     duration: 2000
              //   });
              // }
            } else {
              this.$notify.error(res.data.m);
            }
          });
        } else {
          console.log("error submit!!");

          return false;
        }
      });
      // this.$refs.loginForm.validate(valid => {
      //   if (valid) {
      //     this.loading = true
      //     this.$store.dispatch('user/login', this.loginForm)
      //       .then(() => {
      //         this.$router.push({ path: this.redirect || '/', query: this.otherQuery })
      //         this.loading = false
      //       })
      //       .catch(() => {
      //         this.loading = false
      //       })
      //   } else {
      //     console.log('error submit!!')
      //     return false
      //   }
      // })
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    handleSms() {
      this.getCodeDisabled = false;
      const payload = {
        phone: this.loginForm.username,
        category: "SIGNIN"
      };
      Axios({
        method: "GET",
        url: `${process.env.VUE_APP_BASE_API}api/common/sms/send`,
        params: payload,
        headers: {
          Authorization: "Bearer " + sessionStorage.getItem("token")
        }
      }).then(res => {
        if (res.data.c === 200) {
          this.getCodeDisabled = true;
          this.timer();
          this.$notify({
            title: "成功",
            message: "获取验证码成功",
            type: "success",
            duration: 2000
          });
        }
      });
    },
    timer() {
      this.codeText = `${this.time}s 后重新获取`;
      var interval = setInterval(() => {
        this.time--;
        this.codeText = `${this.time}s 后重新获取`;
        if (this.time === 0) {
          this.time = 60;
          this.codeText = "获取验证码";
          this.getCodeDisabled = false;
          clearInterval(interval);
        }
      }, 1000);
    }
  }
};
</script>

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

$bg: #fff;
$light_gray: #000000;
$cursor: #000;

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

/* 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: #000;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }
  // .el-form{
  //   width: 340px;
  // }

  .el-form-item {
    border: 1px solid #d6d6d6;
    // background: rgba(0, 0, 0, 0.1);
    border-radius: 10px;
    color: #454545;
  }
}
</style>

<style lang="scss" scoped>
$bg: #059cda;
$dark_gray: #889aa4;
$light_gray: #1890ff;

.login-container {
  min-height: 100%;
  width: 100%;
  // background-color: $bg;
  background: url("./img/bg.png") no-repeat;
  background-size: cover;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 340px;
    max-width: 100%;
    // padding: 160px 35px 0;
    padding: 115px 0px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .tips {
    font-size: 14px;
    color: #fff;
    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;
    }
  }
  .btn_getCode {
    border: 0;
    background: none;
    color: #ff4200;
    position: absolute;
    right: 10px;
    top: 6px;
    padding: 10px;
    cursor: pointer;
  }
  .login_titleLine_left {
    background: url("./img/login_titleLine_left.png") no-repeat;
    background-size: cover;
    display: inline-block;
    width: 315px;
    height: 1px;
    margin-right: 29px;
    vertical-align: middle;
  }
  .systemTitle {
    font-size: 37px;
    color: rgb(255, 255, 255);
    margin-bottom: 63px;
    min-width: 1098px;
    margin: 63px auto;
  }
}
</style>
