<style lang="scss">
@import '@/styles/index.scss'; //导入样式

.upgradedlg {
    width: 100%;
    margin: auto;

    &__item {
        width: 100%;
        display: flex;

        &-left {
            flex: 1;
        }

        &-right {
            flex: none;
            -webkit-box-sizing: border-box;
            -moz-box-sizing: border-box;
            box-sizing: border-box;
            padding-left: 15px;
            text-align: right;
        }
    }
}
</style>

<template>
    <div class="upgradedlg">
        <el-form :model="dialogData.editData.data" :rules="dialogData.editData.rules" ref="editDataForm"
            label-width="100px" :size="controlSize">
            <el-form-item label="项目编号">
                <el-input v-model="calProjectId" disabled auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="基站编号">
                <el-input-number :precision="0" :step="1" :min="1000" disabled
                    v-model.trim="dialogData.editData.data.bts_id" auto-complete="off"
                    style="width:100%"></el-input-number>
            </el-form-item>
            <el-form-item label="设备类型">
                <el-select v-model="dialogData.editData.data.bts_type" disabled clearable placeholder="请选择"
                    style="width:100%">
                    <el-option v-for="(item, index) in mainData.btsTypeList" :key="index" :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="文件名称">
                <div class="upgradedlg__item">
                    <div class="upgradedlg__item-left">
                        <el-input v-model.trim="dialogData.editData.uploadFile.fileName" readonly
                            auto-complete="off"></el-input>
                    </div>
                    <div class="upgradedlg__item-right">
                        <el-upload class="uploader" ref="uploadControl" action="/pcapi/uploadfile/uploadUpgradeFile"
                            :data="uploadFileParam()" :auto-upload="false" accept="application/octet-stream"
                            :show-file-list="false" :on-change="hUploadChange" :before-upload="hBeforeUploadBin"
                            :on-success="hUploadBinSuccess">
                            <el-button slot="trigger" type="primary">选择文件</el-button>
                        </el-upload>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="升级进度">
                <div class="upgradedlg__item">
                    <div class="upgradedlg__item-left">
                        <el-progress :text-inside="true" :stroke-width="32"
                            :percentage="dialogData.editData.uploadFile.percentage"
                            style="border-radius:'0px'"></el-progress>
                    </div>
                    <div class="upgradedlg__item-right">
                        <el-button type="success" @click="hUploadUpgradeFile">远程升级</el-button>
                    </div>
                </div>
            </el-form-item>
        </el-form>
        <div style="padding-top: 10px;text-align:right">
            <el-button type="warning" @click="hClose">关闭窗口</el-button>
        </div>
    </div>
</template>

<script>
import { getBtsBaseParamById, resetBts } from "@/api/bparam"
import { getUpgradeStatus } from "@/api/uploadfile.js"
import { genBtsTypeList } from "../basestaticdata.js"
export default {
    name: 'upgradedlg',
    props: {
        isUpdate: {
            type: Boolean,
            require: true,
            default: false
        },
        id: {
            type: Number,
            require: true,
            default: 1
        },
        pid: {
            type: Number,
            require: true,
            default: 0
        }
    },
    data: function () {
        return {
            dialogData: {
                editData: {
                    data: {
                        id: 0,
                        project_id: 0,
                        bts_id: 0,
                        bts_type: 0,
                        center_freq: 0,
                        tx_power: 0,
                        rssi: -128,//接收电平
                    },
                    rules: {
                    },
                    uploadFile: {
                        fileName: "",
                        totalCounter: 0,
                        currentCounter: 0,
                        percentage: 0,
                        timerId: 0,
                    }
                }
            },
            mainData: {
                btsTypeList: genBtsTypeList(),
                btnEnable: true,
                center_freq: 0,
                bts_type: 0,
            },
            webSocket: {
                ws: null,//web socket实例
                data: {
                    flag: 1,
                    percent: 0
                }
            }

        }
    },
    watch: {
    },
    computed: {
        controlSize() {
            return this.$store.getters.controlSize
        },
        calProjectId() {
            let hexStr = this.dialogData.editData.data.project_id.toString(16).toUpperCase()
            return hexStr.padStart(8, '0')
        }
    },
    mounted() {
        this.$nextTick(function () {
            this.init()
        })
    },
    methods: {
        init() {
            if (this.isUpdate) {
                this.getBtsBaseParamById()
            }
        },
        hClose() {//关闭对话框
            this.$emit("close")
        },
        getData() {
            this.$emit("get")
        },
        getBtsBaseParamById() {
            let paramData = {}
            paramData.id = parseInt(this.id)
            getBtsBaseParamById(paramData).then((res) => {
                this.dialogData.editData.data = res.data
                this.mainData.bts_type = this.dialogData.editData.data.bts_type
            }).catch((err) => {
                console.log(err)
            })
        },
        uploadFileParam() {//文件上传时附带的参数
            let param = {}
            param['project_id'] = parseInt(this.dialogData.editData.data.project_id)
            param['bts_id'] = parseInt(this.dialogData.editData.data.bts_id)

            return param
        },
        hUploadChange(file, fileList) {
            this.dialogData.editData.uploadFile.fileName = file.name//保存文件名
        },
        hBeforeUploadBin(file) { //在上传文件之前，判断文件类型和文件大小是否满足要求
            const isAllowedFile = (file.type === 'application/octet-stream')//类型
            const isAllowedSize = file.size / 1024 < 1024 //1024k大小
            if (!isAllowedFile) {
                this.$message.error('只能上传bin文件')
            }
            if (!isAllowedSize) {
                this.$message.error('文件大小不能超过1024KB')
            }

            return isAllowedFile && isAllowedSize
        },
        hUploadBinSuccess(res, file, fileList) { //上传成功后的处理函数
            //let self = this
            if (res.code == 2000) {//返回成功
                this.connectWebSocket()
                // self.dialogData.editData.uploadFile.timerId = setInterval(
                //     self.getUpgradeStatus, 1200)
            } else {//返回失败
                this.$message({ message: '上传文件出错', type: 'error', duration: 3 * 1000 })
            }
        },
        hUploadUpgradeFile() {//上传文件
            //判断是否选择了文件
            const fileName = this.dialogData.editData.uploadFile.fileName
            if (typeof fileName !== "string" || fileName === "" || fileName.length === 0) {
                this.$alert('请首先选择升级文件！', '提示')
                return
            }

            //上传文件
            let uploadControl = this.$refs['uploadControl']
            this.$confirm('确定要进行远程升级吗', '提示', {
                cancelButtonText: '取消',
                confirmButtonText: '确定'
            }).then(() => {
                this.$nextTick(function () {
                    this.dialogData.editData.uploadFile.percentage = 0
                })

                uploadControl.submit()
            }).catch(() => {
            })
        },
        getUpgradeStatus() {//获得升级状态
            let self = this
            getUpgradeStatus().then((res) => {
                const respData = res.data
                if (respData.upgrade_flag === 2) {
                    self.$nextTick(function () {
                        self.dialogData.editData.uploadFile.percentage = respData.upgrade_percent
                    })

                    if (respData.upgrade_percent >= 100) {
                        clearInterval(self.dialogData.editData.uploadFile.timerId)
                        this.$message({ message: '远程升级成功', type: 'error', duration: 3 * 1000 })
                    }
                } else if (respData.upgrade_flag === 1) {
                    clearInterval(this.dialogData.editData.uploadFile.timerId)//清除定时器
                    this.$message({ message: '远程升级失败1', type: 'error', duration: 3 * 1000 })
                } else if (respData.upgrade_flag === 0) {
                    if (respData.upgrade_percent > 0) {
                        clearInterval(this.dialogData.editData.uploadFile.timerId)//清除定时器
                        this.$message({ message: '远程升级失败2', type: 'error', duration: 3 * 1000 })
                    }
                }
            }).catch(() => {
                clearInterval(this.dialogData.editData.uploadFile.timerId)//清除定时器
                this.$message({ message: '远程升级失败3', type: 'error', duration: 3 * 1000 })
            })
        },
        connectWebSocket() {
            this.webSocket.ws = new WebSocket('ws://127.0.0.1:8080/pcapi/uploadfile/createWebSocket')
            this.webSocket.ws.onopen = () => {
                console.log('WebSocket connection opened');
            }

            //监听服务器端发送的消息
            this.webSocket.ws.onmessage = (event) => {
                this.$nextTick(function () {
                    this.dialogData.editData.uploadFile.percentage = parseInt(event.data)
                })

                if (parseInt(event.data) >= 100) {
                    this.hResetBts()
                }
            }

            this.webSocket.ws.onclose = () => {
                console.log('WebSocket connection closed')
            }

            this.webSocket.ws.onerror = (error) => {
                console.error('WebSocket error:', error)
            }
        },
        async hResetBts() {
            const res = await this.$confirm("升级成功，设备重启后生效，要重启吗？", "提示", { type: "warning" }).catch(err => err)
            if (res != 'confirm') {
                return
            }

            let paramData = {}
            paramData['bts_id'] = this.dialogData.editData.data.bts_id
            paramData['reset_bts'] = 0

            resetBts(paramData).then(() => {
                this.$message({ message: '设备重启中，请稍后', type: 'success' })
            }).catch((err) => {
                this.$message({ message: err, type: 'error' })
            })
        }
    }
}

</script>
