<template>
  <div class="login" v-loading="loginLoading" element-loading-text="自动登录中，请稍等">
    <div class="img">
      <!-- <img :src="getImgUrl('indexImages/bb.png')" alt="" /> -->
    </div>
    <div class="box-logo">
      <img :src="getImagePath('loginbg_new.png')" />
    </div>
    <div class="box">
      <div class="box-logoright">
        <img :src="getImagePath('Mask_group_new.png')" />
      </div>
      <div class="box-title">欢迎登录</div>
      <!-- <div class="tab">
        <span :class="openshow ? 'colors' : 'cuper'" @click="openshow = true">密码登录</span>
        <span class="ml10 mr10">/</span>
        <span :class="!openshow ? 'colors' : 'cuper'" @click="openshow = false">二维码登录</span>
      </div> -->
      <div v-if="openshow">
        <el-form v-if="!loginLoading" :model="loginForm" ref="loginFromRef" label-width="0" label-position="right"
          @submit.prevent :class="isTrue ? '' : 'mt63'">
          <el-form-item prop="userName" class="row" :rules="{ required: true, message: '请输入账号', trigger: 'blur' }">
            <!-- <img class="icon" :src="getImgUrl('indexImages/yonghu.png')" alt="" /> -->
            <img class="icon" :src="getImagePath('Vector.png')" alt="" />
            <div
              style="height: 34px;width: 2px;background-color: rgb(18, 135, 141);position: absolute;top: 9px;left: 37px;z-index: 999;">
            </div>
            <el-input class="input" v-model="loginForm.userName" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item prop="password" class="row" :rules="{ required: true, message: '请输入密码', trigger: 'blur' }">
            <!-- <img class="icon" :src="getImgUrl('indexImages/suo.png')" alt="" /> -->
            <img class="icon" :src="getImagePath('suo.png')" alt="" />
            <div
              style="height: 34px;width: 2px;background-color: rgb(18, 135, 141);position: absolute;top: 9px;left: 37px;z-index: 999;">
            </div>
            <el-input class="input" type="password" v-model="loginForm.password" show-password placeholder="请输入密码" />
          </el-form-item>
          <el-form-item v-if="isTrue" prop="kaptcha" :rules="{ required: true, message: '请输入验证码', trigger: 'blur' }">
            <el-input class="inputyzm" v-model="loginForm.kaptcha" placeholder="请输入验证码">
            </el-input>
          </el-form-item>
          <el-form-item label-width="0">
            <el-button class="login-btn" native-type="submit" :loading='loading' @click="handleLogin()">
              登录
            </el-button>
          </el-form-item>
        </el-form>
        <img v-if="isTrue" class="imgsyzm" :src="ErmImg" alt="" />
      </div>
      <!-- <div class="tab" v-if="openshow" @click="openshow = false">
        <div class="box-logo" style="cursor: pointer">
          <img :src="getImagePath('erweima.png')" />
        </div>
        <div :class="openshow ? 'colors' : 'cuper'">扫码登录</div>
      </div> -->
    </div>
    <div class="botbox" v-if="!openshow">
      <MOSTY.ErwmImg :url="qrcodepxImg(uuid, 'login', '', '')" :filename='"扫码登录二维码"' />
    </div>
    <div class="user" v-if="!openshow" @click="openshow = true">
      <div><img class="icon" :src="getImagePath('Vector.png')" alt="" /></div>
      <div>账号密码登录</div>
    </div>
  </div>
</template>
<script setup>
import { getImgUrl } from "@/utils/tools.js"
import { onMounted, ref, onUnmounted } from "vue";
import { useStore } from "vuex";
import { useRouter } from "vue-router";
import { ElMessageBox, ElMessage } from "element-plus"
import { setItem } from "@/utils/storage";
import { getApi, getApiToken } from "@/api/tobAcco_api.js";
import * as MOSTY from "@/components/MyComponents/index";
import { qrcodepxImg, generateUUID } from "@/utils/tools.js";
import Base64 from "base-64";
const getImagePath = (src) => {
  return 'assets/indexImages/' + src
};
const store = useStore();
const router = useRouter();
const isTrue = ref(false)
const timer = ref(null);//定时器
const uuid = ref(generateUUID())
const ErmImg = ref('')
const openshow = ref(true)
const loginForm = ref({
  userName: "",
  password: "",
  kaptcha: "",
  loginType: "02",
  checked: false
});
const loading = ref(false);
const loginFromRef = ref(null);
const handleLogin = () => {
  loginFromRef.value.validate((valid) => {
    if (!valid) return false;
    loading.value = true;
    getlogin()
  });
};
function getlogin() {
  loginForm.value.loginType = '02'
  store.dispatch("user/login", loginForm.value)
    .then((res, code) => {
      loading.value = true;
      // 登录后操作
      if (res) {
        if (res == 4090) {
          loading.value = false;
          getApi({ username: loginForm.value.userName }, '/mosty-base/getKaptcha').then((res) => {
            ErmImg.value = res
            isTrue.value = true
          })
        } else {
          if (loginForm.value.checked) {
            localStorage.setItem("userName", loginForm.value.userName);
            localStorage.setItem("password", loginForm.value.password);
          } else {
            localStorage.setItem("userName", "");
            localStorage.setItem("password", "");
          }
          // 登录成功后，跳转到首页
          store.commit(
            "app/addTagsViewList",
            {
              fullPath: "/dutyBook/home/workbench",
              meta: {
                meta: {
                  title: "工作台"
                  // icon: "gerenzhongxin"
                }
              },
              name: "dutyBook/home/workbench",
              params: {},
              path: "/dutyBook/home/workbench",
              query: {},
              title: "工作台"
            },
            {
              immediate: true
            }
          );
          // router.push('/editPassword')
          router.push('/dutyBook/home/workbench')
          // router.push('/newsystem').then(() => {
          //   // 如果路由已经切换完成，则刷新页面
          //   location.reload();
          // });
          getuserinfo()
        }

      } else {
        deptList.value = [...res.dept];
        loginDialog.value = true;
        authorization.value = res.jwtToken;
        ElNotification({
          title: "提示",
          message: "请选择部门",
          duration: 3000
        });
      }
    })
    .catch((err) => {
      loading.value = false;
    });
}
function jump() {
  console.log('跳转');
  router.push('/preview')
}
//	查询用户配置主题色信息
function getuserinfo() {
  getApi({}, '/mosty-base/userConfig/getConfig').then(res => {
    if (res && res.color) {
      setItem("ZtColor", res.color);
    } else {
      setItem("ZtColor", 'rgba(4, 128, 134, 1)');
    }
  })
}
onMounted(() => {
  let userName = localStorage.getItem("userName");
  let password = localStorage.getItem("password");
  if (userName && password) {
    loginForm.value = {
      userName: userName,
      password: password,
      checked: true
    };
  } else {
    loginForm.value = {
      userName: "",
      password: "",
      checked: false
    };
  }
  checkTokenFromUrl()
  start()
});
//开启定时器方法
const start = () => {
  //定时器触发周期
  let speed = ref(2000);
  //setInterval会返回一个id,clearTimeout拿到该id才可清除
  timer.value = setInterval(MarqueeTest, speed.value);
};
const MarqueeTest = () => {
  //获取用户登录数据
  getApi({}, '/mosty-base/checkLogin?loginToken=' + uuid.value).then((res) => {
    if (res.loginResult == 'Y') {
      //清除定时器
      clearTimeout(timer.value);
      loginForm.value.userName = Base64.decode(res.loginName)
      loginForm.value.password = Base64.decode(res.password)
      getlogin()
      console.log('9 二维码 重新登录');
    }
  })
};
// 单点登录
const loginLoading = ref(false)
const checkTokenFromUrl = () => {
  const hash = window.location.hash;
  if (hash.includes('?')) {
    const queryString = hash.split('?')[1];
    const params = new URLSearchParams(queryString);
    const ssoToken = params.get('sso_token');
    const redirectUrl = params.get('redirect_url');
    if (ssoToken) {
      loginLoading.value = true;
      getApiToken({ token: ssoToken }, '/mosty-platform/platform/tokenAccess').then((res) => {
        if (res && Object.keys(res).length > 0) {
          let loginForm = {
            userName: res.userName,
            loginType: "02",
            thridLogin: true,
            verifyCode: res.verifyCode,
          }
          const cleanHash = hash.split('?')[0];
          window.history.replaceState({}, document.title, window.location.pathname + cleanHash);
          store.dispatch("user/oatuhTokenLogin", loginForm)
            .then((res, code) => {
              if (res) {
                if (res == 4090) {
                  getApi({ username: loginForm.userName }, '/mosty-base/getKaptcha').then((res) => {
                    ErmImg.value = res
                    isTrue.value = true
                  })
                } else {
                  if (!loginForm.thridLogin) {
                    localStorage.setItem("userName", loginForm.value.userName);
                    localStorage.setItem("password", loginForm.value.password);
                  } else {
                    localStorage.setItem("userName", "");
                    localStorage.setItem("password", "");
                  }
                  if (redirectUrl && isValidRedirect(redirectUrl)) {
                    router.push(redirectUrl)
                  } else {
                    store.commit(
                      "app/addTagsViewList",
                      {
                        fullPath: "/dutyBook/home/workbench",
                        meta: {
                          meta: {
                            title: "工作台"
                          }
                        },
                        name: "dutyBook/home/workbench",
                        params: {},
                        path: "/dutyBook/home/workbench",
                        query: {},
                        title: "工作台"
                      },
                      {
                        immediate: true
                      }
                    );
                    router.push('/dutyBook/home/workbench')
                  }
                  getuserinfo()
                }
              } else {
                loginLoading.value = false;
              }
            })
            .catch((err) => {
              loginLoading.value = false;
            });
        } else {
          loginLoading.value = false;
          ElMessage({
            message: "自动登录失败，请手动登录",
            type: "error",
            duration: 3000
          })
        }
      })
    } 
  }

  return null;
}
/**
 * 验证重定向地址是否安全
 */
const isValidRedirect = (url) => {
  // 只允许相对路径
  return !url.startsWith('http://') && !url.startsWith('https://');
};
onUnmounted(() => {
  loginLoading.value = false;
  //清除定时器
  clearTimeout(timer.value);
});
</script>

<style lang="scss" scoped>
.login {
  background: url("~@/assets/images/logobg_new.png") no-repeat center;
  background-size: 100% 100%;
  border: 1px solid #979797;
  height: 970;
  overflow: hidden;
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  z-index: 1;
  font-family: PingFangSC-Regular;

  h1 {
    font-size: 40px;
    text-align: center;
    letter-spacing: 10px;
  }

  .aqbybox {
    display: flex;
    justify-content: center;
    text-align: center;
    font-size: 20px;
    background: linear-gradient(to bottom, #ffffff, #00ffff);
    -webkit-background-clip: text;
    color: transparent;

    >span {
      margin: 0 10px;
    }
  }

  .img {
    // width: 719px;
    // height: 651px;
    // background-color: #ffffff;
    position: absolute;
    left: 79.5%;
    top: 49%;
    transform: translate(-50%, -50%);
    // background-color: rgb(0, 19, 34);

    img {
      width: 600px;
      height: 560px;
    }
  }

  .box-logo {
    position: absolute;
    left: 30px;
    top: 30px;
  }

  .box {
    width: 650px;
    height: 550px;
    border-radius: 10px;
    background-color: #ffffff;
    z-index: 999;
    background-size: 100% 100%;
    position: absolute;
    left: 81%;
    top: 47%;
    transform: translate(-50%, -50%);
    padding: 50px 109px;
    box-sizing: border-box;


    .box-logoright {
      position: absolute;
      top: -12px;
      right: -13px;
    }

    .box-title {
      // margin-top: 20px;
      // margin-bottom: 20px;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 500;
      font-size: 32px;
      text-align: center;
      color: rgba(4, 128, 134, 1)
    }

    .row {
      margin-bottom: 24px;
      position: relative;
      border-radius: 10px;

      .icon {
        position: absolute;
        z-index: 55;
        width: 15px;
        height: 20px;
        left: 10px;
        top: 17px;
      }
    }

    :deep(.el-input) {
      --el-input-placeholder-color: #007c9d !important;
    }

    .input {
      display: block;
      background: rgba(230, 242, 243, 1) !important;
      // border: 1px solid rgba(33, 142, 147, 0);
      height: 54px;
      box-sizing: border-box;
      color: #fff;
      width: 100%;
      border-radius: 10px;

      &::-webkit-input-placeholder {
        font-size: 16px;
        color: rgba(230, 242, 243, 1) !important;
        font-weight: 400;
      }
    }

    .login-btn {
      display: block;
      width: 100%;
      height: 54px;
      line-height: 40px;
      text-align: center;
      font-size: 18px;
      color: rgba(255, 255, 255, 1);
      font-weight: 400;
      background: rgba(33, 142, 147, 1);
      margin-top: 5px;
      border: none;
      cursor: pointer;
      border-radius: 6px;

      &:hover {
        // background-color: rgb(72, 210, 210);
      }
    }
  }
}

.tab {
  text-align: center;
  font-size: 21px;
}

.el-form {
  display: block;
}

::v-deep .el-input__inner {
  height: 100%;
  padding: 0 0 0 48px;
  background: rgba(230, 242, 243, 1) !important;
  border: none;
}

::v-deep .el-input-group__append::before {
  height: 30px;
}

.inputyzm {
  padding: 0px;
  // display: block;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.2);
  height: 54px;
  box-sizing: border-box;
  color: #fff;
  width: 45%;
  border-radius: 10px;

  &::-webkit-input-placeholder {
    font-size: 16px;
    color: rgba(18, 135, 141, 1);
    font-weight: 400;
  }

  ::v-deep .el-input__inner {
    height: 100%;
    padding: 0 0 0 12px !important;

  }
}



.footerInfor {
  position: fixed;
  bottom: 88px;
  left: 50%;
  transform: translateX(-50%);
  color: #fff;

  .info {
    text-align: center;

    a {
      color: #2b91fb;
      text-decoration-line: underline;
      text-decoration-color: #2b91fb;
    }
  }
}

.logo {
  margin-top: 20px;
  margin-left: 20px;
}

.el-checkbox {
  color: #fff;
  --el-checkbox-checked-bg-color: rgba(18, 135, 141, 1);
}

::v-deep .el-checkbox__input.is-checked+.el-checkbox__label {
  color: aqua !important;
}

.colors {
  cursor: pointer;
  color: rgba(33, 142, 147, 1);
}

.cuper {
  cursor: pointer;
}

.imgsyzm {
  position: relative;
  height: 52px;
  width: 200px;
  bottom: 149px;
  /* right: -41px; */
  left: 173px;
}

.botbox {
  ::v-deep .el-image {
    margin-left: 12px !important;
    width: 222px !important;
    height: 221px !important;
  }

  position: absolute;
  z-index: 9999;
  left: 69%;
  top: 39%;
}

.user {
  cursor: pointer;
  color: rgba(33, 142, 147, 1);
  position: absolute;
  z-index: 9999;
  left: 73%;
  top: 72%;
  display: flex;
  align-items: center;
  font-size: 15px;

  div:nth-child(1) {
    margin-right: 10px;
  }

}
</style>
