<template>
  <!--<div class="login-container">-->
  <!--<div class="login-page login-cover">-->
  <!--  <div class="cover-container">-->
  <!--    <div class="cover-center">-->
  <!--      <div class="cover-center__left">-->
  <!--        <p class="left-base-content">智慧校园</p>-->
  <!--        <p>智慧校园系统是通过信息化手段,实现对校园内各类资源的有效集成 整合和优化，实现资源的有效配置和充分利用，将校务管理过程的优化协调。为校园提供数字化教学、数字化学习、数字化科研和数字化管理。</p>-->
  <!--      </div>-->
  <!--      <div class="cover-center__right">-->
  <!--        <el-image-->
  <!--          style="width: 600px;"-->
  <!--          :src="require('@/assets/images/logo-login.gif')"-->
  <!--        ></el-image>-->
  <!--      </div>-->
  <!--    </div>-->
  <!--  </div>-->
  <!--</div>-->
  <!--</div>-->
  <div class="login">
    <div class="login-card-container">
      <div class="login-card-left">
        <el-image style="width: 600px;" :src="require('@/assets/images/login.png')" lazy></el-image>
        <!--          :src="require('@/assets/images/logo-login.gif')"-->
      </div>
      <div class="login-card-right">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
<!--          <h3 class="title">智慧校园管理系统</h3>-->
          <h3 class="title">智慧校园管理系统</h3>
          <el-form-item prop="phonenumber">
            <el-input v-model="loginForm.phonenumber" 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="text" style="text-security:disc; -webkit-text-security:disc;"
              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: 63%"-->
          <!--          @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-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
          <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>
    <!--  底部  -->
    <div class="el-login-footer">
<!--      <span>© 2021 zhimin Copyright </span>-->
    </div>
  </div>
</template>



<script>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import * as dd from 'dingtalk-jsapi';
import { getCode } from "@/api/ddLogin";
import { getToken, setToken, removeToken } from '@/utils/auth'
import VueRouter from "vue-router";

export default {
  name: "Login",
  data() {
    return {
      code: null,
      token: null,
      codeUrl: "",
      loginForm: {
        // username: "admin",
        phonenumber: '',
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        // username: [
        //   { required: true, trigger: "blur", message: "请输入您的账号" }
        // ],
        phonenumber: [
          { required: true, trigger: "blur", message: "请输入您的手机号码" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        // code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 验证码开关
      // captchaEnabled: true,
      captchaEnabled: false,
      // 注册开关
      register: false,
      redirect: undefined
    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    this.getCode();

  },
  mounted() {
    // this.getCode();
    this.getCookie();
  },
  methods: {
    // 获取code
    getCode() {
      dd.getAuthCode({
        //测试
        // corpId: 'dingaa3937ff8b7dd267f2c783f7214b6d69',
        //正式
        corpId: 'dingccea40788226c988f2c783f7214b6d69',
        success: (res) => {
          console.log('获取新的免登码成功', res);
          const code = res.code
          // this.code = code;
          // this.authCodeTimestamp = currentTime;
          // console.log('this.authCodeTimestamp', this.authCodeTimestamp);
          console.log('code', code);
          this.getToken(code)
          // console.log('loginResponse', loginResponse);
        },
        fail: (res) => {
          console.log('获取免登码失败', res);
        },
        complete: () => { },
      });
    },
    // 获取token
    getToken(code) {
      getCode(code).then(res => {
        if (res) {
          setToken(res)
          this.$store.commit('SET_TOKEN', res)
          this.$router.push({ path: '/' });
          // 判断当前用户是否已拉取完user_info信息
          this.$store.dispatch('GetInfo').then((res) => {
            this.$store.dispatch('GenerateRoutes').then(accessRoutes => {
              // 根据roles权限生成可访问的路由表
              router.addRoutes(accessRoutes) // 动态添加可访问路由表
            })
          })
        } else {
          this.$message.error(res.message)
        }

      })
    },
    // 获取token
    // async loginWithAuthCode(code) {
    //   console.log('code', code);
    //   try {
    //     // 向后端发送请求，使用免登码进行登录
    //     const loginResponse = await getCode({ code });
    //     console.log('code', code);
    //     this.$router.push({ path: '/index' });
    //     console.log('跳转页面');
    //     // 处理登录成功的情况，可能需要保存用户信息或者跳转到其他页面
    //     console.log('用户登录成功', loginResponse);
    //     const { token } = loginResponse.data; // 假设返回的数据中包含 token 字段
    //     console.log('用户 Token:', token); // 打印返回的 Token
    //   } catch (error) {
    //     // 处理登录失败的情况
    //     // console.error('登录失败', error);
    //   }
    // }
    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 phonenumber = Cookies.get("phonenumber");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        // username: username === undefined ? this.loginForm.username : username,
        phonenumber: phonenumber === undefined ? this.loginForm.phonenumber : phonenumber,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            // Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("phonenumber", this.loginForm.phonenumber, { 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("phonenumber");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || "/" }).catch(() => {
            });
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    }


  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  background-color: rgba(0, 191, 255, 0.15);
}

.login-container {
  //transition: transform .5s ease-in;

  .login-page {
    //height: 100vh;
  }
}

// 封面背景
.login-cover {
  //background-image: url("~@/assets/images/head_img.png");
  background-size: cover;
}

// 封面内容
.cover-container {
  width: 1200px;
  margin: auto;
  height: 100%;
  display: flex;
  flex-direction: column;

  .cover-center {
    position: relative;

    .cover-center__left {
      position: absolute;
      left: 0;
      top: 0;
      display: flex;
      flex-direction: column;
    }

    .cover-center__right {
      position: absolute;
      width: 559px;
      height: 559px;
      right: 0;

    }
  }
}

// 封面左侧内容
.left-base-content {
  font-size: 50px;
}

// 登录页
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  //background-image: url("~@/assets/images/head_img.png");
  background-size: cover;

  .login-card-container {
    display: flex;
    //padding: 20px;
    //justify-content: center;
    //align-items: center;


    .login-card-right {
      display: flex;
      padding-left: 256px;
    }
  }
}

.el-card.is-always-shadow {
  -webkit-box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: #fff4;
  backdrop-filter: blur(6px);
}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  //color: #707070;
  color: #0988ef;
}

.login-form {
  border-radius: 6px;
  border: 1px solid #e0e0e0;
  box-shadow: 0 0 10px 1px #e0e0e0;
  background: aliceblue;
  width: 350px;
  margin: auto;
  padding: 30px 20px 20px 20px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: absolute;
  bottom: 0;
  width: 100%;
  text-align: center;
  //color: #fff;
  color: #989797;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
</style>
