<template>
  <div class="icore-lg">
    <img
      style="width: 100%; height: 100%; position: absolute"
      src="../../../assets/img/icore-shown-all.png"
    />
    <section v-if="isJump === true">
      <div class="jumpText">正在为您跳转,请稍后...</div>
    </section>
    <section v-else>
      <div>
        <div class="frame-area">
          <div class="desc-area"></div>
          <div style="position: absolute; left: 30px; width: 346px; top: 105px">
            <el-form
              class="lg-form"
              :inline="false"
              ref="loginForm"
              :model="loginForm"
              :rules="loginFormRules"
            >
              <el-form-item style="margin-bottom: 20px" prop="loginName">
                <el-input v-model="loginForm.loginName" placeholder="用户名">
                  <i class="oa-login-ibg oa-login-ibg1" slot="prefix"></i>
                </el-input>
              </el-form-item>
              <el-form-item style="margin-bottom: 20px" prop="password">
                <el-input
                  v-model="loginForm.password"
                  :type="pwdShow ? 'text' : 'password'"
                  placeholder="密码"
                  @keyup.enter.native="loginSubmit('loginForm')"
                >
                  <i class="oa-login-ibg oa-login-ibg2" slot="prefix"></i>
                  <i
                    class="icore-icons icore-icons-see oa-login-ibg4"
                    :class="{ 'icore-icons-see-reverse': !pwdShow }"
                    @click="showPwd"
                    slot="suffix"
                  ></i>
                </el-input>
              </el-form-item>
              <el-form-item style="margin-bottom: 20px">
                <el-button
                  type="primary"
                  class="width100"
                  @click="loginSubmit('loginForm')"
                  :loading="loginBtnLoading"
                  >登&nbsp;录</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>
<script>
import { cookieUserId, cookieTime, cookieUserName } from "@/config/config.js";
import { setCookie, getCookie, formatDate } from "@/utils/util.js";
import store from "@/store/index.js";
import JsSHA from 'jssha'
const shaObj = new JsSHA('SHA-1', 'TEXT', { encoding: 'UTF8' })
export default {
  data() {
    return {
      store,
      loginBtnLoading: false,
      pwdShow: false,
      shaObj,
      loginForm: {
        loginName: "",
        password: "",
      },
      loginFormRules: {
        loginName: [
          { required: true, message: "请输入用户名", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      isJump: false,
    };
  },
  beforeCreate() {
    let token = getCookie("accessToken");
    if (token) {
      this.$router.push({ path: "default" });
    } else {
      window.top.localStorage.setItem("lockpwd", "");
    }
    window.top.localStorage.setItem("allPrivilege", "");
    window.top.localStorage.setItem("ownPrivilege", "");
  },
  mounted() {
    // 从cookie中获取上一次的登录用户名，赋值给用户名
    this.loginForm.loginName = getCookie("loginName")
      ? getCookie("loginName")
      : "";
  },
  methods: {
    loginSubmit(formName) {
      this.loginForm.loginName = this.loginForm.loginName.trim();
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 登陆中 登录按钮不可用
          this.loginBtnLoading = true;
          let form = JSON.parse(JSON.stringify(this.loginForm));
          form.app_code = 'web'; //终端code暂时写死
          this.shaObj.update(form.password)
          console.log(form.password)
          form.password = this.shaObj.getHash('HEX')
          console.log(form.password)
          this.store
            .dispatch("index/login/login", form)
            .then((res) => {
              if (res.code === "0") {
                console.log(res,"res")
                //  登录成功
                //  设置缓存信息
                setCookie("accessToken", res.data.accessToken, cookieTime, "/");
                setCookie(
                  "refreshToken",
                  res.data.refreshToken,
                  cookieTime,
                  "/"
                );
                setCookie("orgCode", res.data.user.orgCode);
                setCookie("userId", res.data.user.userId);
                setCookie("appId", res.data.appId);
                setCookie("loginId", res.data.user.userId); // 为配合bms取值添加
                setCookie("loginName", this.loginForm.loginName);
                let info = JSON.parse(JSON.stringify(res.data.user));
                for (let k in info) {
                  if (
                    k === "sysGroup" ||
                    k === "sysCompanys" ||
                    k === "sysRoles" || k === 'photo'
                  ) {
                    delete info[k];
                  }
                }
                setCookie("userInfo", JSON.stringify(info));
                // 判断用户集团公司情况跳转
                let userInfo = res.data.user;
                let sRedirect = this.$route.query.redirect;
                // 超级管理员
                if (userInfo.userCode === "admin") {
                  if (userInfo.sysCompanys) {
                    // 公司列表过多时cookie存放失败，存至localStorage
                    // setCookie('companys', JSON.stringify(userInfo.sysCompanys));
                    window.top.localStorage.setItem(
                      "sysGroup",
                      JSON.stringify(userInfo.sysGroup)
                    );
                    window.top.localStorage.setItem(
                      "companys",
                      JSON.stringify(userInfo.sysCompanys)
                    );
                    if (userInfo.hasOwnProperty("sysCompanys")) {
                      window.top.localStorage.setItem(
                        "companyId",
                        userInfo.sysCompanys[0].id
                      );
                    }
                  }
                  if (sRedirect) {
                    this.$router.push({ name: sRedirect });
                  } else {
                    this.$router.push({ name: "default" }).catch(() => {});
                  }
                  // 普通用户
                } else {
                  if (
                    userInfo.hasOwnProperty("sysGroup") &&
                    userInfo.sysGroup !== "" &&
                    userInfo.sysGroup !== null &&
                    JSON.stringify(userInfo.sysGroup) !== "{}" &&
                    JSON.stringify(userInfo.sysGroup) !== "[]"
                  ) {
                    window.top.localStorage.setItem(
                      "sysGroup",
                      JSON.stringify(userInfo.sysGroup)
                    );
                    if (userInfo.hasOwnProperty("sysCompanys")) {
                      window.top.localStorage.setItem(
                        "companys",
                        JSON.stringify(userInfo.sysCompanys)
                      );
                      window.top.localStorage.setItem(
                        "companyId",
                        userInfo.sysCompanys[0].id
                      );
                      if (userInfo.sysCompanys.length > 1) {
                        // 跳转选择集团公司页面
                        this.$router.push({ name: "selectCompany" });
                      } else {
                        if (sRedirect) {
                          this.$router.push({ name: sRedirect });
                        } else {
                          this.$router
                            .push({ name: "default" })
                            .catch(() => {});
                        }
                      }
                    } else {
                      this.$message.error(
                        "后台返回数据缺少company信息，请联系开发人员！"
                      );
                    }
                  } else {
                    this.$message.error(
                      "必须隶属一个集团！请先联系管理员添加集团信息!"
                    );
                  }
                }
              } else {
                //  登录失败
                // 提示
                this.$message({
                  message: res.message,
                  type: "error",
                });
              }
              this.loginBtnLoading = false;
            })
            .catch(() => {
              this.loginBtnLoading = false;
            });
        } else {
          return false;
        }
      });
    },
    showPwd() {
      this.pwdShow = !this.pwdShow;
    },
  },
};
</script>

<style lang="less" scoped>
.jumpText {
  position: absolute;
  width: 100%;
  text-align: center;
  line-height: 500px;
  color: white;
  font-size: 24px;
}
</style>
