<template>
    <div class="emotion">
        <el-switch v-model="value" size="large" inactive-text="打开摄像头" @change="change" />
        <el-row :gutter="20">
            <el-col :span="8">
                <p>网络摄像头：</p>
                <canvas ref="canvasEl" style="display: none;"></canvas>
                <video  ref="videoEl" style="width: 300px;height: 260px;display: block;" v-if="switchCamera"></video>
                <div v-else class="video_img">
                    请先打开摄像头
                </div>
            </el-col>
            <el-col :span="14" style="margin-left: 20px;">
                <el-col :span="24">
                    <el-button v-if="clickButton" style="margin-top: 10px;" type="primary"
                        @click="refresh">重新拍摄</el-button>
                    <el-button v-else style="margin-top: 10px;" type="primary" :disabled="!switchCamera"
                        @click="photoRecognition">拍照识别</el-button>
                </el-col>
                <el-col :span="24">
                    <p class="emotion_result_p">识别结果：</p>
                </el-col>
                <el-col :span="24" class="emotion_result_span">
                    {{ resultGesture || "未识别到结果" }}
                </el-col>
                <el-col :span="24" style>
                    <el-switch v-model="cloudValue" size="large" inactive-text="是否发送到云端" @change="rendCloud" />
                </el-col>
                <el-col>
                    <p>请选择一个 CocoCloud 项目，分析后的数据将会发送至该项目
                        <img src="../../assets/img/刷新.png" @click="refreshCloud" alt="">
                    </p>
                </el-col>
                <el-col>
                    <el-select name="select" id="" v-model="apiMode" @change="getApiKey">
                        <!-- <option value="" v-for="item in cloudList" v-model="item.url">{{ item.value }}</option> -->
                        <el-option v-for="item in cloudList" :key="item.url" :label="item.value" :value="item.url" />
                    </el-select>
                </el-col>
            </el-col>
        </el-row>

    </div>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import userInfo from '@/stores/modules/userInfo';
const value = ref(false);
const videoEl = ref(HTMLVideoElement); // 摄像头video
const switchCamera = ref(false);
const cloudList = ref();
const resultGesture = ref();
const cloudValue = ref(false);
const apiMode = ref("");
const clickButton = ref(false);
const canvasEl = ref(HTMLVideoElement);
const rendCloud = (val) => {
    if (val) {
        cloudValue.value = true;
    } else {
        cloudValue.value = false;
    }
}
const change = (val) => {
    if (val) {
        getCamera();
        switchCamera.value = true;
    } else {
        // videoEl.value.srcObject = null;
        switchCamera.value = false;
    }
}
onMounted(() => {
    console.log(userInfo().userInfo)
    if (userInfo().userInfo) {
        refreshCloud()
    }
})
// 打开摄像头
const getCamera = async () => {
    const navigator = window.navigator.mediaDevices;
    // 获取所有设备
    const devices = await navigator.enumerateDevices();

    if (devices) {
        const stream = await navigator.getUserMedia({
            audio: false,
            video: {
                width: 300, // 设置视频宽度
                height: 260, // 设置视频高度
                facingMode: "user", // 使用前置摄像头
            },
        });
        if (videoEl.value) {
            videoEl.value.srcObject = stream;
            videoEl.value.play();
        }
    }
}
const photoRecognition = () => {
    clickButton.value = true;
    // 检查视频元素和canvas 是否存在
    if (videoEl.value) {
        videoEl.value.style.display = 'none';
        canvasEl.value.width = 300;
        canvasEl.value.height = 260;
        // 获取画布上下文对象
        const ctx = canvasEl.value.getContext('2d');
        // 绘制图像到画布上
        ctx?.drawImage(videoEl.value, 0, 0, 300, 260);
        // 将画布内容转换为base64格式
        const imagebase64 = canvasEl.value.toDataURL('image/jpeg', 1).split(";");
        var contentType = imagebase64[0].split(":")[1];
        var realData = imagebase64[1].split(",")[1];
        const blob = b64toBlob(realData, contentType);
        // console.log()
        canvasEl.value.style.display = 'block';
        // https://ai-api.cocorobo.cn/gesture 手势识别接口
        // 将blob对象装换成file对象
        const file = new File([blob], 'image.jpg', { type: 'image/jpeg' });
        const formData = new FormData();
        formData.append('image', file);
        axios.post('https://ai-api.cocorobo.cn/gesture', formData).then(res => {
            const datas = res.data.data.result;
            if (datas.length > 0) {
                resultGesture.value = datas[0].classname
                if (cloudValue.value) {
                    sendCloud()
                }
            }
        })
    }
}
const b64toBlob = (b64Data, contentType, sliceSize = 512) => {
    contentType = contentType || '';
    sliceSize = sliceSize || 512;
    var byteCharacters = atob(b64Data);
    var byteArrays = [];
    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        var slice = byteCharacters.slice(offset, offset + sliceSize);
        var byteNumbers = new Array(slice.length);
        for (var i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }
    var blob = new Blob(byteArrays, { type: contentType });
    return blob;
}
const refreshCloud = () => {
    const apiKey = userInfo().userInfo.apiKey
    const event = window.location.host.indexOf("cocorobo.hk") > -1 ? `https://api.cocorobo.hk/iot/data/apikey/${apiKey.value}/event/` : `https://api.cocorobo.cn/iot/data/apikey/${apiKey}/event/`
    axios.get(event).then(res => {
        // console.log(res)
        if (res.data.length > 0) {
            let list = []
            res.data.map(x => {
                let obj = {
                    id: x.eventAPIKey,
                    value: x.name,
                    url: x.url
                }
                list.push(obj)
                return x
            })
            cloudList.value = list
        }
    })
}

const getApiKey = (e) => {
    apiMode.value = e
}
const sendCloud = () => {
    console.log(apiMode.value)
    let data = resultEmotion.value
    axios.post(apiMode.value, JSON.stringify(data)).then(res => {
        console.log(res)
    })
}

const refresh = () => {
    clickButton.value = false;
    videoEl.value.style.display = 'block';
    canvasEl.value.style.display = 'none';
}
</script>

<style scoped lang="scss">
.emotion {
    .video_img {
        width: 300px;
        height: 260px;
        background: #f0f0f0;
        border-radius: 6px;
        text-align: center;
        line-height: 260px;
        color: rgba(0, 0, 0, .4);
    }


    .emotion_result_p {
        font-weight: 200;
        margin: 10px 0;
        color: #000;
    }

    .emotion_result_span {
        border: 1px solid #f0f0f0;
        background-color: rgba(0, 0, 0, .02);
        font-weight: 600;
        color: rgba(0, 0, 0, .4);
        padding: 8px 5px;
        border-radius: 5px;
    }

    select {
        margin: 10px 0;
        width: 100%;
        padding: 8px;
        border-radius: 5px;
    }

    img {
        width: 25px;
        float: right;
        cursor: pointer;
    }
}
</style>