<!--
 * @Description: 生成日志
 * @Author: xiaofengzhou
 * @Email: 2946471396@qq.com
 * @Date: 2022-09-14 10:55:33
 * @LastEditTime: 2022-10-19 10:59:20
 * @LastEditors: xiaofengzhou
-->

<template>
    <div>
        <a-modal width="1000px" :maskClosable="false" v-model:visible="visible" @cancel="onCancle" @ok="onOk" centered>
            <div style="text-align: center;">
                <span style="font-size: 28px;vertical-align: middle;color: #284f84;"
                    class="iconfont icon-screen-code-line"></span>
                &nbsp;&nbsp;
                <span style="font-size: 18px;vertical-align: middle;color: #284f84;">生成日志</span>
            </div>
            <div>


                <div class="messageBox">
                    <div class="item" v-for="(item, index) in baseMessage">
                        <span>{{ item.content }}</span>
                        <div class="state loading" v-show="item.isActive">
                            <span class="iconfont icon-loading"></span>
                        </div>
                        <div class="state success" v-show="!item.isActive && item.code !== '1'">
                            <span class="iconfont icon-ok"></span>
                        </div>
                        <div class="state error" v-show="!item.isActive && item.code === '1'">
                            <span class="iconfont icon-Shapex"></span>
                        </div>
                    </div>
                </div>
            </div>
        </a-modal>

    </div>
</template>

<script>
import { notification } from 'ant-design-vue'
import { generateProject } from '../../../../../packages/api/manage'
export default {
    data() {
        return {
            baseMessage: [],
            websocket: null,
            visible: false,
            sendFlag: true,
            isActive: true,
            projectId: '',
            current: 1,
            lockReconnect: false,//是否真正建立连接
            timeout: 30000,//30秒一次心跳
            timeoutObj: null,//心跳心跳倒计时
            serverTimeoutObj: null,//心跳倒计时
            timeoutnum: null,//断开 重连倒计时
            count: 0,
            isDestoryed: false

        }
    },
    //生命周期 - 创建完成（访问当前this实例）
    created() {

    },
    //生命周期 - 挂载完成（访问DOM元素）
    mounted() {
    },
    methods: {

        // 取消
        onCancle() {

            // this.websocket = null
            this.isDestoryed = true
            // this.websocketonclose()
            this.timeoutnum && clearTimeout(this.timeoutnum)
            this.timeoutObj && clearTimeout(this.timeoutObj)
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
            this.websocket.close() // 关闭ws
            this.visible = false


        },
        // 确定
        onOk() {
            // this.websocket = null
            this.isDestoryed = true
            // this.websocketonclose()
            this.timeoutnum && clearTimeout(this.timeoutnum)
            this.timeoutObj && clearTimeout(this.timeoutObj)
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj)
            this.websocket.close() // 关闭ws
            this.visible = false

        },
        // 初始化
        init(record) {
            this.isDestoryed = false
            this.count = 0
            this.projectId = record.projectId
            this.baseMessage = []
            this.baseMessage.push({
                content: "已提交生成请求，请耐心等待",
                isActive: false,
                code: '2'
            })
            this.initWebSocket()
        },
        // 初始化ws
        initWebSocket() {

            let wsurl = ''
            const userId = this.userInfo.userId
            const system = JSON.parse(localStorage.getItem('pro__system')).value
            const token = JSON.parse(localStorage.getItem('xt__Access-Token')).value
            if (process.env.NODE_ENV === 'development') {
                if (system === 'http://169.169.171.148:8080') {
                    wsurl = `${"ws://" + window.location.host + "/websocket/"}${userId}?token=${token}`
                } else {
                    wsurl = `${"ws://169.169.171.141/api/websocket/"}${userId}?token=${token}`
                }
            } else {
                if (system === 'http://169.169.171.148:8080') {
                    wsurl = `${"ws://" + window.location.host + "/api/websocket/"}${userId}?token=${token}`
                } else {
                    wsurl = `${"ws://169.169.171.141/api/websocket/"}${userId}?token=${token}`
                }
            }



            this.websocket = new WebSocket(wsurl)
            this.websocket.onmessage = this.websocketonmessage
            this.websocket.onopen = this.websocketonopen
            this.websocket.onerror = this.websocketonerror
            this.websocket.onclose = this.websocketonclose
        },
        // 接收消息
        websocketonmessage(e) {
            // 收到新消息，将上一个动画取消
            try {
                let mes = JSON.parse(e.data)
                let mess = JSON.parse(mes.data)
                this.baseMessage[this.baseMessage.length - 1].isActive = false
                if (mess.code === '3') {
                    notification.success({
                        message: '系统提示',
                        description: mess.message,
                        duration: 4
                    })
                    this.onCancle()
                    // 重新发起请求
                    this.$emit("GenerateLogs")

                } else if (mess.code === '1') {
                    notification.error({
                        message: '系统提示',
                        description: mess.message,
                        duration: 4
                    })
                    this.onCancle()
                    // 重新发起请求
                    this.$emit("GenerateLogs")
                }
            } catch (error) {

            }
            this.resetHeart()
            let a = null
            try {
                a = JSON.parse(e.data).data
            } catch (err) {
                a = ''
            }
            // const a = JSON.parse(e.data).data
            if (a.includes("连接成功")) {
                this.count += 1
                if (this.count === 1) {
                    generateProject(this.projectId).then((res) => {
                        // if (res) {
                        //     notification.success({
                        //         message: '系统提示',
                        //         description: res.message,
                        //         duration: 4
                        //     })

                        // }
                    }).catch(err => {
                        // if (err) {
                        //     notification.error({
                        //         message: '系统提示',
                        //         description: "生成失败",
                        //         duration: 4
                        //     })
                        // }
                    })
                }
            }
            try {

                let mes = JSON.parse(e.data)
                let mess = JSON.parse(mes.data)
                this.baseMessage.push({
                    content: mess.message,
                    isActive: mess.message === '项目已生成' ? false : true,
                    code: mess.code
                })

            } catch (error) {

            }



        },
        // 发送数据
        websocketonopen() {


            this.startHeart()
        },
        // 失败
        websocketonerror() {


            this.reconnect()

        },
        // 关闭
        websocketonclose() {


            this.reconnect()
        },
        resetHeart() {
            let that = this
            clearTimeout(that.timeoutObj)
            clearTimeout(that.serverTimeoutObj)
            that.startHeart()
        },
        startHeart() {
            let self = this;
            self.timeoutObj && clearTimeout(self.timeoutObj)
            self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj)
            self.timeoutObj = setTimeout(function () {

                if (self.websocket.readyState === 1) {
                    // console.log("发送心跳", new Date().getTime());
                    self.websocket.send("ping")

                } else {
                    self.reconnect()
                }
                self.serverTimeoutObj = setTimeout(function () {
                    self.websocket.close()
                }, 3000)

            }, self.timeout);
        },
        reconnect() {
            let that = this;
            if (that.lockReconnect || that.isDestoryed) {
                return;
            };
            that.lockReconnect = true;
            //没连接上会一直重连，设置延迟避免请求过多
            that.timeoutnum && clearTimeout(that.timeoutnum);
            that.timeoutnum = setTimeout(function () {
                //新连接
                that.initWebSocket();
                that.lockReconnect = false;
            }, 5000);

        }
    },
    computed: {
        userInfo() {
            return this.$store.getters.userInfo
        },
    },

}

</script>
<style scoped lang="less">
/* @import url(); 引入css类 */
.ant-steps-item {
    height: 150px;
}

.messageBox {
    height: 500px;
    width: 800px;
    /* margin-top: 20px; */
    margin: 0 auto;
    border: none;
    background-color: #fafafa;
    overflow: scroll;
}

.messageBox .item {
    margin-top: 5px;
    margin-left: 5px;
    /* border: 1px solid red; */
    height: 40px;
    width: 800px;
    position: relative;
    & span{
        line-height: 40px;
        font-size: 20px;
    }
}

.messageBox .item .state {
    margin-left: 750px;
    position: absolute;
    left: 0;
    top: 0;
}

@keyframes animtran {
    from {
        transform: rotateZ(0deg);
    }

    to {
        transform: rotateZ(360deg);
    }
}

.state {
    height: 16px;
    width: 17px;
    line-height: 16px;
    text-align: center;
}

.loading {
    animation: animtran 5s linear infinite;
    -webkit-animation: animtran 5s linear infinite;
}

.success {
    color: green;
}

.error {
    color: red;
}
</style>