<template>
  <a-modal
    title="人脸图像采集"
    :visible="visible"
    :width="690"
    @cancel="closeDialog"
  >
    <img v-if="faceImg" :src="faceImgBase64" alt="人脸照片" />
    <div v-else style="text-align: center">
      <p style="text-align: center; color: black">
        当前采集用户: <b>{{ selectedUser.realname }}</b>
      </p>
      <video style="border-radius: 50%" ref="video" width="400" height="400" autoplay></video>
      <canvas ref="canvas" width="640" height="480" style="display: none"></canvas>
      <p style="text-align: center; color: indianred">请保持人脸在取景框内</p>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <a-button type="primary" @click="takePhoto">拍 照</a-button>
        <a-button type="primary" @click="handleUploadFace">确 定</a-button>
        <a-button @click="closeDialog">取 消</a-button>
      </div>
    </template>
  </a-modal>
</template>

<script>

import { postAction } from '@api/manage'

export default {
  props: {
    selectedUser: {
      type: Object,
      required: true,
    },
    visible: {
      type: Boolean,
      required: true,
    },
  },
  data() {
    return {
      faceImg: null,
      faceImgBase64: "",
      stream: null,
    };
  },
  watch: {
    visible(newVal) {
      if (newVal) {
        this.startCamera();
      } else {
        this.stopCamera();
      }
    },
  },
  methods: {
    startCamera() {
      navigator.mediaDevices
        .getUserMedia({ video: true })
        .then((stream) => {
          this.stream = stream;
          this.$refs.video.srcObject = stream;
        })
        .catch((err) => {
          console.error("Error accessing camera: ", err);
        });
    },
    stopCamera() {
      if (this.stream) {
        this.stream.getTracks().forEach((track) => track.stop());
      }
    },
    takePhoto() {
      const video = this.$refs.video;
      const canvas = this.$refs.canvas;
      const context = canvas.getContext("2d");

      context.drawImage(video, 0, 0, canvas.width, canvas.height);
      this.faceImgBase64 = canvas.toDataURL("image/png");

      const base64Data = this.faceImgBase64.replace(/^data:image\/png;base64,/, "");
      const byteCharacters = atob(base64Data);
      const byteNumbers = new Array(byteCharacters.length);

      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }

      const byteArray = new Uint8Array(byteNumbers);
      this.faceImg = new File([byteArray], this.selectedUser.username+"_face.jpg", { type: "image/jpeg" });

      this.stopCamera();
    },
    handleUploadFace() {
      const formData = new FormData();
      formData.append("file", this.faceImg);
      formData.append('id', this.selectedUser.id);

      postAction("sys/user/uploadFace",formData)
        .then((res) => {
          if (res.success) {
            this.$message.success("人脸信息上传成功");
            this.closeDialog();
          } else {
            this.$message.error(res.message);
          }
        })
        .catch((err) => {
          this.$message.error("上传失败");
          console.error(err);
        });
    },
    closeDialog() {
      this.$emit("update:visible", false);
      this.stopCamera();
      this.faceImg = null;
    },
  },
};
</script>

<style scoped>
.dialog-footer {
  text-align: right;
}
</style>