<template>
  <div class="login-by-account">
    <el-form
      ref="loginForm"
      label-position="top"
      :model="loginForm"
      :rules="steploginFormRules"
    >
      <el-form-item label="账号" prop="userid">
        <el-input
          v-model="loginForm.userid"
          autofocus="autofocus"
          placeholder="请输入账号"
          @keyup.enter.native="loginAction()"
        />
      </el-form-item>
      <el-form-item label="密码" 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 label="验证码" prop="yzm">
        <div class="msg-code">
          <el-input
            v-model="loginForm.yzm"
            placeholder="请输入验证码"
            @keyup.enter.native="loginAction()"
          />
          <img
            class="yzm_img"
            title="看不清？换一张"
            :src="imgSrc"
            @click="getImg()"
          />
        </div>
      </el-form-item>
      <el-form-item>
        <el-checkbox v-model="rememberPassword">记住密码</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="loginAction()" style="width: 100%">
          登 录
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import CryptoJS from "crypto-js";
import { getCookie, clearCookie, setCookie } from "@/services/cookie.js";
import menu from "../router/function";
import { generateRoutes } from "../router/index";

export default {
  name: "LoginByAccount", // 账号密码登录
  data() {
    return {
      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,
    };
  },
  methods: {
    loginAction() {
      if (this.rememberPassword) {
        let userinfo = window.btoa(
          encodeURI(`${this.loginForm.userid},${this.loginForm.password}`)
        );
        setCookie("userinfo", userinfo);
      } else {
        clearCookie("userinfo");
      }

      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.$axios
            .get(
              `/apaas/system/v5/user/verifyCaptcha?id=${this.imgId}&value=${this.loginForm.yzm}`
            )
            .then((res) => {
              if (res.data.code == 200) {
                this.login();
              } else {
                this.$message.error(res.data.data);
              }
            });
        }
      });
    },
    login() {
      this.$axios
        .post(`/apaas/system/v5/user/login`, {
          system_account: this.loginForm.userid,
          password: CryptoJS.AES.encrypt(
            this.loginForm.password,
            "swuE9cmCZQwrkYRV"
          ).toString(),
        })
        .then(({ data }) => {
          if (data.code == 200) {
            this.getUser();
          } else {
            this.getImg(true);
            this.$message({
              message: data.data,
              type: "error",
            });
          }
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getUserInfo() {
      return this.$axios.get(`/apaas/system/v5/user/getUserInfo`);
    },
    getMenu(search) {
      return this.$axios.get(`/apaas/system/v5/menu/user/tree?search=${search}`);
    },
    getUser() {
      Promise.all([this.getUserInfo(), this.getMenu('apaas')]).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 || [];
          this.$store.commit("setUserInfo", res[0].data.data);
          // if (res.data.data.userType == 1) {
          //超管
          this.$store.commit("setMenu", data);

          menu.menuToRouter(data);

          this.$store.commit("setRoute", data);

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

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

      this.rememberPassword = true;
    } else {
      this.checked = false;
    }
  },
};
</script>

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

  > .bg-identify {
    margin-left: 6px;
    flex-shrink: 0;
  }
}
</style>
