<template>
  <div class="login-from" v-if="!isFace">
    <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>
        <div class="pwd_input">
          <input
            v-model="useInfo.password"
            class="ipt"
            :type="inputType"
            placeholder="请输入"
            @focus="stopKeyborad"
            @blur="stopKeyborad"
            @click="stopInput"
        />
        <van-icon @click="changeInputType(true)" v-if="inputType==='password'" name="eye-o" class="icon"/>
        <van-icon @click="changeInputType(false)" v-else name="closed-eye" class="icon" />
        </div>
      </div>
    </div>
    <div class="login-btn" @click="userLogin">登录</div>
    <div class="login-face" @click="changeFaceLogin">人脸登录</div>
  </div>
  <div class="face-login-box" v-else>
    <p>人脸识别登录</p>
    <div class="face-box">
      <video
        id="facevideo"
        autoplay
        muted
        style="
          width: 100%;
          height: 100%;
          border-radius: 50%;
          object-fit: cover;
          transform: rotateY(180deg);
        "></video>
      <br />
      <canvas id="facecanvas" width="400" height="400" style="position: absolute; top: 40px"></canvas>
      <canvas
        id="facecanvasF"
        ref="canvasface"
        width="600"
        height="600"
        style="display: none; position: absolute; top: 0"></canvas>
    </div>
    <!-- <p>人脸识别登录</p> -->
    <div class="tip">请保持您的正脸在取景框内...</div>
    <div @click="fnClose" class="back_btn">返回</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,useIdLogin} 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";
import { Icon } from 'vant';
import { getDeviceInfo } from "@/api/user";

import { doubleUserLogin } from "@/utils/login.js";
const userStore = useUserStore();

const router = useRouter();
const useInfo = reactive({
  username: "",
  password: "",
});
let verify_num = ref(1);
const getDeviceInfoMethods = async () => {
  let { data } = await getDeviceInfo();
  if (data.code == 200) {
    verify_num.value = data.data.need_two_face;
  }
};
getDeviceInfoMethods();
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;
  }
  let { data } = await getDeviceInfo();
  if (data.code == 200) {
    verify_num.value = data.data.need_two_face;
  }
  const res = await useLogin(useInfo);
  if (res.data.code == 200) {
    let { user_id, user_name } = res.data.data;
    notify(res.data.message, "success");

if (verify_num.value != 2) {
  notify("验证成功！", "success");
  sessionStorage.setItem(
    "userInfo",
    JSON.stringify({ ...res.data.data, userId: user_id, userName: user_name })
  );
  router.push("/home");
  return;
}
let isDouble = doubleUserLogin({
  ...res.data.data,
      userId: user_id,
      userName: user_name,
    });
    if (isDouble) {
      router.push("/home");
    } else {
      useInfo.userName = "";
      useInfo.userPwd = "";
    }
  } else {
    notify(res.data.desc, "danger");
  }
};
/**
 * @param 人脸识别按钮点击
 */
const video = ref();
const canvas = ref();
const canvasCtx = ref();
const canvasface = ref();
const canvasfaceCtx = ref();
const status = ref();
const stopeVideo = ref();
const timerInter = ref();
const timeout = ref();
let isFace = ref(false);
const changeFaceLogin = () => {
  status.value = true;
  isFace.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) {
            timeout.value = setTimeout(() => {
              getPhotoLocal();
            }, 1500);
            status.value = false;
          }
        });
      });
    });
  });
};

const getPhotoLocal = async () => {
  canvasfaceCtx.value.clearRect(0, 0, canvasface.value.width, canvasface.value.height);
  canvasfaceCtx.value.drawImage(video.value, 0, 0, 400, 400);
  let imgUrl = saveAsPNG(canvasface.value);
  let newImg = imgUrl.split('base64,')[1];
  try {
    {
      let { data } = await getDeviceInfo();
      if (data.status == 1) {
        verify_num.value = data.data.need_two_face;
      }
    }
    const res = await userFaceLogin({ raw: newImg });
    let data = res.data;
    console.log(data,'MMMMMMMMMM');
    if (data.code == 200) {
      let id = data.data.user_id;
      status.value = false;
      console.log('id=====', id);
      let res2 = await useIdLogin({ id });
      let status2 = res2.data.code;
      if (status2) {
        let { user_id, user_name } = res2.data.data;
        // notify(res2.data.desc, "success");

        if (verify_num.value != 2) {
          notify("验证成功！", "success");
          sessionStorage.setItem(
            "userInfo",
            JSON.stringify({
              ...res2.data.data,
              userId: user_id,
              userName: user_name,
            })
          );
          router.push("/home");
          return;
        }
        // userStore.faceLoginMethods(res.data);
        let isDouble = doubleUserLogin({
          ...res2.data.data,
          userId: user_id,
          userName: user_name,
        });
        if (isDouble) {
          router.push("/home");
          fnClose();
          return;
        }
      } else {
        notify("人脸认证失败", "danger");
      }
      fnClose();
    } else {
      notify(data.desc);
      status.value = true;
    }
  } catch (error) {
    status.value = true;
  }
};

const saveAsPNG = (c) => {
  return c.toDataURL('image/jpeg', 0.8);
};

const fnClose = () => {
  isFace.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();
});
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;
          }
        });
      });
    });
  });
};
let inputType = ref('password')
const changeInputType = (bol) => {
  inputType.value = bol ? 'text' : 'password'
}
</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-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 300px;
  //padding: 20px 31px 15px 32px;
  background: #ffffff;
  border-radius: 4px 4px 4px 4px;
  border: 1px solid #dcdcdc;
  box-sizing: border-box;
  p {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    font-size: 16px;
    color: #ffffff;
  }

  .face-box {
    margin: 0px auto 0px;
    width: 200px;
    height: 200px;
    box-shadow: 0px 4px 8px 1px rgba(97, 101, 188, 0.29);
    border-radius: 50%;
  }
  .tip {
    margin: 10px auto;
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: 400;
    font-size: 16px;
    color: #525964;
    text-align: center;
  }
  .back_btn {
    text-align: center;
    font-size: 16px;
    margin-bottom: 10px;
  }
}
.pwd_input{
  position: relative;
  .icon{
  font-size: 20px;
  position: absolute;
  right: 10px;
  top: 15px;
}
}
</style>
