<template>
  <div class="login-from">
    <div class="item">
      <div class="title">用户名</div>
      <div>
        <input
            v-model="useInfo.username"
            class="ipt"
            @focus="stopKeyborad"
            @blur="stopKeyborad"
            @click="stopInput"
            placeholder="请输入"
        />
      </div>
    </div>
    <div class="item">
      <div class="title">密码</div>
      <div>
        <input
            v-model="useInfo.password"
            class="ipt"
            type="password"
            placeholder="请输入"
            @focus="stopKeyborad"
            @blur="stopKeyborad"
            @click="stopInput"
        />
      </div>
    </div>
    <div class="login-btn" @click="userLogin">登录</div>
    <div class="login-face" @click="faceLoginNew">人脸登录</div>
  </div>
  <div class="fooder-mark">
    <div class="content">COPYRIGHT © 2024 杭州研一智控科技有限公司 版权所有</div>
  </div>
  <div class="face-login" v-if="showFaceBox">
    <div class="face-login-box">
      <div class="face-login-content">
        <video id="facevideo" autoplay muted style="object-fit: cover"></video><br />
        <canvas id="facecanvas" style="position: absolute; top: 0"></canvas>
        <canvas
            id="facecanvasF"
            style="display: none; position: absolute; top: 0"
        ></canvas>
      </div>
      <div class="tip">人脸识别认证</div>
      <div class="tip-message">请保持正脸在取景框内...</div>
      <el-button class="face-login-button" @click="fnClose">取消</el-button>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, watch, watchEffect, nextTick, onBeforeUnmount } from "vue";
import {useLogin, userFaceLogin} from "@/api/login.js";
import { useRouter } from "vue-router";
import { message, notify } from "@/utils/message.js";
import axios from "axios";
import { useUserStore } from "@/store/user";
const userStore = useUserStore();

const router = useRouter();
const useInfo = reactive({
  username: "",
  password: "",
});

const isFocused = ref(false);

const stopInput = (e) => {
  if (isFocused.value) {
    e.target.setAttribute("readonly", true);
    setTimeout(() => {
      e.target.removeAttribute("readonly");
    }, 100);
  }
};

const stopKeyborad = (e) => {
  isFocused.value = true;
  e.target.setAttribute("readonly", true);
  setTimeout(() => {
    e.target.removeAttribute("readonly");
  }, 100);
};

const userLogin = async () => {
  if (useInfo.username == "" || useInfo.password == "") {
    notify("请输入用户名或密码");
    return;
  }
  const res = await useLogin(useInfo);
  if (res.data.code == 200) {
    let { user_id, user_name } = res.data.data;
    notify(res.data.desc, "success");
    let userInfo = {
      userId: user_id,
      userName: user_name,
    };
    sessionStorage.setItem("userInfo", JSON.stringify(userInfo));
    router.push("/home");
  } else {
    notify(res.data.desc, "danger");
  }
};
/**
 * @param 人脸识别按钮点击
 */
const video = ref();
const canvas = ref();
const canvasCtx = ref();
const canvasface = ref();
const canvasfaceCtx = ref();
const timeout = ref();
const timerInter = ref();
const status = ref(true);
const stopeVideo = ref();
const showFaceBox = ref(false);
const faceLoginNew = () => {
  status.value = true;
  showFaceBox.value = true;
  nextTick(() => {
    video.value = document.getElementById("facevideo");
    canvas.value = document.getElementById("facecanvas");
    canvasCtx.value = canvas.value.getContext("2d");
    canvasface.value = document.getElementById("facecanvasF");
    canvasfaceCtx.value = canvasface.value.getContext("2d");

    navigator.mediaDevices.getUserMedia({ video: true, audio: false }).then((stream) => {
      video.value.srcObject = stream;
      stopeVideo.value = stream.getTracks()[0];
      video.value.addEventListener("play", () => {
        timerInter.value = setInterval(async () => {
          if (status.value) {
            setTimeout(() => {
              getPhotoLocal();
              // if (import.meta.env.VITE_FACE_TYPE == 1) {
              //   getPhotoLocal();
              // } else {
              //   getPhotonew();
              // }
            }, 300);
            status.value = false;
          }
        });
      });
    });
  });
};

const getPhotonew = async () => {
  canvasfaceCtx.value.clearRect(0, 0, canvasface.value.width, canvasface.value.height);
  canvasfaceCtx.value.drawImage(video.value, 0, 0, 200, 200);
  let imgUrl = saveAsPNG(canvasface.value);
  let newImg = imgUrl.split("base64,")[1];

  let data = { raw: newImg };
  // let ip="http://"+window.location.hostname+':8081' // api的base_url

  axios({
    method: "post",
    url: ip + `/api/rms/web/sessions/face`,
    data,
    headers: {
      "Content-Type": "application/json",
    },
  })
      .then((res) => {
        if (res.data.code == 200) {
          console.log(res.data);
          // userStore.faceLoginMethods(res.data);
          sessionStorage.setItem("userInfo", JSON.stringify(res.data.data));
          router.push("/home");

          notify("欢迎登录", "success");
          fnClose();
        } else {
          status.value = true;
          notify(res.data.desc, "danger");
        }
      })
      .catch((err) => {
        status.value = true;
      });
};

const getPhotoLocal = () => {
  canvasfaceCtx.value.clearRect(0, 0, canvasface.value.width, canvasface.value.height);
  canvasfaceCtx.value.drawImage(video.value, 0, 0, 200, 200);
  let imgUrl = saveAsPNG(canvasface.value);
  let newImg = imgUrl.split("base64,")[1];

  userFaceLogin({ raw: newImg })
      .then((res) => {
        if (res.code == 200) {
          userStore.faceLoginMethods(res);
          message.success("欢迎登录");
          fnClose();
        } else {
          status.value = true;
        }
      })
      .catch((err) => {
        status.value = true;
      });
};

const fnClose = () => {
  showFaceBox.value = false;
  canvasCtx.value?.clearRect(0, 0, canvas.value.width, canvas.value.height);
  video.value?.pause();
  clearTimeout(timeout.value);
  clearInterval(timerInter.value);
  stopeVideo.value?.stop();
};
onBeforeUnmount(() => {
  fnClose();
});

function saveAsPNG(c) {
  return c.toDataURL("image/jpeg", 0.8);
}
</script>

<style lang="less" scoped>
@commonSize: 16px;
.login-from {
  position: absolute;
  top: 55%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 283px;
  padding: 20px 31px 15px 32px;
  background: #ffffff;
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #dcdcdc;

  .item {
    margin-bottom: 16px;

    .title {
      font-size: @commonSize;
      font-family: Source Han Sans CN, Source Han Sans CN;
      font-weight: 400;
      color: #666666;
      text-align: left;
      font-style: normal;
      text-transform: none;
      margin-bottom: 5px;
    }

    .ipt {
      width: 220px;
      height: 44px;
      background: #ffffff;
      border-radius: 2px 2px 2px 2px;
      font-size: @commonSize;
      border: 1px solid #dcdcdc;
    }
  }

  .login-btn {
    width: 220px;
    height: 48px;
    background: linear-gradient(180deg, #fe5e67 0%, #850006 100%);
    box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.4);
    border-radius: 4px 4px 4px 4px;
    font-size: @commonSize;
    color: #fff;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .login-face {
    background: white;
    color: red;
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: @commonSize;
  }
}

.fooder-mark {
  position: absolute;
  bottom: 0;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;

  box-shadow: 0px 4px 8px 1px rgba(0, 0, 0, 0.16);
  border-radius: 0px 0px 0px 0px;

  .content {
    width: 730px;
    height: 31px;
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-weight: 400;
    font-size: 12px;
    color: #989898;
    line-height: 36px;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }
}
.face-login {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;

  .face-login-box {
    width: 1200px;
    padding: 30px 0 55px;
    background-color: #fff;
    box-shadow: 0px 20px 40px 1px rgba(0, 0, 0, 0.16);
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #eeeeee;

    .face-login-content {
      width: 200px;
      height: 200px;
      margin: 0 auto;
      position: relative;
      border-radius: 50%;
      overflow: hidden;
      border: 8px solid #fff;
      box-shadow: 0px 8px 10px #e0e0e0;
      // top: 10px;
      #facevideo {
        position: absolute;
        top: 0;
        left: 0;
        width: 200px;
        height: 200px;
      }

      #facecanvas {
        position: absolute;
        top: 0;
        left: 0;
        width: 200px;
        height: 200px;
      }

      #facecanvasF {
        width: 200px;
        height: 200px;
      }
    }

    .tip {
      font-size: 16px;
      font-family: Source Han Sans CN-Regular, Source Han Sans CN;
      font-weight: 400;
      color: #000000;
      line-height: 39px;
      text-align: center;
      margin-top: 10px;
    }

    .tip-message {
      font-size: 12px;
      font-family: Source Han Sans CN-Regular, Source Han Sans CN;
      font-weight: 400;
      color: #c0c4cc;
      text-align: center;
      margin: 10px 0 10px 0;
    }

    .face-login-button {
      height: 40px;
      margin: 0 auto;
      display: block;
      border-radius: 20px;
      width: 100px;
      border: 1px solid #409eff;
      color: #409eff;
      font-size: 24px;
    }
  }
}
</style>
