<template>
  <div class="login">
    <div class="login-bg"></div>
    <div v-if="isLogin">
      <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
        <h3 class="title">产发工程数字管理平台</h3>
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            auto-complete="off"
            placeholder="账号"
          >
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            auto-complete="off"
            placeholder="密码"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input
            v-model="loginForm.code"
            auto-complete="off"
            placeholder="验证码"
            style="width: 68%"
            @keyup.enter.native="handleLogin"
          >
            <svg-icon
              slot="prefix"
              icon-class="validCode"
              class="el-input__icon input-icon"
            />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-checkbox v-model="loginForm.rememberMe" style="margin: 0px 0px 25px 0px"
              >记住密码</el-checkbox
            >
          </el-col>
          <el-col :span="12" style="text-align: right; font-size: 14px">
            <el-link type="primary" icon="el-icon-warning" @click="isLogin = false"
              >忘记密码？立即修改</el-link
            >
          </el-col>
        </el-row>
        <el-form-item style="width: 100%">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width: 100%"
            @click.native.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div style="float: right" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="!isLogin">
      <el-form ref="passForm" :model="passForm" :rules="passRules" class="login-form">
        <h3 class="title">产发工程数字管理平台</h3>
        <el-form-item prop="loginName">
          <el-input v-model="passForm.loginName" type="text" placeholder="手机账号">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="pCode">
          <el-input v-model="passForm.pCode" placeholder="验证码" style="width: 68%">
            <svg-icon
              slot="prefix"
              icon-class="validCode"
              class="el-input__icon input-icon"
            />
          </el-input>
          <div class="login-code">
            <el-button
              size="medium"
              type="primary"
              style="width: 100%"
              @click="sendPhoneMsg"
              :disabled="disabled"
            >
              {{ buttonText }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item prop="pw">
          <el-input v-model="passForm.pw" type="password" placeholder="登录密码">
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item prop="cpw">
          <el-input v-model="passForm.cpw" type="password" placeholder="确认密码">
            <svg-icon
              slot="prefix"
              icon-class="password"
              class="el-input__icon input-icon"
            />
          </el-input>
        </el-form-item>
        <el-form-item style="width: 100%">
          <el-button
            :loading="loading"
            size="medium"
            type="primary"
            style="width: 100%"
            @click="codeUpdatePwd"
          >
            <span v-if="!loading">修 改 密 码</span>
            <span v-else>修 改 中...</span>
          </el-button>
        </el-form-item>
        <el-form-item style="width: 100%">
          <el-button
            plain
            :loading="loading"
            size="medium"
            type="info"
            style="width: 100%"
            @click="isLogin = true"
          >
            <span>返 回 登 录</span>
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2023 西咸新区泾河新城产业发展集团 All Rights Reserved.</span>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import { codeUpdatePwd, sendPhoneMessage } from "@/api/system/user";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";

export default {
  name: "Login",
  data() {
    return {
      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: "",
      },
      passForm: {
        loginName: "",
        pw: "",
        cpw: "",
        pCode: "",
        source: "r",
      },
      loginRules: {
        username: [{ required: true, trigger: "change", message: "请输入您的账号" }],
        password: [{ required: true, trigger: "change", message: "请输入您的密码" }],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      passRules: {
        loginName: [{ required: true, trigger: "change", message: "请输入您的账号" }],
        pw: [{ required: true, trigger: "change", message: "请输入您的密码" }],
        cpw: [{ required: true, trigger: "change", message: "请输入确认密码" }],
        pCode: [{ required: true, trigger: "change", message: "请输入验证码" }],
      },
      loading: false,
      // 验证码开关
      captchaEnabled: true,
      // 注册开关
      register: false,
      redirect: undefined,
      isLogin: true,
      timer: null,
      count: 30,
      buttonText: "发送验证码",
      disabled: false,
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    },
  },
  created() {
    this.getCode();
    this.getCookie();
  },
  methods: {
    getCode() {
      getCodeImg().then((res) => {
        this.captchaEnabled =
          res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.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),
      };
      this.passForm.loginName = "";
    },
    handleLogin() {
      this.redirect = this.$route.query.redirect;
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set("rememberMe", this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove("rememberMe");
          }
          this.$store
            .dispatch("Login", this.loginForm)
            .then(() => {
              window.open(this.redirect || "#/index", "_self");
            })
            .catch(() => {
              this.loading = false;
              if (this.captchaEnabled) {
                this.getCode();
              }
            });
        }
      });
    },
    resetCountdown() {
      this.count = 30;
      this.buttonText = "发送验证码";
      this.disabled = false; // 恢复按钮可点击
    },
    startCountdown() {
      this.disabled = true; // 禁用按钮
      this.buttonText = `${this.count}秒后发送`;
      this.timer = setInterval(() => {
        this.count--;
        this.buttonText = `${this.count}秒后发送`;
        if (this.count <= 0) {
          clearInterval(this.timer);
          this.resetCountdown();
        }
      }, 1000);
    },
    //发送验证码
    sendPhoneMsg() {
      if (this.passForm.loginName) {
        sendPhoneMessage({ phoneNumber: this.passForm.loginName }).then((res) => {
          if (res.code == 200 && res.data) {
            this.$modal.msgSuccess(`已发送验证码，请注意查收。5分钟内有效！`);
            this.startCountdown();
          } else {
            this.$modal.msgError(`请稍后再试！`);
          }
        });
      } else {
        this.$modal.msgError(`请输入正确的登录账号/手机号！`);
      }
    },
    codeUpdatePwd() {
      this.$refs.passForm.validate((valid) => {
        if (valid) {
          if(this.passForm.pw!=this.passForm.cpw){
            this.$modal.msgError(`两次输入的密码不一致，请重新输入！`);
            return false;
          }
          this.loading = true;
          this.passForm.password = this.passForm.pw;
          this.passForm.confPass = this.passForm.cpw;
          this.passForm.code = this.passForm.pCode;
          codeUpdatePwd(this.passForm).then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess(`密码修改成功！`);
              this.loading = false;
              this.isLogin = true;
            }
          }).catch((err) => {
            this.loading = false;
          })
        }
      });
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss">
@media only screen and (min-width: 1600px) {
  .login-bg {
    background-size: 100% 100%;
  }
}
.login-bg {
  background-image: url("/images/bg1.png?v=20230923");
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0px;
  left: 0px;
  /** opacity: 0.4; */
}
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;

  background-size: cover;
}
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #333;
  font-weight: bold;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  z-index: 9;
  opacity: 0.9;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 29%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
  color: #111;
  text-shadow: 3px 3px 5px #d3a3a3;
}
.login-code-img {
  height: 38px;
}
</style>
