<template>
    <div class="device">
        <deviceHeader />
        <div :span="24" class="device_connect">
            <span>{{ connectText }}</span>
        </div>
        <div :span="24" class="device_connect">
            <el-progress :percentage="percentage" />
        </div>
        <div class="device_connect">
            <el-select v-model="devicePort" style="width: 200px;">
                <el-option :disabled="!item.path" v-for="item in deviceSelect" :key="item.path" :value="item.path">{{
                    item.path }}</el-option>
            </el-select>
        </div>
        <div class="device_connect device_connect_btn">
            <div>
                <el-button :disabled="devicePort == '检测不到端口'" 
                :type="devicePort == '检测不到端口'?'':'primary'" @click="runCode">运行</el-button>
                <el-button :disabled="devicePort == '检测不到端口'" 
                :type="devicePort == '检测不到端口'?'':'primary'" @click="uploadCode">上传</el-button>
                <el-button v-if="deviceType == 'AI'" :disabled="devicePort == '检测不到端口'"
                :type="devicePort == '检测不到端口'?'':'primary'">初始化主屏界面</el-button>
            </div>
            <div>
                <el-button :disabled="devicePort == '检测不到端口'" type="primary" @click="reset">重启设备</el-button>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref, onMounted } from 'vue'
import Devices from '@/stores/device'
import Blocklys from '@/stores/blockly';
import deviceHeader from './deviceHeader.vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';
const connectText = ref('插件未启用')
const percentage = ref(0)
const deviceSelect = ref([
    {
        id: 1,
        path: '检测不到端口',
        // path: ""
    }
])
const Uploaders = Devices.useUploaders()
const serialData = Devices.usePrintData()
const devicePort = ref('检测不到端口')
const websocket = ref(null)
const deviceType = ref('')
const devices = Devices.useDeveics()
const socketPort = [9991, 9992, 9993, 9994, 9995, 9996, 9997, 9998, 9999, 10000]
const cancelToken = axios.CancelToken;
const source = cancelToken.source();
const code = Blocklys.useyPythonCodeStore()

onMounted(() => {
    wsconect()
    deviceType.value = localStorage.getItem('deviceType')
})
const wsconect = () => {
    let fail = 0
    for (let i = 0; i < socketPort.length; i++) {
        let ws = io('http://localhost:' + socketPort[i]);
        ws.on('connect', () => {
            websocket.value = ws;
            Uploaders.uploaders.status = true;
            getVersion()
            connectText.value = "模块未连接"

        });
        ws.on('connect_error', () => {
            ws = ws.close() ? null : null;
            ++fail === socketPort.length ? setTimeout(() => {
                console.log('重连中')
                Uploaders.uploaders.status = false;
                wsconect()
            }, 2000) : null;
        });
        ws.on('close', () => {
            Uploaders.uploaders.status = false;
            ++fail === socketPort.length ? setTimeout(() => {
                console.log('重连中')
                Uploaders.uploaders.status = false;
                wsconect()
            }, 2000) : null;
        });
    }
    // return
}
const runCode = async () => {
    if (!(websocket.value && websocket.value.id)) {
        return
    } else if (code.pythonCode == "") {
        ElMessage({
            message: '代码为空，运行失败',
            type: 'error',
        })
        return
    }
    percentage.value = 0
    let type = 1
    let data = {
        comname: devicePort.value,
        sid: websocket.value.id,
        code: code.pythonCode,
        type: true
    }
    connectText.value = "运行中..."
    if (type) {
        await axios({
            url: `${websocket.value.io.uri}/pythonupload`,
            method: 'post',
            data: data,
            onDownloadProgress: function (progressEvent) {
                // Do whatever you want with the progressEvent
                console.log(progressEvent)
                percentage.value = progressEvent.loaded / progressEvent.total * 100
                connectText.value = "运行成功"
            },

        })
    }

}
const uploadCode = async () => {
    console.log('上传代码', code.pythonCode)
    if (!(websocket.value && websocket.value.id)) {
        return
    } else if (code.pythonCode == "") {
        ElMessage({
            message: '上传代码为空，上传失败',
            type: 'error',
        })
        return
    }
    connectText.value = "上传中"
    let path = deviceType.value == "AI" ? "sd/user_latest_code.py" : "user_latest_code.py"
    let pythonuploadCode = `import os
os.remove("${path}")`
    // 上传之前先把文件删除
    let data = await axios({
        url: `${websocket.value.io.uri}/pythonupload`,
        method: 'post',
        data: { comname: devicePort.value, sid: websocket.value.id, code: pythonuploadCode, type: true },
    })
    console.log('data', data)
    // 上传
    if (data.data == "success") {
        await axios({
            url: `${websocket.value.io.uri}/pythonuploadfile`,
            method: 'post',
            data: { comname: devicePort.value, sid: websocket.value.id, code: code.pythonCode, name: path },
            onDownloadProgress: function (progressEvent) {
                // Do whatever you want with the progressEvent
                console.log(progressEvent)
                percentage.value = progressEvent.loaded / progressEvent.total * 100
                connectText.value = "上传成功"
            },
        })
    } else {
        connectText.value = "上传失败"
    }

}
const reset = () => {
    console.log('重置设备')
    if (!(websocket.value && websocket.value.id)) {
        return
    }
    let data = { comname: devicePort.value, sid: websocket.value.id }
    axios.post(`${websocket.value.io.uri}/pythonreset`, data).then(res => {
        console.log(res)
        if (res.data == "success") {
            ElMessage({
                message: '重启设备成功',
                type: 'success',
            })
        } else {
            ElMessage({
                message: '重启设备失败',
                type: 'warning',
            })
        }
    })
}
const getVersion = () => {
    websocket.value.emit('command', { cmd: 'list' });
    websocket.value.on('version', version => {
        console.log('version', version)
        Uploaders.uploaders.version = version
    })
    websocket.value.on('list', data => {
        let list = data.List.boards.concat(data.List.wifi)
        if (list.length > 0) {
            devicePort.value = list.length > 0 ? list[0].path : "检测不到端口"
            connectText.value = "直接将代码上传到电子模块中"
            deviceSelect.value = list
            getmcnty()
        } else {
            devicePort.value = "检测不到端口"
            connectText.value = "模块未连接"
            deviceSelect.value = [{ id: 1, path: "检测不到端口" }]
        }

    });
    websocket.value.on('repl', data => { replData(data) });
    websocket.value.on('disconnect', () => wsdisconnect());
}
const wsdisconnect = () => {
    console.log('断开连接')
    wsconect()
    connectText.value = "插件未启用"
    // websocket.value.emit('command', { cmd: 'close' })
    // websocket.value.close()
    // websocket.value = null
}
// 获取硬件类型
const getmcnty = () => {
    if (devicePort.value != "检测不到端口") {
        let data = { comname: devicePort.value, sid: websocket.value.id }
        axios.post(`${websocket.value.io.uri}/getmcnty`, data, {
            cancelToken: source.token
        }).then(res => {
            if (res.data) {
                deviceType.value = res.data
                localStorage.setItem('deviceType', res.data)
                devices.devices.type = res.data
            }
        })
    }
    else {
        setTimeout(() => {
            getmcnty()
        }, 2000)
    }

}
// 
const replData = (data) => {
    let code = data.code
    code = code.replace(/(^OK)|(>\r\n)/g, "");
    // code = code.replaceAngleBrackets()
    var _str = code.replace(/[\r\n]/g, function (str) {
        return "</div><div>";
    });
    let divs = document.createElement("div")
    divs.innerHTML = _str;
    for (let i = 0; i < divs.children.length; i++) {
        if (divs.children[i].innerText != "") {
            if (divs.children[i].innerText == ">>> ") {
                let _span = document.createElement("span")
                _span.innerHTML = "&nbsp"
                divs.children[i].append(_span)

            }
        } else {
            divs.removeChild(divs.children[i])
            i--;
        }
    }
    if(divs && divs.innerText != "" && document.getElementById("serialoutput")){
        document.getElementById("serialoutput").append(divs)
        // serialData.data = _ndiv
    }
}
</script>
<style scoped lang="scss">
.device {
    width: 100%;
    height: 100%;
    background-color: #f8f8f8;

    .device_connect {
        margin: 10px 10px;

    }

    .device_connect_btn {
        display: flex;
        justify-content: space-between;
    }
}
</style>