<template>
  <div class="login-view">

    <div class="logo space-x-[10px]">
      <img src="@/assets/images/logo/logo.png" alt=""></img>
      <img src="@/assets/images/logo/logo-text.svg" alt=""></img>
    </div>
    
    <div class="login-text">
      <img src="@/assets/images/login/bg-text.svg" alt=""></img>
    </div>

    <el-form ref="loginRef" :model="loginForm" class="login-form">
      <h3 class="title">账号登录</h3>
      <div class="main">
        <el-form-item prop="username">
          <el-input
            v-model="loginForm.username"
            type="text"
            size="large"
            auto-complete="off"
            placeholder="请输入登录账号"
          ></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password"
            type="password"
            size="large"
            auto-complete="off"
            placeholder="请输入登录密码"
            @keyup.enter="handleLogin"
          ></el-input>
        </el-form-item>
        <el-form-item style="width:100%;">
          <div class="w-full h-[116px]">
            <div class="error-tips space-x-[4px]" v-show="errorMsg">
              <el-icon><Warning /></el-icon>
              <span>{{ errorMsg }}</span>
            </div>
          </div>
          <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>
      </div>
    </el-form>
    <!--  底部  
    -->
    <div class="el-login-footer">
      <span>哈尔滨跃渊环保智能装备有限责任公司 技术支持</span>
    </div>
    
  </div>
</template>

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

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

const loginForm = ref({
  username: "",
  password: "",
  rememberMe: false,
  code: "",
  uuid: ""
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }]
};

const errorMsg = ref("");

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(true);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);

watch(route, (newRoute) => {
    redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

function handleLogin() {

  const { username, password } = unref(loginForm);

  if (!username) {
    return errorMsg.value = '请输入用户名称'
  }
  if (!password) {
    return errorMsg.value = '请输入登录密码'
  }
  
  errorMsg.value = '';

  loading.value = true;
  
  // 调用action的登录方法
  userStore.login(loginForm.value).then(() => {
    const query = route.query;
    const otherQueryParams = Object.keys(query).reduce((acc, cur) => {
      if (cur !== "redirect") {
        acc[cur] = query[cur];
      }
      return acc;
    }, {});

    usePermissionStore().generateRoutes().then(accessRoutes => {
      if ( accessRoutes.length ) {
        const path = accessRoutes[0]?.children[0]?.path;
        router.push({ path });
        // let isOff = false;
        // accessRoutes.forEach(({ children }) => {
        //   children?.forEach(item => {
        //     if ( item.path === 'voice/workbench' ) {
        //       isOff = true;
        //     }
        //   })
        // });

        // if ( isOff ) {
        //   router.push({ path: "/voice/workbench", query: otherQueryParams });
        // } else {
        //   const path = accessRoutes[0]?.children[0]?.path;
        //   router.push({ path });
        // }
      } else {
        loading.value = false;
        proxy.$modal.msgError("当前账号未分配权限");
        removeToken();

      }
    })
    
    // router.push({ path: "/voice/workbench", query: otherQueryParams });
  }).catch(() => {
    loading.value = false;
  });
}

function getCode() {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = "data:image/gif;base64," + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value = {
    username: username === undefined ? loginForm.value.username : username,
    password: password === undefined ? loginForm.value.password : decrypt(password),
    rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
  };
}

// getCode();
getCookie();
</script>

<style lang='scss' scoped>
.login-view {
  position: relative;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login/bg-login-text.png");
  background-size: cover;
}

.login-text {
  position: absolute;
  left: 180px;
  top: 240px;
}

.logo {
  position: absolute;
  left: 38px;
  top: 38px;
  display: flex;
  align-items: center;
}

.login-form {
  width: 440px;
  margin-right: 100px;
  border-radius: 12px;
  border: 2px solid #FFF;
  background: rgba(255, 255, 255, 0.8);
  box-shadow: 0px 2px 80px 5px rgba(19, 29, 107, 0.06);
  position: relative;
  z-index: 11;

  .title {
    padding: 20px 0 20px 60px;
    border-bottom: 1px solid #EDEFF2;
    text-align: left;
    font-size: 24px;
    font-weight: bold;
    color: #1D2129;
  }
  
  .main {
    padding: 60px 60px 66px 60px;

    :deep(.el-input__wrapper) {
      border: 1px solid #F2F4F9;
      border-radius: 8px;
      box-shadow: none;
    }
    
    .error-tips {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 32px;
      border-radius: 8px;
      background: #FFF1F0;
      text-align: center;
      font-size: 12px;
      color: #FF7152;
    }

    .el-button {
      height: 54px;
      border-radius: 8px;
      background: linear-gradient(91deg, #165DFF 0.41%, #00A6FF 97.92%);
      font-size: 18px;
    }
  }

  .el-input {
    height: 54px;
    input {
      height: 54px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  position: absolute;
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 20px;
  width: 100%;
  text-align: center;
  color: #989EA7;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
