<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="loginAction()" />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          :type="hidePassword ? 'password' : 'text'"
          v-model="loginForm.password"
          placeholder="请输入密码"
          @keyup.enter="loginAction()">
          <template #suffix>
            <span :title="!hidePassword ? '隐藏密码' : '显示密码'">
              <bg-icon
                @click="hidePassword = !hidePassword"
                style="font-size: 16px; color: #a9b1c7; cursor: pointer"
                :icon="hidePassword ? '#bg-ic-eye' : '#bg-ic-eye-close'"></bg-icon>
            </span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item prop="yzm">
        <div class="msg-code">
          <el-input
            v-model="loginForm.yzm"
            placeholder="请输入验证码"
            @keyup.enter="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>
        <el-button class="register_btn" @click.prevent="$emit('register')" style="width: 100%">
          还没有账号？前往注册
          <bg-icon class="icon-arrow-right" 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";
import { useRouter } from "vue-router";

const router = useRouter();

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(`/v1/api/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(`/v1/api/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) => {});
};
const getUserInfo = () => {
  return axios.get(`/v1/api/user/getUserInfo`);
};
const getMenu = (search) => {
  return axios.get(`/v1/api/menu/user/tree?search=${search}`);
};
const getUser = () => {
  Promise.all([getUserInfo(), getMenu("1e99371c-187f-4966-94cf-32f116f42ce6")]).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();
      router.push("/forewarning/list");
    }
  });
};
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(`/v1/api/user/getCaptcha?width=138&height=36`).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, imgSrc, 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 {
      margin: 4px 0 0 16px;
      flex: 1;
    }

    > .bg-identify {
      margin-left: 6px;
      flex-shrink: 0;
    }
  }
  :deep() .el-input__wrapper {
    background-color: #f7f8f9;
  }
  .regist_bottom {
    line-height: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    :deep(.el-checkbox) {
      height: auto;
    }
  }
}
</style>
