<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>
        <vxe-input
          class="ipt"
          v-model="useInfo.password"
          placeholder="请输入"
          :type="showPwd ? 'string' : 'password'"
          @suffix-click="changePwdType"
          @focus="stopKeyborad"
          @blur="stopKeyborad"
          @click="stopInput"></vxe-input>
      </div>
    </div>
    <div class="login-btn" @click="userLogin">登录</div>
    <div class="face-link-btn" @click="changeFaceLogin">人脸登录</div>
  </div>
  <div class="face-login-box" v-else>
    <p>人脸识别登录</p>
    <div class="face-box">
      <video
        id="facevideo"
        autoplay
        muted
        style="width: 272px; height: 272px; border-radius: 50%; object-fit: cover"></video>
      <br />
      <canvas id="facecanvas" width="400" height="400" style="position: absolute; top: 0"></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 class="sub-tip">请保持正脸在取景框内...</div>
    <div @click="fnClose" class="face-cancel-btn">返回</div>
  </div>
  <div class="fooder-mark">
    <div class="content">COPYRIGHT © 2025 杭州研一智控科技有限公司 版权所有</div>
  </div>

  <FaceDialog v-if="faceDialogVisible" oprType="'FACE_LOGIN'" />
</template>

<script setup>
import { reactive, ref, watch, watchEffect, onBeforeUnmount, nextTick, onMounted } from 'vue';
import { useLogin, useIdLogin } from '@/api/login.js';
import { userFaceLogin, bindFaceApi } from '@/api/face.api';
import { useRouter } from 'vue-router';
import { message, notify } from '@/utils/message.js';
import { doubleUserLogin } from '@/utils/login.js';
import { getDeviceInfo } from '@/api/user';
import FaceDialog from '../../components/FaceDialog/index.vue';

const router = useRouter();
const useInfo = ref({
  username: '',
  password: ''
});
let faceDialogVisible = ref(false);

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);
let showPwd = ref(false);
const changePwdType = () => {
  showPwd.value = !showPwd.value;
};
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.value.username == '' || useInfo.value.password == '') {
    notify('请输入用户名或密码');
    return;
  }
  const res = await useLogin(useInfo.value);
  console.log('login---res-----', res);
  if (res?.data?.code === 200) {
    let { user_id, user_name } = res.data.data || {};
    if (verify_num.value != 2) {
      notify('验证成功！', 'success');
      sessionStorage.setItem('userInfo', JSON.stringify(res.data.data));
      router.push('/home');
      return;
    }
    let isDouble = doubleUserLogin(res.data.data);
    if (isDouble) {
      sessionStorage.setItem('userInfo', JSON.stringify(res.data.data));
      router.push('/home');
    } else {
      useInfo.value = {
        userId: '',
        username: ''
      };
    }
  } else {
    notify(res.data.desc, 'danger');
  }
};
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(() => {
              if (import.meta.env.VITE_FACE_TYPE == 1) {
                getPhotoLocal();
              }
            }, 1500);
            status.value = false;
          }
        });
      });
    });
  });
};
let faceUrl = ref('');
faceUrl.value = 'http://' + window.location.hostname + ':8081';
//faceUrl.value="http://"+'192.168.1.72'+':8081'

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 {
    const res = await userFaceLogin({ raw: newImg }, faceUrl.value);
    let data = res.data;
    if (data.code == 200) {
      let id = data.data.user_id;
      status.value = false;
      let res2 = await useIdLogin({ id });
      let code2 = res2.data.code;
      if (code2) {
        let { user_id, user_name } = res2.data.data;
        notify(res2.data.desc, 'success');
        let userInfo = {
          userId: user_id,
          userName: user_name
        };
        if (verify_num.value != 2) {
          notify('验证成功！', 'success');
          sessionStorage.setItem('userInfo', JSON.stringify(res.data.data));
          router.push('/home');
          fnClose();
          return;
        }
        let isDouble = doubleUserLogin(res2.data.data);
        if (isDouble) {
          sessionStorage.setItem('userInfo', JSON.stringify(res.data.data));
          router.push('/home');
          fnClose();
          return;
        }
        //sessionStorage.setItem('userInfo', JSON.stringify(userInfo));
        // router.push('/home');
      } 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();
});
</script>

<style lang="less" scoped>
@commonSize: 40px;
.login-from {
  position: absolute;
  top: 52%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 510px;
  height: 530px;
  background: #ffffff;
  border-radius: 12px 12px 12px 12px;
  border: 1px solid #dcdcdc;
  .item {
    margin-bottom: 40px;
    .title {
      margin-bottom: 15px;
      font-size: 23px;
      color: #666666;
    }

    .ipt,
    ::v-deep .vxe-input--inner {
      width: 376px;
      height: 67px;
      padding-left: 0;
      background: #ffffff;
      box-shadow: inset 0px 3px 6px 1px rgba(0, 0, 0, 0.16);
      border-radius: 4px 4px 4px 4px;
      border: 1px solid #dcdcdc;
      font-size: 24px;
    }
    ::v-deep .vxe-input--inner::placeholder {
      color: rgb(117, 117, 117);
    }
  }

  .login-btn,
  .face-link-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 375px;
    height: 65px;
    background: linear-gradient(180deg, #cf4a4a 0%, #a21313 100%);
    box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.2);
    border-radius: 6px;
    font-size: 24px;
    color: #fff;
    cursor: pointer;
  }
  .face-link-btn {
    margin-top: 24px;
    background: linear-gradient(180deg, #1f89e7 0%, #1472c5 100%);
    box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.2);
  }
}

.fooder-mark {
  position: absolute;
  bottom: 30px;
  left: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  .content {
    width: 730px;
    height: 31px;
    font-family: Microsoft YaHei, Microsoft YaHei;
    font-size: 20px;
    color: #c3c3c3;
    text-align: center;
    font-style: normal;
    text-transform: none;
  }
}
.face-login-box {
  position: absolute;
  top: 52%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 800px;
  height: 560px;
  background: #ffffff;
  border-radius: 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: 36px;
    color: #ffffff;
  }

  .face-box {
    margin: 0px auto 0px;
    width: 272px;
    height: 272px;
    box-shadow: 0px 4px 8px 1px rgba(97, 101, 188, 0.29);
    border-radius: 50%;
  }
  .tip {
    margin-top: 24px;
    font-size: 24px;
    color: #000000;
    text-align: center;
  }
  .sub-tip {
    margin-top: 16px;
    font-size: 20px;
    color: #c0c4cc;
    text-align: center;
  }
  .face-cancel-btn {
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    width: 160px;
    height: 60px;
    margin-top: 28px;
    background: linear-gradient(180deg, #ffffff 0%, #e5e5e5 100%);
    box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.2);
    border-radius: 8px 8px 8px 8px;
    border: 1px solid #e5e5e5;
    font-size: 21px;
    color: #e24a4a;
  }
}
</style>
