<template>
  <div class="login-container">
    <div class="form-content">
      <div class="title-container">
        <img src="../../assets/images/login-head.png" class="images" />
      </div>
      <el-form
        v-if="loginOrRetrieve == 'login'"
        ref="loginForm"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        autocomplete="on"
        label-position="left"
      >
        <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-tooltip
          v-model="capsTooltip"
          content="Caps lock is On"
          placement="right"
          manual
        >
          <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"
              autocomplete="on"
              @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-button
          :loading="loading"
          type="primary"
          style="width: 100%; margin-bottom: 30px"
          @click="handleLogin"
          >立即登录</el-button
        >
        <div class="tips">
          <div @click="Retrieve('retrieve')" style="cursor: pointer">
            找回密码
          </div>
        </div>
      </el-form>
      <div v-if="loginOrRetrieve == 'retrieve'">
        <el-form
          ref="RetrieveForm"
          :model="RetrieveForm"
          :rules="RetrieveRules"
          class="login-form"
          autocomplete="on"
          label-position="left"
        >
          <el-form-item prop="phone">
            <el-input
              ref="phone"
              v-model="RetrieveForm.phone"
              placeholder="请输入手机号"
              name="phone"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </el-form-item>
          <el-tooltip
            v-model="capsTooltip"
            content="Caps lock is On"
            placement="right"
            manual
          >
            <el-form-item prop="verification_code">
              <el-input
                ref="verification_code"
                v-model="RetrieveForm.verification_code"
                type="text"
                placeholder="请输入验证码"
                name="text"
                tabindex="2"
                autocomplete="on"
              />
              <span class="show-pwd">
                <el-button :disabled="isDisabled" @click="getCode">
                  {{ buttonText }}
                </el-button>
              </span>
            </el-form-item>
          </el-tooltip>

          <el-tooltip
            v-model="capsTooltip"
            content="Caps lock is On"
            placement="right"
            manual
          >
            <el-form-item prop="new_password1">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="RetrieveForm.new_password1"
                :type="passwordType"
                placeholder="请输入新密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon
                  :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"
                />
              </span>
            </el-form-item>
          </el-tooltip>
          <el-tooltip
            v-model="capsTooltip"
            content="Caps lock is On"
            placement="right"
            manual
          >
            <el-form-item prop="new_password2">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                :key="passwordType"
                ref="passwords"
                v-model="RetrieveForm.new_password2"
                :type="passwordTypes"
                placeholder="确认新密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltips = false"
              />
              <span class="show-pwd" @click="showPwds">
                <svg-icon
                  :icon-class="
                    passwordTypes === 'password' ? 'eye' : 'eye-open'
                  "
                />
              </span>
            </el-form-item>
          </el-tooltip>

          <el-button
            :loading="loading"
            type="primary"
            style="width: 100%; margin-bottom: 30px"
            @click="retPass"
            >重置密码</el-button
          >
          <div class="tips">
            <div @click="Retrieve('login')" style="cursor: pointer">返回登录</div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import { validUsername } from "@/utils/validate";
import { tailPhone, codeCheckout, updatePassword, login } from "@/api/user";
import SocialSign from "./components/SocialSignin";

export default {
  name: "Login",
  components: { SocialSign },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value.length < 3) {
        callback(new Error("请填写正确的登录用户名"));
      } else {
        callback();
      }
    };
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("请填写正确的密码,密码不得小于6位"));
      } else {
        callback();
      }
    };
    const validatePhone = (rule, value, callback) => {
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (value === "") {
        callback(new Error("请输入手机号码"));
      } else if (!phoneRegex.test(value)) {
        callback(new Error("请输入正确的手机号码"));
      } else {
        callback();
      }
    };

    const validateNewPassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error("新密码不能少于6个字符"));
      } else {
        if (this.RetrieveForm.new_password2 !== "") {
          this.$refs.RetrieveForm.validateField("new_password2");
        }
        callback();
      }
    };

    const validateConfirmPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.RetrieveForm.new_password1) {
        callback(new Error("两次输入的密码不一致"));
      } else {
        callback();
      }
    };
    return {
      loginForm: {
        username: "",
        password: "",
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", validator: validateUsername },
        ],
        password: [
          { required: true, trigger: "blur", validator: validatePassword },
        ],
      },
      passwordType: "password",
      passwordTypes: "password",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      redirect: undefined,
      otherQuery: {},
      loginOrRetrieve: "login",
      RetrieveForm: {
        phone: "",
        verification_code: "",
        new_password1: "",
        new_password2: "",
      },
      RetrieveRules: {
        phone: [{ required: true, trigger: "blur", validator: validatePhone }],
        verification_code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
        ],
        new_password1: [
          { required: true, trigger: "blur", validator: validateNewPassword },
        ],
        new_password2: [
          {
            required: true,
            trigger: "blur",
            validator: validateConfirmPassword,
          },
        ],
      },
      countdown: 60,
      isDisabled: false,
      buttonText: "获取验证码",
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    // window.addEventListener('storage', this.afterQRScan)
  },
  mounted() {
    if (this.loginForm.username === "") {
      this.$refs.username.focus();
    } else if (this.loginForm.password === "") {
      this.$refs.password.focus();
    }
  },
  destroyed() {
    // window.removeEventListener('storage', this.afterQRScan)
  },
  methods: {
    /* 找回密码 */
    retPass() {
      this.$refs.RetrieveForm.validate((valid) => {
        if (valid) {
          codeCheckout({
            phone: this.RetrieveForm.phone,
            verification_code: this.RetrieveForm.verification_code,
          })
            .then((response) => {
              if (response.status !== 200) return;
              updatePassword(this.RetrieveForm).then((res) => {
                this.loginOrRetrieve = "login";
                this.$message.success("密码已成功重置");
              });
            })
            .catch((error) => {
              this.$message.error("验证码校验失败");
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    /* 获取验证码 */
    getCode() {
      this.$refs.RetrieveForm.validateField("phone", (errorMessage) => {
        if (errorMessage) {
          this.$message.warning(errorMessage);
        } else {
          this.isDisabled = true;
          this.buttonText = `${this.countdown}s`;
          const timer = setInterval(() => {
            if (this.countdown > 0) {
              this.countdown--;
              this.buttonText = `${this.countdown}s`;
            } else {
              clearInterval(timer);
              this.isDisabled = false;
              this.buttonText = "获取验证码";
              this.countdown = 60;
            }
          }, 1000);

          tailPhone({ phone: this.RetrieveForm.phone }).then((res) => {
            console.log(res);
          });
        }
      });
    },
    showPwds() {
      if (this.passwordTypes === "password") {
        this.passwordTypes = "";
      } else {
        this.passwordTypes = "password";
      }
      this.$nextTick(() => {
        this.$refs.passwords.focus();
      });
    },
    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) {
          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;
      }, {});
    },
    // afterQRScan() {
    //   if (e.key === 'x-admin-oauth-code') {
    //     const code = getQueryObject(e.newValue)
    //     const codeMap = {
    //       wechat: 'code',
    //       tencent: 'code'
    //     }
    //     const type = codeMap[this.auth_type]
    //     const codeName = code[type]
    //     if (codeName) {
    //       this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
    //         this.$router.push({ path: this.redirect || '/' })
    //       })
    //     } else {
    //       alert('第三方登录失败')
    //     }
    //   }
    // }
    /* 找回密码 */
    Retrieve(val) {
      this.loginOrRetrieve = val;
    },
  },
};
</script>

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