<template>
    <a-modal class="handleForm" :visible="visible" :title="title" :width="600" :bodyStyle="{ padding: '16px 24px' }" @ok="handleOk" @cancel="handleCancel" :destroyOnClose="true" :maskClosable="false">
        <video ref="local_video1" width="560" height="480" style="object-fit: fill" autoplay></video>
    </a-modal>
</template>
  <script setup>
import { reactive, ref, defineProps, onMounted, getCurrentInstance } from "vue";
import { message } from 'ant-design-vue';
const props = defineProps({
    visible: Boolean,
    title: String,
});
const emit = defineEmits(["handleSubmit", "changeCancel"]);
const local_video = ref("");
/**打开摄像头 */
const OnCamera = () => {
    navigator.getUserMedia(
        {
            audio: false,
            video: true,
        },
        function (stream) {
            local_video.value.srcObject = stream;
        },
        function (error) {
            console.log(error);
            message.warning('未找到摄像头设备，请检查设备是否插紧');
        }
    );
};
/**关闭摄像头 */
const OffCamera = () => {
    if (local_video.value.srcObject != null) {
        let stream = local_video.value.srcObject;
        stream.getTracks().forEach(function (track) {
            track.stop();
        });
        local_video.value.srcObject = null;
    }
};
const imgBase64 = ref("");
/**截图 */
const screenshot = () => {
    const canvas = document.createElement("canvas");
    const canvasCtx = canvas.getContext("2d");
    const ratio = window.devicePixelRatio || 1;
    canvasCtx.scale(ratio, ratio);
    canvas.width = local_video.value.offsetWidth * ratio;
    canvas.height = local_video.value.offsetHeight * ratio;
    canvasCtx.drawImage(local_video.value, 0, 0, canvas.width, canvas.height);
    imgBase64.value = canvas.toDataURL("image/png");
    OffCamera();
};

// 提交事件
const handleOk = async () => {
    screenshot();
    await emit("handleSubmit", imgBase64, handleCancel);
};
// 关闭弹框事件
const handleCancel = async () => {
    OffCamera();
    await emit("changeCancel", false);
};
onMounted(() => {
    const instance = getCurrentInstance();
    local_video.value = instance?.refs.local_video1;
    OnCamera();
});
</script>
    <style lang="less" scoped>
.handleForm {
    :deep(.ant-modal-content .ant-modal-close-x) {
        width: 49px;
        height: 49px;
        line-height: 49px;
    }
    :deep(.ant-modal-content .ant-modal-body) {
        padding-block: 16px;
    }
    .form {
        :deep(.ant-form-item-with-help) {
            margin-bottom: -16px;
        }
        :deep(.ant-input-number, .ant-picker) {
            width: 100%;
        }
        :deep(.ant-form-item) {
            margin-right: 0;
            margin-bottom: 10px;
        }
    }

    .dropPoint {
        display: flex;
        justify-content: space-between;
        align-items: center;
        > .ant-input {
            flex: 1;
            margin-right: 10px;
        }
    }
}
</style>
    