<template>
  <div class="login">
    <div class="lg_left">
        <img src="@/assets/jft.png" class="lg_logo" alt="Image">
        <div class="lg_h2">就服通</div>
    </div>
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form" label-position="top">
      <div class="sign">
          <img v-if="sign" src="@/assets/images/saoma.png" style="width: 120px;" @click="toggleSign">
          <img v-else src="@/assets/images/zhanghao.png" style="width: 143px;" @click="toggleSign">
      </div>
      <h2 class="title">欢迎登录 <span style="color: #346DF2;">就服通</span></h2>
      <template v-if="sign">
        <el-form-item prop="account" label="用户名">
          <el-input
            v-model="loginForm.account"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="输入后台账号"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input
            v-model="loginForm.password"
            type="password"
            size="large"
            auto-complete="off"
            placeholder="输入登录密码"
            @keyup.enter="handleLogin"
          >
          </el-input>
        </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="large"
            type="primary"
            style="width:100%;"
            @click.prevent="handleLogin"
          >
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
        </el-form-item>
      </template>
      <template v-else>
        <div class="qrCode" id="qrCode" ref="qrcode"></div>
      </template>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2018-2024 ruoyi.vip All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup>
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user'
import {getLoginQRcode, loginState} from '@/api/login'

const userStore = useUserStore()
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

const loginForm = ref({
  account: "",
  password: "",
  rememberMe: false,
});
let sign = ref(true)
let qrcode = ref("");
let qrcodeKey = ref("")
let intervalFlush
const loginRules = {
  account: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
};

const loading = ref(false);
const redirect = ref(undefined);

watch(route, (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });
function handleLogin() {
  proxy.$refs.loginRef.validate(valid => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        Cookies.set("account", loginForm.value.account, { expires: 30 });
        Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
      } else {
        // 否则移除
        Cookies.remove("account");
        Cookies.remove("password");
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then((res) => {
        if (res.code == "200") {
          const query = route.query;
          const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
            if (cur !== "redirect") {
              acc[cur] = query[cur];
            }
            return acc;
          }, {});
          router.push({ path: "/", query: otherQueryParams });
        }else {
          proxy.$modal.msgError(res.message);
          loading.value = false;
        }
      }).catch(() => {
        loading.value = false;
      });
    }
  });
}

function getCookie() {
  const account = Cookies.get("account");
  const password = Cookies.get("password");
  loginForm.value = {
    account: account === undefined ? loginForm.value.account : account,
    password: password === undefined ? loginForm.value.password : decrypt(password),
  };
}
const toggleSign = async () => {
    sign.value = !sign.value;
    qrcode.value = "";
    if (intervalFlush) {
        clearInterval(intervalFlush)
    }
    if (!sign.value) {
        const { isSuccess, data } = await getLoginQRcode();
        if (isSuccess) {
            new WxLogin({
                self_redirect: true,
                id: 'qrCode', // 需要显示的容器id
                appid: 'wxbd5b6f7d18e73397', // 公众号appid wx*******
                scope: 'snsapi_login', // 网页默认即可
                redirect_uri: encodeURI('https://cha.365jft.com/djl-account/wx/channel/callback'), // 授权成功后回调的url
                state: data.key, // 可设置为简单的随机数加session用来校验
                style: 'black', // 提供"black"、"white"可选。二维码的样式
                href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4OyBtYXJnaW46MH0KLmltcG93ZXJCb3ggLnRpdGxlIHtkaXNwbGF5OiBub25lO30KLmltcG93ZXJCb3ggLmluZm8ge3dpZHRoOiAyMDBweDt9Ci5zdGF0dXNfaWNvbiB7ZGlzcGxheTogbm9uZX0KLmltcG93ZXJCb3ggLnN0YXR1cyB7dGV4dC1hbGlnbjogY2VudGVyO30=', // 外部css文件url，需要https
            })
            qrcodeKey.value = data.key
            getQrcodeKeyState()
        }
      }
};
const getQrcodeKeyState = () => {
    intervalFlush = setInterval((async ()=>{
        const { data, isSuccess, code } = await loginState({key: qrcodeKey.value});
        if (isSuccess) {
            if (data.state == 2) {
                clearInterval(intervalFlush)
                let form = {
                  account: data.account,
                  password: data.password,
                  loginType: 'scan'
                }
                userStore.login(form).then((res) => {
                  if (res.code == "200") {
                    const query = route.query;
                    const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
                      if (cur !== "redirect") {
                        acc[cur] = query[cur];
                      }
                      return acc;
                    }, {});
                    router.push({ path: "/", query: otherQueryParams });
                  }else {
                    proxy.$modal.msgError(res.message);
                    loading.value = false;
                  }
                }).catch(() => {
                  loading.value = false;
                });
            }
        } else {
            clearInterval(intervalFlush)
            ElMessage.error(prompt[code]);
            sign.value = !sign.value;
        }
    }),2000)
}
onUnmounted(() => {
    if (intervalFlush) {
        clearInterval(intervalFlush)
    }
})
getCookie();
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/bj.png");
  background-size: cover;
  position: relative;
  .lg_left {
    position: absolute;
    left: 200px;
    top: 10px;
    display: flex;
    .lg_logo {
        width: 70px;
        height: 70px;
        margin-right: 10px;
        margin-top: 25px;
    }
    .lg_h2 {
        color: #000;
        font-size: 40px;
        font-weight: 600;
        line-height: 120px;
        font-style: italic;
    }
  }
  .login-form {
    background: #ffffff;
    width: 380px;
    height: 471px;
    padding: 30px;
    position: absolute;
    border-radius: 20px;
    right: 24%;
    top: 22%;
    box-shadow: 0px 0px 12px rgba(0,0,0,.2);
    overflow: hidden;
    .sign{
      position: absolute;
      top: 0;
      right: 0;
    }
    .title {
      padding: 30px 0;
      text-align: left;
      color: #707070;
    }
    .el-input {
      height: 40px;
      input {
        height: 40px;
      }
    }
    .el-button{
      height: 34px;
    }
    .input-icon {
      height: 39px;
      width: 14px;
      margin-left: 0px;
    }
    .qrCode {
        width: 200px;
        height: 200px;
        margin-left: 9px;
        iframe {
            width: 200px !important;
            height: 200px;
        }
    }
  }
  .el-login-footer {
    height: 40px;
    line-height: 40px;
    position: fixed;
    bottom: 0;
    width: 100%;
    text-align: center;
    color: #fff;
    font-family: Arial;
    font-size: 12px;
    letter-spacing: 1px;
  }
}

</style>
