<template>
    <div>
        <div class="content">
            <dataBreadcrumb :breads="breads"></dataBreadcrumb>
            <div>中国标准时间：{{ currentTime }}</div>
            <div class="hal">
                <h2 style="text-align: center">{{ projectName }}项目开标大厅</h2>
                <div class="time-message flex-between">
                    <div class="flex">
                        <p>截标倒计时：</p>
                        <timeDown :remain-time="remaintime" @countDowmEnd="remaintimeEnd"></timeDown>
                    </div>
                    <div class="flex" v-show="openStatus == 2">
                        <p>解密倒计时：</p>
                        <timeDown :remain-time="decodeTime" @countDowmEnd="decodeTimeEnd"></timeDown>
                    </div>
                    <div class="flex" v-show="openStatus == 2">
                        <p>签名倒计时：</p>
                        <timeDown :remain-time="signatureTime" @countDowmEnd="signatureTimeEnd"></timeDown>
                    </div>
                </div>
                <div class="flex">
                    <div class="hal-left">
                        <div>
                            <h1>签到 {{ !leftmessage.signIn ? '否' : '是' }}</h1>
                            <h1>解密 {{ !leftmessage.decode ? '否' : '是' }}</h1>
                            <h1>签名 {{ !leftmessage.signature ? '否' : '是' }}</h1>
                        </div>
                    </div>
                    <div class="hal-center" v-chat-scroll>
                        <ul>
                            <li v-for="(item, index) in halList" :key="index" class="flex-item">
                                <div>{{ item.time }}</div>
                                <div>{{ item.role }}</div>
                                <div>{{ item.name }}</div>
                                <div>{{ item.behavior }}</div>
                            </li>
                        </ul>
                    </div>
                    <div class="hal-right">
                        <el-button @click="dialogFormVisible = true" style="margin-left: 10px">开标规则说明</el-button>
                        <el-button @click="isdialogue">在线对话<i class="el-icon-chat-dot-round"></i></el-button>
                        <el-button
                            :disabled="!isDecode"
                            v-show="openStatus == 2 && !leftmessage.decode"
                            @click="changeDecode"
                            type="primary"
                            >解密投标文件</el-button
                        >
                    </div>
                    <!-- 在线对话 -->
                    <div class="dialogue" style="margin-top: 30px" v-show="dialogue">
                        <JwChat :taleList="dialogueList" scrollType="scroll" @enter="bindEnter" v-model="content" :toolConfig="tool">
                            <el-button slot="tools" style="float: right" class="abs" @click="dialogue = false">关闭聊天框</el-button>
                        </JwChat>
                    </div>
                    <!-- <div class="dialogue" style="margin-top: 30px;" v-show="dialogue">
						<ul class="dialogueList"  v-chat-scroll>
							<li v-for="(item,index) in dialogueList" :key="index" :class="myId==item.userId?'flex-left':'flex-right'">
								<div>
									<div class="flex-item">
										<div v-if="myId==item.userId">我</div>
										<div v-else>{{item.name}}</div>
										<div>({{item.time}})</div>
									</div>
									<div>{{item.chatContent}}</div>
								</div>
							</li>
						</ul>
						<el-input placeholder="请输入内容" v-model="content" clearable @keyup.enter.native="send" maxlength="30">
						</el-input>
					</div> -->
                </div>
                <div class="flex-center buttons">
                    <div>
                        <el-button icon="el-icon-refresh" @click="refrsh">刷新</el-button>
                        <el-button @click="openInfo" :disabled="!issueTable">查看开标一览表</el-button>
                        <el-button @click="back">退出大厅<i class="el-icon-right"></i></el-button>
                    </div>
                </div>
            </div>
        </div>
        <!-- 开标说明 -->
        <el-dialog :visible.sync="dialogFormVisible" title="开标规则说明">
            <div class="explain">
                <h1>开标说明</h1>
                <div>1、网上开标共有解密、签名两个环节，投标人根据开标大厅中间滚动提示进行相应操作。</div>
<div>2、截标前当天大厅开放，已上传投标文件的投标人可在解密倒计时结東前进入开标大厅。</div>
<div>3、截标后主持人宣布开标，所有投标人进行解密操作，解密时间共计30分钟投标人须在解密倒计时结束前
完成解密。解密倒计时结東后，因投标人原因造成投标文件未解密的根据《电子招标投标办法其投标文件》视
为撤销。</div>
<div>4、解密倒计时结東或所有投标文件均已解密，投标人可查询所有投标人的开标情况并进行签名，签名时间
共计10分钟。</div>
<div>5.、所有投标人完成签名操作或签名倒计时结束后，项目经理开标结束，投标人可离开开标大厅。开标过程
中，投标人可点击开标大厅右上角在线聊天与主持人沟通。开标结束后视为开标过程无异议。</div>
            </div>
            <div class="flex-center">
                <el-button type="primary" @click="dialogFormVisible = false">关闭</el-button>
            </div>
        </el-dialog>
        <!-- 开标一览表 -->
        <el-dialog :visible.sync="isopenInfo" title="开标一览表">
            <nopageTable :tableData="tableData" :columns="nopagecolumns" :margin-top="0" :margin-bottom="0"> </nopageTable>
            <div slot="footer" class="dialog-footer">
                <el-button @click="isopenInfo = false">关闭 </el-button>
                <el-button
                    :disabled="!isSignature"
                    v-show="openStatus == 2 && !leftmessage.signature"
                    @click="changeSignature"
                    type="primary"
                    >签名</el-button
                >
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { signdetail } from '@api/purchaser/bid';
import { openUrl } from '@utils/common';
import { openBidsign, opentimeInfo, openInfolist, decode, signature } from '@api/supply/bid';
import { getTime } from '@utils/time';
import nopageTable from '@components/nopageTable.vue';
import dataBreadcrumb from '@components/dataBreadcrumb.vue';
import timeDown from '@components/timeDown.vue';
import dataTable from '@components/dataTable.vue';
export default {
    components: {
        dataBreadcrumb,
        timeDown,
        dataTable,
        nopageTable
    },
    data() {
        return {
            tool: {
                show: [''],
                callback: this.toolEvent,
                showEmoji: false
            },
            issueTable: '',
            openStatus: '',
            isSignature: false,
            isDecode: false,
            dialogue: false,
            isopenInfo: false,
            remaintime: '',
            decodeTime: '',
            signatureTime: '',
            projectName: '',
            pageObj: {
                size: 10,
                total: 1000,
                currentPage: 1,
                func: (currentPage) => {
                    this.pageTurning(currentPage);
                }
            },
            dialogFormVisible: false,
            tableData: [],
            columns: [
                {
                    label: '中标供应商',
                    prop: 'name'
                },
                {
                    label: '中标项目',
                    prop: 'project'
                },
                {
                    label: '中标时间',
                    prop: 'data',
                    sortable: true
                },
                {
                    label: '备注',
                    prop: 'remark'
                },
                {
                    slot: 'operate'
                }
            ], //
            nopagecolumns: [
                {
                    label: '投标公司',
                    prop: 'companyName'
                },
                {
                    label: '投标报价(元)',
                    prop: 'price'
                },
                {
                    label: '是否签名',
                    prop: 'isSign'
                }
            ], //
            isOpenbid: false,
            buttonWords: '立即开标',
            openbidButton: false,
            halList: [
                {
                    time: '17:56:56',
                    role: '招标人',
                    person: '谢天',
                    behavior: '进入开标大厅'
                },
                {
                    time: '17:56:56',
                    role: '投标人',
                    person: '测试1',
                    behavior: '确认可开标'
                }
            ],
            minutes: '6',
            seconds: '60',
            currentTime: '',
            breads: ['招标管理', '招标项目管理', '工作台'],
            leftmessage: '',
            websocket: '',
            dialogueList: [],
            halList: [],
            content: '',
            myId: ''
        };
    },
    mounted() {
        this.add();
    },
    created() {
        // 中国标准时间
        let currentTime = getTime();
        this.currentTime = currentTime;
        this.timer1 = setInterval(() => {
            let currentTime = getTime();
            this.currentTime = currentTime;
        }, 1000);
        this.projectName = localStorage.getItem('projectName');
        this.getsigndetail();
        this.openBidsign();
        this.createWebSocket();
        this.myId = JSON.parse(localStorage.getItem('userInfo')).userId;
        // 长轮训获取
        this.timer = setInterval(() => {
            this.getsigndetail();
        }, 5000);
    },
    methods: {
        openInfo() {
            this.isopenInfo = true;
            this.getopenInfo();
        },
        refrsh() {
            history.go(0);
        },
        // 解密
        async changeDecode() {
            let projectId = localStorage.getItem('projectId');
            try {
                const { msg, code } = await decode(projectId);
                if (code == 200) {
                    this.$message.success(msg);
                    this.openBidsign();
                } else {
                    this.$message.error(msg);
                }
            } catch (e) {
                console.log(e);
            }
        },
        // 签名
        async changeSignature() {
            let projectId = localStorage.getItem('projectId');
            try {
                const { msg, code } = await signature(projectId);
                if (code == 200) {
                    this.$message.success(msg);
                    this.openBidsign();
                } else {
                    this.$message.error(msg);
                }
            } catch (e) {
                console.log(e);
            }
        },
        isdialogue() {
            this.dialogue = !this.dialogue;
        },
        // websocket
        createWebSocket() {
				let token = localStorage.getItem("token")
				let projectId = localStorage.getItem("projectId")
				this.websocket = new WebSocket(`ws:${openUrl}/webSocket/${projectId}/${token}`)
				// this.websocket = new WebSocket('ws://192.168.3.35:8085/webSocket/' + projectId + "/" + token)
				// this.websocket = new WebSocket('ws://60.205.251.80:8085/webSocket/' + projectId +"/"+token )
				// 连接成功时
				this.websocket.onopen = () => {}
				this.websocket.onmessage = event => {
					// 后端发送的消息在event.data中
					let data = JSON.parse(event.data);
					console.log(data)
					if (data.type == 1) {
							if(data.userId==this.myId){
							  data.mine=true
							}else{
								data.mine=false
							}
							const msgObj = {
								"date":data.time ,
								"text": {
									"text": data.chatContent
								},
								"mine": data.mine,
								"name": data.name,
								"img": "http://hsz1997.oss-cn-beijing.aliyuncs.com/img/1603292025286_67c099c6tou.jpg"
							}
						this.dialogueList.push(msgObj)
					} else {
						this.halList.push(data)
					}
				}
				this.websocket.onclose = function() {
					console.log('关闭了')
				}
				// 路由跳转时结束websocket链接
				// this.$router.afterEach(function() {
				// 	this.websocket.close()
				// })
				// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常
				window.onbeforeunload = function() {
				     console.log("窗口关闭")
					this.websocket.close()
				}
			},
        bindEnter() {
            const content = this.content;
            if (!content) return;
            this.websocket.send(content);
        },
        back() {
            this.$router.go(-1);
        },
        // 截标时间到了
        remaintimeEnd(val) {},
        // 解密时间到了
        decodeTimeEnd(val) {
            this.isDecode = val;
        },
        // 签名时间到了
        signatureTimeEnd(val) {
            this.isSignature = val;
        },
        // 计算分秒倒计时
        add: function () {
            var _this = this;
            var time = window.setInterval(function () {
                if (_this.seconds === 0 && _this.minutes !== 0) {
                    _this.seconds = 59;
                    _this.minutes -= 1;
                } else if (_this.minutes === 0 && _this.seconds === 0) {
                    _this.seconds = 0;
                    window.clearInterval(time);
                } else {
                    _this.seconds -= 1;
                }
            }, 1000);
        },
        // 截标时间到了
        countDowmEnd(val) {
            this.openbidButton = val;
        },
        // 左边信息栏
        async openBidsign() {
            let projectId = localStorage.getItem('projectId');
            try {
                const { data, code } = await openBidsign(projectId);
                this.leftmessage = data;
            } catch (e) {
                console.log(e);
            }
        },
        // 获取时间比较
        async getsigndetail() {
            try {
                let projectId = localStorage.getItem('projectId');
                var { data, code, msg } = await opentimeInfo(projectId);
                if (code == 200) {
                    this.remaintime = Number(data.remainTime);
                    this.storagedecodeTime = Number(data.decodeTime);
                    this.storagesignatureTime = Number(data.signatureTime);
                } else {
						this.$message({
							message: msg,
							type: 'error',
							duration: 3000
						})
						setTimeout(() => {
							this.$router.go(-1)
						}, 3000)
					}
                var { data, code } = await signdetail(projectId);
                if (code == 200) {
                    this.openStatus = data.openStatus;
                    this.issueTable = data.issueTable;
                    let localTime = new Date().getTime();
                    console.log(this.storagedecodeTime, '..............');
                    let comparyTime = this.storagedecodeTime - (localTime - data.openBidTime) / 1000;
                    if (comparyTime > 0) {
                        this.decodeTime = comparyTime;
                        console.log('大于');
                    } else {
                        console.log('小于');
                        this.isDecode = true;
                    }
                    let comparyTime1 = this.storagesignatureTime - (localTime - data.openBidTime) / 1000;
                    if (comparyTime > 0) {
                        this.signatureTime = comparyTime1;
                        console.log('大于');
                    } else {
                        console.log('小于');
                        this.isSignature = true;
                    }
                }
            } catch (e) {
                console.log(e);
            }
        },
        // 开标一栏表
        async getopenInfo() {
            try {
                let projectId = localStorage.getItem('projectId');
                const { data, code } = await openInfolist(projectId);
                if (code == 200) {
                    for (let item of data) {
                        if (item.isSign) {
                            item.isSign = '是';
                        } else {
                            item.isSign = '否';
                        }
                    }
                    this.tableData = data;
                }
            } catch (e) {
                console.log(e);
            }
        }
    },
    // updated() {
    // 	// 聊天定位到底部
    // 	let ele = document.getElementById('chatRecord');
    // 	ele.scrollTop = ele.scrollHeight;
    // 	let ele1 = document.getElementById('chatRecord1');
    // 	ele1.scrollTop = ele1.scrollHeight;
    // },
    destroyed() {
        //清除定时器
        clearInterval(this.timer);
        clearInterval(this.timer1);
        this.websocket.close();
    }
};
</script>

<style scoped>
.abs {
    position: absolute;
    right: 100px;
    bottom: -91px;
}
.flex-left {
    display: flex;
    justify-content: flex-start;
}

.flex-right {
    display: flex;
    justify-content: flex-end;
}

.hal {
    position: relative;
}

.dialogue {
    position: absolute;
    top: 10%;
    right: 10%;
    border: 1px solid #cccccc;
    padding: 10px;
}

.dialogue > .dialogueList {
    box-sizing: border-box;
    padding: 20px;
    overflow: auto;
    border: 1px solid #dcdfe6;
    width: 400px;
    height: 300px;
}

.dialogueList > li {
    margin-bottom: 20px;
}

.explain > h1 {
    text-align: center;
    margin: 30px 0;
}

.buttons {
    margin: 100px 0;
}

.hal-left {
    width: 200px;
}

.hal-left > div {
    width: 100%;
    height: 300px;
    border: 1px solid #000;
    box-sizing: border-box;
    padding: 40px 20px;
}

.hal-right {
    width: 200px;
    height: 500px;
}

.hal-right > button {
    margin-bottom: 20px;
}

.hal-center {
    flex: 1;
    height: 500px;
    border: 1px solid #000;
    margin: 0 50px;
    box-sizing: border-box;
    padding: 30px;
    overflow: auto;
}

.hal-center > ul > li {
    margin-bottom: 30px;
}

.hal-center > ul > li > div {
    margin-right: 10px;
    font-size: 16px;
}

.button-pos {
    margin-top: 50px;
}

.time-message {
    width: 60%;
    margin: 10px auto;
    font-size: 16px;
}

.hal-left h1 {
    margin-bottom: 50px;
    /* 	letter-spacing:5px */
}

.bid-message {
    flex-wrap: wrap;
    font-size: 16px;
}

.bid-message > div {
    margin-right: 50px;
    margin-bottom: 30px;
}
</style>
