Untitled

 avatar
unknown
plain_text
5 months ago
15 kB
4
Indexable
<template>
  <q-dialog v-model="visible" class="modalDialog" persistent>
    <q-card class="main_white">
      <q-toolbar>
        <q-toolbar-title
          ><span class="text-weight-bold"
            >ค้นหาด้วยรูปภาพ</span
          ></q-toolbar-title
        >
        <q-btn
          flat
          round
          dense
          icon="close"
          style="color: black"
          v-close-popup
          @click="closeModal()"
        />
      </q-toolbar>

      <div class="q-pa-md">
        <q-stepper v-model="step" ref="stepper" color="primary" animated>
          <q-step :name="1" title="แสกน QRCODE" icon="settings" :done="done1">
            <q-card-actions>
              <q-btn
                class="csd_btn"
                style="
                  width: 80px;
                  background-color: #4caf50;
                  color: white;
                  justify-content: center;
                "
                dense
                @click="refreshPage()"
                ><q-icon name="refresh" class="icon" />
              </q-btn>
            </q-card-actions>
            <q-card-section>
              <div style="padding: 5px 15px 5px">
                <div v-if="!isLoading">
                  <q-img :src="imageUrl" style="height: 100%; width: 100%" />
                </div>
              </div>
            </q-card-section>
          </q-step>

          <q-step
            :name="2"
            title="รูปหน้า/นิ้ว"
            icon="create_new_folder"
            :done="done2"
          >
            <div id="selected_type">
              <q-radio
                v-model="face_type"
                checked-icon="task_alt"
                unchecked-icon="panorama_fish_eye"
                val="face"
                label="รูปหน้า"
                style="color: black"
                color="cyan"
              />
              <q-radio
                v-model="face_type"
                checked-icon="task_alt"
                unchecked-icon="panorama_fish_eye"
                val="finger"
                label="รูปนิ้ว"
                color="cyan"
                style="color: black"
              />
            </div>
            <q-card-section>
              <div>
                <input type="file" ref="fileInput" @change="handleFileChange" />

                <q-img
                  v-if="imageBase64"
                  :src="imageBase64"
                  alt="Uploaded Image"
                />
              </div>
            </q-card-section>

            <q-card-actions>
              <q-btn
                class="csd_btn"
                @click="sendFinger(this.score, this.imageBase64)"
                >ประมวลผล</q-btn
              >
              <q-btn class="csd_btn" label="ปิด" @click="closeModal" />
              <q-btn class="csd_btn" label="Next" @click="showFaceRecModal" />
            </q-card-actions>
          </q-step>

          <q-step
            :name="3"
            title="แสดงรายชื่อ"
            icon="add_comment"
            :done="done3"
          >
            <DataCard
              title="รายการค่าความคล้าย"
              :initialData="crimeDoc.initialData"
              :tableColumns="crimeDoc.tableColumns"
              :payload="crimeDoc.payload"
            />
          </q-step>

          <!-- <template v-slot:navigation>
            <q-stepper-navigation>
              <q-btn
                @click="$refs.stepper.next()"
                color="primary"
                :label="step === 3 ? 'Finish' : 'Continue'"
              />
              <q-btn
                v-if="step > 1"
                flat
                color="primary"
                @click="$refs.stepper.previous()"
                label="Back"
                class="q-ml-sm"
              />
            </q-stepper-navigation>
          </template> -->
        </q-stepper>
      </div>
    </q-card>
  </q-dialog>

  <!-- <FaceListPerson
    :is-visible="showFaceRecList"
    @child-data="face_reg_personalid"
    @close-modal="closeModal"
  /> -->
</template>

<script>
// import { useQRCodeStore } from "@/stores/faceStore";
// import { Notify } from "quasar";
// import FaceListPerson from "../../components/modals/FaceListPerson.vue";
// import { getAccessToken } from "@/services/userApi";
import { LocalStorage } from "quasar";
import { validate, refresh } from "@/services/userApi";
import DataCard from "@/components/card/DataCard.vue";

import { ref } from "vue";
export default {
  name: "FaceRecModal",
  props: {
    isVisible: {
      type: Boolean,
      required: true,
    },
  },
  components: {
    DataCard,
  },
  setup(props, { emit }) {
    const personalid = ref([]);
    const isBrowseFile = ref(true);
    const tokenValid = ref(false);

    const closeModal = async () => {
      // console.log("closed");
      // clearInterval(intervalId.value);
      emit("close-modal");
    };

    return {
      tokenValid,
      personalid,
      isBrowseFile,
      closeModal,
    };
  },
  data() {
    return {
      visible: false,
      imageBase64: "",
      isButtonDisabled: true,
      showFaceRecList: false,

      step: ref(1),

      // value
      qrcode: "",
      tx_id: "",
      imageUrl: "",
      isLoading: false,
      intervalId: null,
      face_type: ref("face"),
      score: 50,

      crimeDoc: {
        initialData: [],
        tableColumns: [
          {
            name: "ประเภทเอกสาร",
            field: "doc_type",
            align: "left",
            sortable: true,
          },
          {
            name: "ชนิดเอกสาร",
            field: "doc_type_detail",
            align: "left",
            sortable: true,
          },
          {
            name: "รายละเอียด",
            field: "doc_detail",
            align: "left",
            sortable: true,
          },
        ],
        payload: {
          missing_id: this.MissingID,
        },
      },
    };
  },
  watch: {
    async isVisible(newValue) {
      this.visible = newValue;
      if (this.visible) {
        this.getQrcode();
      } else {
        clearInterval(this.intervalId);
      }
    },
  },
  mounted() {},
  methods: {
    refreshPage() {
      this.getQrcode();
    },
    async getQrcode() {
      try {
        this.imageUrl = null;
        this.isLoading = true;

        // ---- validate token -----
        const isValid = await validate();
        if (!isValid) {
          const isRefresh = await refresh();
          if (!isRefresh) {
            return (window.location = process.env.SSO_LOGIN);
          }
        }
        // ----- end of validate -----

        const accessToken = LocalStorage.getItem("accessToken", null);
        const response = await this.$api.get(`/lk/qrcode5`, {
          headers: {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            Authorization: `Bearer ${accessToken}`,
          },
        });
        if (response.status !== 200) {
          throw new Error("Network response was not ok");
        }
        this.step = 1;
        if (response.data.qrcode_external) {
          const data = response.data;
          this.qrcode = data.qrcode_external;
          this.tx_id = data.tx_id;

          // แปลงข้อมูล Base64 เป็น Blob
          var binaryData = atob(this.qrcode);
          var arrayBuffer = new ArrayBuffer(binaryData.length);
          var uint8Array = new Uint8Array(arrayBuffer);
          for (var i = 0; i < binaryData.length; i++) {
            uint8Array[i] = binaryData.charCodeAt(i);
          }
          var blob = new Blob([uint8Array], { type: "image/png" });
          // สร้าง URL ของ Blob
          this.imageUrl = URL.createObjectURL(blob);
          this.isLoading = false;

          await this.AccessToken(this.tx_id);
        } else if (response.data.status === "This user already has token") {
          console.log("first");
          this.step = 2;
        }
      } catch (error) {
        console.error(error);
        this.isLoading = false;
      }
    },
    async AccessToken(tx_id) {
      console.log("accesss", tx_id);
      try {
        // เช็คว่า intervalId มีค่าหรือไม่
        if (!this.intervalId) {
          // ถ้าไม่มี intervalId ให้เริ่ม setInterval
          this.intervalId = setInterval(async () => {
            const result = await this.AccessToken(this.tx_id);
            if (result === "done") {
              clearInterval(this.intervalId);
            }
          }, 3000);
        }
        // ----- validate token ------
        const isValid = await validate();
        if (!isValid) {
          const isRefresh = await refresh();
          if (!isRefresh) {
            return (window.location = process.env.SSO_LOGIN);
          }
        }
        // ----- end of validate ------

        const accessToken = LocalStorage.getItem("accessToken", null);
        const response = await this.$api.post(
          `/lk/btoken?tx_id=${tx_id}`,
          {},
          {
            headers: {
              "Content-Type": "application/json",
              "Access-Control-Allow-Origin": "*",
              Authorization: `Bearer ${accessToken}`,
            },
          }
        );
        const data = await response.data;

        if (data) {
          if (data.status === "success") {
            this.step = 2;
            clearInterval(this.intervalId);
            return false;
          } else if (data.status === "failure") {
            // console.log("data.error", data);
            this.$q.notify({
              position: "top",
              color: "red-5",
              textColor: "white",
              icon: "error",
              message: "คุณไม่มีสิทธิ์ใช้งาน",
              timeout: 30000,
            });
            // clearInterval(this.intervalId);
            return false;
          }
        }
      } catch (error) {
        console.error(error);
      }
    },

    showFaceRecModal() {
      this.showFaceRecList = true;
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        this.convertToBase64(file);
        this.isButtonDisabled = false;
      }
    },
    // convertToBase64(file) {
    //   // console.log("convert ", file);
    //   const reader = new FileReader();
    //   // reader.onload = (event) => {
    //   //   this.imageBase64 = event.target.result;
    //   // };
    //   // reader.readAsDataURL(file);
    //   // this.imageBase64 = this.resizeImage(this.imageBase64);
    //   // console.log("this.imageBase64", this.imageBase64);
    //   reader.onload = async (event) => {
    //     const base64Str = event.target.result;
    //     this.imageBase64 = await this.resizeImage(base64Str);
    //     // console.log("this.imageBase64", this.imageBase64);
    //   };
    //   reader.readAsDataURL(file);
    // },
    convertToBase64(file) {
      console.log("file", file);
      const reader = new FileReader();

      reader.onload = (e) => {
        this.imageBase64 = e.target.result;
        console.log("this.imageBase64 :>> ", this.imageBase64);
      };
      reader.readAsDataURL(file);
    },
    // Send Finger
    resizeImage(base64Str) {
      return new Promise((resolve) => {
        const img = new Image();
        img.onload = () => {
          const canvas = document.createElement("canvas");
          const MAX_WIDTH = 200;
          const MAX_HEIGHT = 200;
          let width = img.width;
          let height = img.height;

          if (width > height) {
            if (width > MAX_WIDTH) {
              height *= MAX_WIDTH / width;
              width = MAX_WIDTH;
            }
          } else {
            if (height > MAX_HEIGHT) {
              width *= MAX_HEIGHT / height;
              height = MAX_HEIGHT;
            }
          }
          canvas.width = width;
          canvas.height = height;
          const ctx = canvas.getContext("2d");
          ctx.drawImage(img, 0, 0, width, height);
          resolve(canvas.toDataURL());
        };
        img.src = base64Str;
      });
    },
    async sendFinger(score, imageBase64) {
      console.log("score", score);
      console.log("imageBase64", imageBase64);

      const image_data = imageBase64
        ?.replace("data:image/jpeg;base64,", "")
        ?.replace("data:image/png;base64,", "");
      console.log("image_data", image_data);
      try {
        const accessToken = LocalStorage.getItem("accessToken", null);
        const response = await fetch(`${process.env.SERVER_API}/bio/face2`, {
          method: "POST",
          body: JSON.stringify({
            score: score,
            image: image_data,
          }),
          headers: {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
            Authorization: `Bearer ${accessToken}`,
          },
        });
        console.log("dai pa ja", response);
        if (response) {
          this.step = 3;
          this.crimeDoc.tableColumns = this.transformResults(response);
          console.log("this.crimeDoc.tableColumns", this.crimeDoc.tableColumns);
          // this.step = 3;
          // clearInterval(this.intervalId);
          // if (data.token) {
          //   this.step = 2;
          //   clearInterval(this.intervalId);
          //   return false;
          // } else if (data.status === "failure") {
          //   console.log("data.error", data);
          //   this.$q.notify({
          //     position: "top",
          //     color: "red-5",
          //     textColor: "white",
          //     icon: "error",
          //     message: "คุณไม่มีสิทธิ์ใช้งาน",
          //     timeout: 30000,
          //   });
          //   return false;
          // }
        }
      } catch (error) {
        console.error(error);
      }
    },
    transformResults(response) {
      return response.result.map((hit) => {
        return {
          doc_type: hit.doc_type,
          doc_type_detail: hit.doc_type_detail,
          doc_detail: hit.doc_detail,
        };
      });
    },
    closeDialog() {
      this.visible = false;
    },
  },
};
</script>
<style>
.main_white {
  background-color: white;
  color: black;
}
#selected_type .q-radio__icon {
  color: black;
}
</style>
Editor is loading...
Leave a Comment