<!--
 * @Author: your name
 * @Date: 2021-10-14 17:17:53
 * @LastEditTime: 2022-03-02 10:48:32
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \Foshan4A\src\App.vue
-->
<template>
  <div id="app">
    <!--全局休眠弹框-->
    <Dialog :flag="dialog" customClass="dormancyDialog" width="496px">
      <div class="dormancy">
        <div class="title">系统休眠，请输入密码解锁</div>
        <div class="content">
          <el-form @submit.native.prevent ref="form" :rules="rules" :model="form">
            <el-form-item prop="pwd">
              <el-input show-password placeholder="请输入密码" tabindex="1" @keyup.enter.native="onSubmit('form')" v-model="form.pwd"></el-input>
            </el-form-item>
            <div v-if="Number(errorNum) >= 2" class="flex-wrap">
              <el-form-item class="flex1" prop="identify">
                <el-input ref="identify" v-model.trim="form.identify" @keyup.enter.native="onSubmit('form')" placeholder="请输入验证码" name="identify" tabindex="1" />
              </el-form-item>
              <Identify @changeCode="changeCode" :identifyCode="form.CheckCode" :contentHeight="48" style="margin-left: 24px" />
            </div>
            <el-form-item>
              <el-button :loading="loading" style="line-height: normal" type="primary" class="button-public-shadow onSubmit" @click="onSubmit('form')">
                确定
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </Dialog>
    <!--路由出口-->
    <router-view />
  </div>
</template>

<script>
import Dialog from "@/layout/components/Dialog/index.vue";
import Identify from "./views/login/identify.vue";
import { mapGetters } from "vuex";
import { SsoLogin } from "@/api/apiHome";
import { GetSSOCheckCode } from "@/api/login";
import { getCodeToken } from "@/utils/auth";
export default {
  name: "App",
  components: {
    Dialog,
    Identify,
  },
  data () {
    return {
      arr: [], //鼠标移动screenX值数组
      arrLen: [], //一段时间后上报的screenX值数组
      timer: null, //定时器
      time: null, //定时器时间 1=1S
      desc: null, //固定的定时器时间/和time保持一致
      form: {
        //表单数据
        pwd: "",
        identify: "",
        CheckCode: "",
      },
      rules: {
        //表单验证
        pwd: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
      flag: false,
      loading: false,
    };
  },
  computed: {
    ...mapGetters([
      "dialog",
      "token",
      "name",
      "systemSet",
      "roles",
      "errorNum",
    ]),
  },
  watch: {
    "$store.state.user.token": {
      handler (val) {
        if (val) {
          this.handleInit();
        } else {
          this.clearAll();
        }
      },
      deep: true,
    },
    $route: {
      handler () {
        this.$store.dispatch("auth/changeAuthMsg", []);
        this.$store.dispatch("auth/changeAuthArrs", []);
        this.$store.dispatch("auth/changeAuthList", []);
        this.$store.dispatch("auth/changeAuthId", null);
      },
      deep: true,
    },
  },
  mounted () {
    const num = Number(this.errorNum);
    if (this.dialog && num >= 2) {
      // this.flag = true;
      this.getCheckCode();
    }
    this.beforeUnload();
  },
  beforeDestroy () {
    //结束定时器和释放timer
    this.clearAll();
  },
  methods: {
    // 初始化
    handleInit () {
      this.handleMove();
      if (!this.dialog) {
        this.handleTimer();
      }
    },
    /**
     * @description: 清除页面定时器和监听
     * @param {*}
     * @return {*}
     */
    clearAll () {
      clearInterval(this.timer);
      this.timer = null;
      this.time = null;
      this.desc = null;
      this.arr = [];
      this.arrLen = [];
      this.handleRmove();
      sessionStorage.setItem("token", "");
    },
    // 页面刷新 重新启用方法
    beforeUnload () {
      window.addEventListener("beforeunload", () => {
        if (this.token) {
          sessionStorage.setItem("token", this.token);
        }
      });
      let oldViews = sessionStorage.getItem("token") || "";
      if (oldViews) {
        this.handleInit();
      }
    },
    /**
     * @description: 定时器方法
     * @param {*}
     * @return {*}
     */
    handleTimer () {
      const obj =
        typeof this.systemSet === "string"
          ? JSON.parse(this.systemSet)
          : this.systemSet;
      const { LockMins } = obj;
      this.time = LockMins * 60;
      this.desc = LockMins * 60;
      this.timer = setInterval(() => {
        this.time--;
        if (this.time === 0) {
          const result = this.arrLen;
          const rut = this.arr;
          result.push(rut.length);
          if (result.length >= 2) {
            if (result[result.length - 2] === result[result.length - 1]) {
              // 相同时 结束倒计时
              this.$store.dispatch("app/toggleDialog", true);
              this.getCheckCode();
              this.clearAll();
            } else {
              this.time = this.desc;
            }
          } else {
            this.time = this.desc;
          }
        }
      }, 1000);
    },
    /**
     * @description: 监听鼠标移动方法/防抖
     * @param {*}
     * @return {*}
     */
    handleMove () {
      window.addEventListener(
        "mousemove",
        _.debounce(this.handleDebounce, 100)
      );
    },
    /**
     * @description: 移除鼠标移动监听
     * @param {*}
     * @return {*}
     */
    handleRmove () {
      window.removeEventListener("mousemove", () => {
        this.arr = [];
      });
    },
    /**
     * @description: 防抖方法
     * @param {*} e
     * @return {*}
     */
    handleDebounce (e) {
      const screenX = e.screenX;
      this.arr.push(screenX);
    },
    /**
     * @description: 提交
     * @param {*}
     * @return {*}
     */
    onSubmit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.ssoLogin();
        } else {
          return false;
        }
      });
    },
    //锁屏验证
    async ssoLogin () {
      try {
        this.loading = true;
        const obj = {
          LoginName: this.name,
          LoginPwd: this.form.pwd,
          token: getCodeToken(),
          userType: sessionStorage.getItem('UserType')
        };
        if (Number(this.errorNum) >= 2) {
          obj.CheckCode = this.form.identify;
        }
        const res = await SsoLogin(obj);
        if (res.code === 0) {
          this.$store.dispatch("app/toggleDialog", false);
          this.$store.dispatch("app/getErrorNum", 0);
          this.arr = [];
          this.arrLen = [];
          this.time = this.desc;
          this.form.pwd = "";
          this.form.identify = "";
          this.form.CheckCode = "";
          this.handleTimer();
          this.loading = false;
        } else {
          const num = Number(res.returnData);
          this.form.identify = '';
          this.$store.dispatch("app/getErrorNum", num);
          if (num >= 2) {
            this.getCheckCode();
          }
          if (num >= 5) {
            await this.$store.dispatch("user/logout");
            this.$store.dispatch("app/getErrorNum", 0);
            this.clearAll();
            this.$store.dispatch("app/toggleDialog", false);
            this.$router.push(`/login?redirect=${this.$route.fullPath}`);
            location.reload();
          }
          this.$message.error(res.message);
          this.loading = false;
        }
      } catch (error) {
        console.log(error);
        this.loading = false;
      }
    },
    //验证码重新获取
    changeCode () {
      this.getCheckCode();
    },
    //获取动态验证码
    async getCheckCode () {
      const res = await GetSSOCheckCode({
        token: getCodeToken()
      });
      if (res.code === 0) {
        this.form.CheckCode = res.returnData;
      } else {
        this.$message.error(res.message);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .dormancyDialog {
  .el-input__inner {
    height: 48px;
    line-height: 48px;
    background: #f5f7fa;
    border: 1px solid #ebeef5;
    border-radius: 6px;
  }
  .onSubmit {
    margin-top: 10px;
  }
}
</style>

