<!--
 * @Description: 
 * @Author: xiaofengzhou
 * @Email: 2946471396@qq.com
 * @Date: 2022-08-06 19:47:53
 * @LastEditTime: 2022-10-31 15:23:47
 * @LastEditors: xiaofengzhou
-->

<template>
    <div>
        <a-modal :maskClosable="false" v-model:visible="visible" @cancel="onCancle" @ok="onOk" centered width="1000px">
            <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 style="display: flex;">
                <div style="width:180px;margin-top: 30px;">
                    <a-steps progress-dot direction="vertical" :current="steps.current">
                        <a-step title="中间件安装"> </a-step>
                        <!-- <a-step title="sql初始化">
                        </a-step> -->
                        <a-step title="项目部署" />
                    </a-steps>
                </div>
                <div style="display: flex;flex-direction: column; ">
                    <div class="messageBox">
                        <div class="item" v-for="(item, index) in middlewareMessage">
                            <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 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 class="messageBox">
                        <div class="item" v-for="(item, index) in repoMessage">
                            <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>
                    <!-- <button @click="chuandi">传递数据</button> -->

                </div>
            </div>
        </a-modal>

    </div>
</template>

<script>
import { notification } from 'ant-design-vue'

import { realeaseProject } from '../../../../../packages/api/manage'
export default {
    data() {
        return {
            baseMessage: [],
            middlewareMessage: [],
            repoMessage: [],
            websocket: null,
            visible: false,
            sendFlag: true,
            isActive: true,
            projectId: '',
            current: 1,
            steps: {
                current: 0
            },
            lockReconnect: false,//是否真正建立连接
            timeout: 30000,//30秒一次心跳
            timeoutObj: null,//心跳心跳倒计时
            serverTimeoutObj: null,//心跳倒计时
            timeoutnum: null,//断开 重连倒计时
            count: 0,
            isDestoryed: false
        }
    },
    //生命周期 - 创建完成（访问当前this实例）
    created() {

    },
    //生命周期 - 挂载完成（访问DOM元素）
    mounted() {
    },
    methods: {
        chuandi(){
            // console.log("触发");
            this.$emit('getData')
        },

        // 取消
        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.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.middlewareMessage = []
            this.repoMessage = []
            this.current = 1
            this.steps.current = 0
            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) {
           
            // console.log(e);
            // 取消上次的状态
            this.resetHeart()
            let a = null
            try {
                a = JSON.parse(e.data).data
            } catch (err) {
                a = ''
            }
            if (a.includes("连接成功")) {
                this.count += 1
                if (this.count === 1) {

                    realeaseProject(this.projectId).then((res) => {
                    }).catch(err => {

                    })
                }

            }
            try {
                let mes = JSON.parse(e.data)
                let mess = JSON.parse(mes.data)
                // 收到错误或者code===3直接关闭
                if (mess.code === '3') {
                    notification.success({
                        message: '系统提示',
                        description: mess.message,
                        duration: 4
                    })
                    this.chuandi()

                    this.onCancle()
                    // 重新发起请求
                    // this.$emit("GenerateLogs")

                } else if (mess.code === '1') {
                    notification.error({
                        message: '系统提示',
                        description: mess.message,
                        duration: 4
                    })
                    this.chuandi()

                    this.onCancle()

                    // 重新发起请求
                    // this.$emit("GenerateLogs")
                }
                // if (this.baseMessage.length !== 0) {
                //     this.baseMessage[this.baseMessage.length - 1].isActive = false
                // }
                if (this.middlewareMessage.length !== 0) {
                    this.middlewareMessage[this.middlewareMessage.length - 1].isActive = false
                }
                if (this.repoMessage.length !== 0) {
                    this.repoMessage[this.repoMessage.length - 1].isActive = false
                }
                if (this.current === 1) {
                    this.middlewareMessage.push({
                        content: mess.message,
                        isActive: true,
                        code: mess.code
                    })
                } else if (2 === this.current) {
                    this.repoMessage.push({
                        content: mess.message,
                        isActive: true,
                        code: mess.code
                    })
                }
                // 失败或者成功都会进入下一阶段
                if (mess.code === '2' || mess.code === '1') {
                    // 进入第二阶段
                    this.current += 1
                }
                // 成功才会进入下一阶段
                if (mess.code === '2') {
                    this.steps.current += 1

                }
            } 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: {
        // baseMessageData() {
        //     return JSON.parse(JSON.stringify(this.baseMessage))
        // },
        // middlewareMessageData() {
        //     return JSON.parse(JSON.stringify(this.middlewareMessage))

        // },
        // repoMessageData() {
        //     return JSON.parse(JSON.stringify(this.repoMessage))

        // },
        userInfo() {
            return this.$store.getters.userInfo
        },
    },
    watch: {
        // baseMessageData: {
        //     handler(newVal, oldVal) {
        //         if (newVal.length > oldVal.length) {
        //             // 改变状态
        //             setTimeout(() => {
        //                 this.baseMessage[newVal.length - 1].isActive = false
        //             }, 2000)
        //         }
        //     },
        // },
        // middlewareMessageData: {
        //     handler(newVal, oldVal) {
        //         if (newVal.length > oldVal.length) {
        //             // 改变状态
        //             setTimeout(() => {
        //                 this.middlewareMessage[newVal.length - 1].isActive = false
        //             }, 2000)
        //         }
        //     },
        // },
        // repoMessageData: {
        //     handler(newVal, oldVal) {
        //         if (newVal.length > oldVal.length) {
        //             // 改变状态
        //             setTimeout(() => {
        //                 this.repoMessage[newVal.length - 1].isActive = false
        //             }, 2000)
        //         }
        //     },
        // }

    }



}

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

.messageBox {
    height: 180px;
    width: 800px;
    margin-top: 20px;
    border: none;
    background-color: #fafafa;
    overflow: scroll;
}

.messageBox .item {
    margin-top: 5px;
    margin-left: 5px;
    /* border: 1px solid red; */
    height: 20px;
    width: 470px;
    position: relative;
}

.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>