<template>
  <div class="login-by-account">
    <el-form ref="loginFormRef" label-position="top" :model="loginForm" :rules="steploginFormRules">
      <el-form-item prop="userid">
        <el-input v-model="loginForm.userid" placeholder="请输入账号" @keyup.enter.native="loginAction()" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          :type="hidePassword ? 'password' : 'text'"
          v-model="loginForm.password"
          placeholder="请输入密码"
          @keyup.enter.native="loginAction()">
          <span
            slot="suffix"
            :title="hidePassword ? '显示密码' : '隐藏密码'"
            :class="hidePassword ? 'hide-password' : 'show-password'"
            @click="hidePassword = !hidePassword"
            style="cursor: pointer"></span>
        </el-input>
      </el-form-item>
      <el-form-item prop="yzm">
        <div class="msg-code">
          <el-input
            v-model="loginForm.yzm"
            placeholder="请输入验证码"
            @keyup.enter.native="loginAction()"
            style="width: 240px" />
          <div class="yzm_img">
            <img title="看不清？换一张" :src="imgSrc" @click="getImg()" style="width: 100%" />
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loginAction()" style="width: 100%"> 登 录 </el-button>
      </el-form-item>
      <el-form-item style="margin-top: 24px">
        <el-button class="register_btn" @click.prevent="$emit('register')" style="width: 100%">
          还没有账号？前往注册&emsp;
          <bg-icon style="font-size: 12px; margin-right: 8px" icon="#bg-ic-arrow-right"></bg-icon>
        </el-button>
      </el-form-item>
      <div class="regist_bottom">
        <el-checkbox v-model="rememberPassword">记住密码</el-checkbox>
        <span class="fr forget_psd" @click.prevent="$emit('password')">忘记密码？</span>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import CryptoJS from "crypto-js";
import { getCookie, clearCookie, setCookie } from "@/services/cookie.js";
import menu from "../router/function";
import { generateRoutes } from "../router/index";
import { reactive, toRefs, ref, onBeforeMount, nextTick } from "vue";
import { ElMessage } from "element-plus";
import axios from "@/request/http.js";
import { Encrypt } from "@/services/secret.js";
import { useStore } from "vuex";

const state = reactive({
  loginForm: {
    userid: "",
    password: "",
    yzm: "",
  },
  steploginFormRules: {
    userid: [{ required: true, message: "请输入账号", trigger: "blur" }],
    password: [{ required: true, message: "请输入密码", trigger: "blur" }],
    yzm: [{ required: true, message: "请输入验证码", trigger: "blur" }],
  },
  imgId: "",
  imgSrc: "",
  identifyCode: "",
  hidePassword: true,
  rememberPassword: false,
});

const store = useStore();

const loginFormRef = ref(null);

const loginAction = () => {
  if (state.rememberPassword) {
    let userinfo = window.btoa(encodeURI(`${state.loginForm.userid},${state.loginForm.password}`));
    setCookie("userinfo", userinfo);
  } else {
    clearCookie("userinfo");
  }

  loginFormRef.value.validate((valid) => {
    if (valid) {
      axios.get(`/apaas/system/v5/user/verifyCaptcha?id=${state.imgId}&value=${state.loginForm.yzm}`).then((res) => {
        if (res.data.code == 200) {
          login();
        } else {
          ElMessage.error(res.data.data);
        }
      });
    }
  });
};
const login = () => {
  axios
    .post(`/apaas/system/v5/user/login`, {
      system_account: state.loginForm.userid,
      password: Encrypt(state.loginForm.password),
    })
    .then(({ data }) => {
      if (data.code == 200) {
        getUser();
      } else {
        getImg(true);
        ElMessage.error(data.data);
      }
    })
    .catch((error) => {
      console.log(error);
    });
};
const getUserInfo = () => {
  return axios.get(`/apaas/system/v5/user/getUserInfo`);
};
const getMenu = (search) => {
  return axios.get(`/apaas/system/v5/menu/user/tree?search=${search}`);
};
const getUser = () => {
  Promise.all([getUserInfo(), getMenu("dadb2d3f-e263-48d1-9389-42acb9ea49f8")]).then((res) => {
    if (res[0].data.code == 200 && res[1].data.code == 200) {
      let data = (res[1].data.data && res[1].data.data[0].children) || [];
      store.commit("setUserInfo", res[0].data.data);
      // if (res.data.data.userType == 1) {
      //超管
      store.commit("setMenu", data);

      menu.menuToRouter(data);

      store.commit("setRoute", data);

      //存储菜单对象信息
      let menuObj = {};
      getMenuObj(data, "", menuObj);
      store.commit("setMenuObj", menuObj);
      // }
      generateRoutes();
      // this.$router.push("/");
      //跳转到工作台页面
      window.location.href = "/apaas/portal/ui/#/";
    }
  });
};
const getMenuObj = (menu, parentRowPath, menuObj) => {
  menu.forEach((e, idx) => {
    e.rowPath = parentRowPath + "." + idx;
    menuObj[e.path] = e;
    if (e.children && e.children.length) {
      getMenuObj(e.children, e.rowPath, menuObj);
    }
  });
};
const getImg = (clearInput = false) => {
  axios.get(`/apaas/system/v5/user/getCaptcha??width=240&height=32`).then((res) => {
    if (res.data.code == 200) {
      state.imgId = res.data.data.id;
      state.imgSrc = res.data.data.captcha;
    }
  });
  if (clearInput) {
    state.loginForm.yzm = "";
  }
};
onBeforeMount(() => {
  getImg();
  if (getCookie("userinfo")) {
    let userinfo = window.atob(decodeURI(getCookie("userinfo"))).split(",");

    state.loginForm.userid = userinfo[0];
    state.loginForm.password = userinfo[1];
    state.checked = true;

    state.rememberPassword = true;
  } else {
    state.checked = false;
  }
});
const { loginForm, steploginFormRules, imgId, imgSrc, identifyCode, hidePassword, rememberPassword } = toRefs(state);
</script>

<style lang="scss" scoped>
.login-by-account {
  .msg-code {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .yzm_img {
      flex: 1;
    }

    > .bg-identify {
      margin-left: 6px;
      flex-shrink: 0;
    }
  }
  :deep() .el-input__wrapper {
    background-color: #f7f8f9;
  }
  .regist_bottom {
    line-height: 34px;
  }
}
</style>
