<template>
  <div>
    <span class="sign-box-type" @click="$emit('change-email')">邮箱登录 ></span>
    <h1>手机登录</h1>
    <div class="tip">
      您还可以进行
      <span @click="changeLogin">{{loginMethod}}</span>&nbsp;登录
    </div>
    <div>
      <el-input
        placeholder="请输入手机号"
        class="input-box"
        v-model.trim="phone"
        maxlength="11"
        @input="phone=phone.replace(/[^\d]/g,'')"
      />
      <!-- code输入框 -->
      <div class="el-input input-box input-box__code" v-if="loginType===1">
        <input
          type="text"
          maxlength="9"
          autocomplete="off"
          v-model.trim="code"
          @input="code=code.replace(/[^\d]/g,'')"
          class="el-input__inner"
          placeholder="请输入短信验证码"
        />
        <div
          class="btn"
          @click="getCode"
        >{{curIntervalSeconds === 0 ? '发送验证码' : curIntervalSeconds + '秒后重新发送'}}</div>
      </div>
      <!-- 密码输入框 -->
      <div class="el-input input-box input-password" v-if="loginType===0">
        <input
          :type="[openOrClose?'password':'text']"
          maxlength="30"
          autocomplete="off"
          v-model.trim="password"
          @input="password=password.replace(/[\u4e00-\u9fa5]/ig,'')"
          class="el-input__inner"
          placeholder="请输入密码"
        />
        <div class="icon" @click="changeOpen">
          <i class="iconfont" :class="[openOrClose?'iconYJ':'iconYC']"></i>
        </div>
      </div>
      <!-- 底部登录按钮 -->
      <div class="sign-in-btn" @click="loginStart">登录</div>
      <!-- 记住密码or设置密码等 -->
      <div class="operation-box" v-if="loginType===0">
        <div class="left-link-zone">
          <el-checkbox v-model="isAutoLogin">记住密码</el-checkbox>
        </div>
        <div class="right-link-zone">
          <a href="javascript:void(0)" class="set-up" @click="SetPassword(0)">设置密码</a>
          <a href="javascript:void(0)" @click="SetPassword(1)">忘记密码</a>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import * as storage from "@/plugins/storage";
import { GO_URLS } from "@/config/URLS";
let CryptoJS = require("crypto-js");
export default {
  data() {
    return {
      phone: "",
      code: "",
      maxIntervalSeconds: 60,
      curIntervalSeconds: 0,
      isAutoLogin: false,
      loginMethod: "手机验证码",
      loginType: 0,
      openOrClose: true,
      password: "",
      isclick: true,
    };
  },
  watch: {
    // 电话号码的变化
    phone: function (val) {
      if (val.length === 11) {
        if (!this.checkPhone()) return;
        this.checkisSetPwd();
      }
    },
  },
  created() {
    if (
      typeof localStorage.ciphertext === "string" &&
      localStorage.ciphertext.length === 0
    ) {
      //本地存在ciphertext，但是没有值，需要清除缓存
      localStorage.removeItem("ciphertext");
      this.isAutoLogin = false;
    } else if (
      typeof localStorage.ciphertext === "string" &&
      localStorage.ciphertext.length > 0
    ) {
      //"属性和值同时存在"
      let ciphertext = localStorage.ciphertext;
      let bytes = CryptoJS.AES.decrypt(ciphertext.toString(), "secret key 123");
      let json = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
      if (json.login_type === 0) {
        this.phone = json.phone;
        this.password = json.pwd;
        this.isAutoLogin = true;
      }
    }
  },
  methods: {
    // 检查是否设置过密码
    async checkisSetPwd() {
      const res = await this.$ajax({
        url: GO_URLS.isSetPwd,
        type: "post",
        params: {
          phone: this.phone,
        },
      });
      if (res) {
        if (res.data && res.data.is_set_pwd === 0) {
          this.loginType = 1;
        } else {
          this.loginType = 0;
        }
        // 0 未设置密码， 1有密码
      }
    },
    // 电话检测
    checkPhone() {
      if (!/^1[3456789]\d{9}$/.test(this.phone)) {
        this.$message.error("手机号码有误，请重填");
        return false;
      } else {
        return true;
      }
    },
    // 获取验证码
    async getCode() {
      if (!this.checkPhone()) return;
      if (this.curIntervalSeconds > 0) return;
      const res = await this.$ajax({
        type: "post",
        url: GO_URLS.sendSms,
        params: {
          phone: this.phone,
          template_id: 0,
        },
      });

      if (res) {
        this.$message({
          message: "短信已发送",
          type: "success",
        });
        this.curIntervalSeconds = this.maxIntervalSeconds;
        this.intervalHandle = setInterval(() => {
          if (this.curIntervalSeconds > 0) {
            this.curIntervalSeconds--;
          } else {
            clearInterval(this.intervalHandle);
          }
        }, 1000);
      }
    },
    // 设置密码
    SetPassword(type) {
      this.$store.commit("updateBusinessType", type);
      this.$emit("SetPassword");
    },
    // 电话+验证码登录
    async loginStart() {
      if (this.isclick) {
        this.isclick = false;
        //下面添加需要执行的事件
        if (!this.checkPhone()) {
          this.isclick = true;
          return;
        }
        if (this.loginType === 1 && this.code.length < 1) {
          this.$message.error("请输入短信验证码");
          this.isclick = true;
          return;
        }
        if (this.loginType === 0 && this.password === "") {
          this.$message.error("请输入密码");
          this.isclick = true;
          return;
        }
        var params = {};
        if (this.loginType === 1) {
          params = {
            login_type: 1,
            phone: this.phone,
            code: this.code,
          };
        } else {
          params = {
            login_type: 0,
            phone: this.phone,
            pwd: this.$md5(
              String(this.password) + this.$md5(String(this.password.length))
            ),
          };
        }
        const res = await this.$ajax({
          type: "post",
          url: GO_URLS.login,
          params: params,
        });
        this.isclick = true;
        if (res && res.data) {
          sessionStorage.setItem("login_type", 1);
          storage.setLogin(
            res.data,
            {
              login_type: 0,
              phone: this.phone,
              pwd: this.password,
            },
            this.isAutoLogin
          );
          this.$router.push({ path: "/categoryManage" });
        }
      }
    },
    // 是否显示密码
    changeOpen() {
      this.openOrClose = !this.openOrClose;
    },
    // 改变登录方式
    changeLogin() {
      // login_type   0：手机号+密码 1:手机号+验证码 2:邮箱+密码 3：邮箱验+证码
      if (this.loginType === 0) {
        this.loginType = 1;
        this.loginMethod = "账号密码";
      } else if (this.loginType === 1) {
        this.loginType = 0;
        this.loginMethod = "手机验证码";
      }
    },
  },
};
</script>
<style lang="less" scoped>
.sign-in-btn {
  width: 441px;
  height: 44px;
  background: rgba(63, 121, 254, 1);
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  line-height: 44px;
  color: white;
  text-align: center;
  &:hover {
    box-shadow: 0px 2px 6px 0px #4a90e2;
  }
}
.operation-box {
  margin-top: 40px;
  .left-link-zone {
    float: left;
    text-decoration: none;
  }
  .right-link-zone {
    float: right;
    a {
      font-size: 14px;
      color: rgba(121, 125, 132, 1);
      text-decoration: none;
    }
    .set-up {
      border-right: 1px solid #797d84;
      padding-right: 8px;
      margin-right: 8px;
    }
  }
}
.input-box__code {
  position: relative;
  .btn {
    width: 104px;
    position: absolute;
    right: 10px;
    top: 10px;
    text-align: center;
    color: #989fa5;
    line-height: 25px;
    font-size: 12px;
    cursor: pointer;
    height: 25px;
    background: rgba(244, 244, 244, 1);
    border-radius: 3px;
  }
}
.input-password {
  position: relative;
  .icon {
    cursor: pointer;
    position: absolute;
    right: 10px;
    top: 0;
    width: 18px;
    line-height: 2.8;
    height: 100%;
  }
}
.input-box {
  margin-bottom: 16px;
  /deep/ .el-input__inner {
    height: 44px !important;
    &::-webkit-input-placeholder {
      /* WebKit browsers */
      color: #797d84;
    }
    &:-moz-placeholder {
      color: #797d84;
    }
    &::-moz-placeholder {
      /* Mozilla Firefox 19+ */
      color: #797d84;
    }

    &:-ms-input-placeholder {
      /* Internet Explorer 10+ */
      color: #797d84;
    }
  }
}
.tip {
  height: 20px;
  font-size: 14px;
  font-weight: 400;
  color: rgba(121, 125, 132, 1);
  line-height: 20px;
  margin-bottom: 24px;
  span {
    color: #3f79fe;
    cursor: pointer;
  }
}
.sign-box-type {
  position: absolute;
  top: 34px;
  right: 32px;
  font-size: 14px;
  color: #5386fb;
  cursor: pointer;
}
h1 {
  font-size: 30px;
  font-weight: 400;
  color: rgba(53, 53, 53, 1);
  line-height: 42px;
  text-align: center;
  margin: 0;
  margin-top: 96px;
  margin-bottom: 36px;
}
</style>