<template>
    <div>
        <div>
            <dataBreadcrumb :breads="breads"></dataBreadcrumb>
            <div class="back-fff" style="padding: 10px 0 0 10px">中国标准时间：{{ currentTime }}</div>
            <div class="hal">
                <h2 class="back-fff" style="text-align: center">{{ projectName }}项目开标大厅</h2>
                <div class="back-fff flex-center time">
                    <div class="time-message flex-between">
                        <div class="flex">
                            <p>截标倒计时：</p>
                            <timeDown :remain-time="remaintime" @countDowmEnd="remaintimeEnd"></timeDown>
                        </div>
                        <!-- <div class="flex" v-show="decodeTime"> -->
                        <div class="flex" v-show="openStatus == 2">
                            <p>解密倒计时：</p>
                            <timeDown :remain-time="decodeTime" @countDowmEnd="decodeTimeEnd"></timeDown>
                        </div>
                        <!-- <div class="flex" v-show="signatureTime"> -->
                        <!-- <div class="flex" v-show="openStatus == 2&&endbidButton"> -->
                        <div class="flex" v-show="openStatus == 2 && issueTable">
                            <p>签名倒计时：</p>
                            <timeDown :remain-time="signatureTime" @countDowmEnd="signatureTimeEnd"></timeDown>
                        </div>
                    </div>
                </div>

                <div class="flex">
                    <div class="hal-left back-fff flex-colunm">
                        <h1>签到{{ leftmessage.signIn }}人</h1>
                        <h1>解密{{ leftmessage.decode }}人</h1>
                        <h1>签名{{ leftmessage.signature }}人</h1>
                        <div @click="isMessge = true">签到解密签名情况 ></div>
                    </div>
                    <div class="hal-center back-fff" v-chat-scroll>
                        <ul>
                            <li v-for="(item, index) in halList" :key="index" class="flex-item textheight">
                                <div>{{ item.time }}</div>
                                <div>{{ item.name }}</div>
                                <div>{{ item.behavior }}</div>
                            </li>
                        </ul>
                    </div>
                    <div class="hal-right">
                        <el-button type="primary" style="margin-left: 10px" @click="isdialogue"
                            ><i class="el-icon-chat-dot-round"></i>在线对话</el-button
                        >
                        <el-button type="primary" @click="openInfo1" :disabled="!endbidButton" v-if="!issueTable">下发开标一览表</el-button>
                        <el-button type="primary" @click="openInfo" :disabled="!issueTable">查看开标一览表</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>
                    <!-- 
						<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 type="primary" @click="isfailInfo = true" v-if="!isFailed">流标</el-button>
                        <el-button type="primary" @click="failDetail" v-else>流标信息</el-button>
                    </div>
                    <div>
                        <el-button type="primary" @click="back">退出大厅</el-button>
                    </div>
                    <div>
                        <!-- <el-button icon="el-icon-refresh" @click="refrsh">刷新</el-button> -->
                        <el-button v-if="openStatus == 1" type="primary" @click="confirm" :disabled="!openbidButton">立即开标</el-button>
                        <el-button v-if="openStatus == 2" type="primary" @click="end" :disabled="!endbidButton">结束开标</el-button>
                    </div>
                </div>
            </div>
            <!--确认开标窗口 -->
            <el-dialog :visible.sync="isOpenbid" title="确认开标" width="35%">
                <div class="flex bid-message" style="width: 70%; margin: 0 auto">
                    <div>项目编号：{{ projectCode }}</div>
                    <div>项目名称：{{ projectName }}</div>
                    <div style="margin-right: 120px">投标人数：{{ startDetail.bidFileCount }}</div>
                    <div>缴纳保证金人数：{{ startDetail.earnestFeeCount }}</div>
                    <div>签到人数：{{ startDetail.signInCount }}</div>
                </div>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="isOpenbid = false">取消开标</el-button>
                    <el-button type="primary" @click="openbid">确定开标 </el-button>
                </div>
            </el-dialog>
            <!--  详细信息 -->
            <el-dialog :visible.sync="isMessge" title="详细信息" width="60%">
                <dataTable :columns="columns" :page-obj="pageObj" :margin-top="0" :margin-bottom="0" url="/open-bid/sign/detail">
                    <el-table-column slot="operate" label="是否买断账期" align="center" fixed="right">
                        <template slot-scope="scope">
                            <div v-if="scope.row.isPayment">是</div>
                            <div v-else>否</div>
                        </template>
                    </el-table-column>
                    <el-table-column slot="operate" label="是否递交投标文件" align="center" fixed="right">
                        <template slot-scope="scope">
                            <div v-if="scope.row.bidFileId">是</div>
                            <div v-else>否</div>
                        </template>
                    </el-table-column>
                    <el-table-column slot="operate" label="签到" align="center" fixed="right">
                        <template slot-scope="scope">
                            <div v-if="scope.row.signIn">是</div>
                            <div v-else>否</div>
                        </template>
                    </el-table-column>
                    <el-table-column slot="operate" label="解密" align="center" fixed="right">
                        <template slot-scope="scope">
                            <div v-if="scope.row.decode">是</div>
                            <div v-else>否</div>
                        </template>
                    </el-table-column>
                    <el-table-column slot="operate" label="签名" align="center" fixed="right">
                        <template slot-scope="scope">
                            <div v-if="scope.row.signature">是</div>
                            <div v-else>否</div>
                        </template>
                    </el-table-column>
                </dataTable>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="isMessge = 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>
                </div>
            </el-dialog>
            <!-- 下发开标一览表 -->
            <el-dialog :visible.sync="isopenInfo1" title="下发开标一览表">
                <nopageTable :tableData="tableData" :columns="nopagecolumns" :margin-top="0" :margin-bottom="0"> </nopageTable>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="isopenInfo1 = false">关闭 </el-button>
                    <el-button @click="issue" type="primary">下发 </el-button>
                </div>
            </el-dialog>
            <!-- 流标框提交 -->
            <el-dialog :visible.sync="isfailInfo" title="流标">
                <el-form :model="form" :rules="rules" ref="form" label-width="100px">
                    <el-form-item label="操作人">
                        <div>{{ userName }}</div>
                    </el-form-item>
                    <el-form-item label="流标原因" prop="reason">
                        <el-input v-model.trim="form.reason" maxlength="300" type="textarea" :rows="2"></el-input>
                    </el-form-item>
                    <el-form-item label="上传附件">
                        <singleUpload :limit="1" :max="10" tip="支持上传1份附件，不差过10M." @input="getfile"></singleUpload>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="isfailInfo = false">取 消</el-button>
                    <el-button type="primary" @click="failbid">确 定</el-button>
                </div>
            </el-dialog>
            <!-- 流标详情 -->
            <el-dialog :visible.sync="isfailDetail" title="流标信息">
                <el-form :model="form" :rules="rules" ref="form" label-width="100px">
                    <el-form-item label="操作人">
                        <div>{{ userName }}</div>
                    </el-form-item>
                    <el-form-item label="流标原因" prop="reason">
                        <div>{{ faildetail.reason }}</div>
                    </el-form-item>
                    <el-form-item label="上传附件" v-if="faildetail.fileName">
                        <div @click="down(faildetail.fileUrl)">{{ faildetail.fileName }}</div>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="isfailDetail = false">取 消</el-button>
                </div>
            </el-dialog>
        </div>
    </div>
</template>

<script>
import { openUrl } from '@utils/common';
import { getTime } from '@utils/time';
import {
    timeInfo,
    startInfo,
    openInfo,
    signdetail,
    startbid,
    openbidFailed,
    bidFaileddetail,
    bidFinish,
    issueopenInfo
} from '@api/purchaser/bid';
import dataBreadcrumb from '@components/dataBreadcrumb.vue';
import timeDown from '@components/timeDown.vue';
import dataTable from '@components/dataTable.vue';
import nopageTable from '@components/nopageTable.vue';
import singleUpload from '@components/Upload/Upload.vue';
export default {
    components: {
        dataBreadcrumb,
        timeDown,
        dataTable,
        nopageTable,
        singleUpload
    },
    data() {
        return {
            tool: {
                show: ['11'],
                callback: this.toolEvent,
                showEmoji: false
            },
            issueTable: false,
            openStatus: '',
            faildetail: '',
            isfailDetail: false,
            projectCode: '',
            projectName: '',
            userName: '',
            isFailed: true,
            rules: {
                reason: [
                    {
                        required: true,
                        message: '请输入',
                        trigger: 'blur'
                    }
                ]
            },
            form: {
                reason: '',
                filePOList: []
            },
            isfailInfo: false,
            endbidButton: false,
            tableData: [],
            isopenInfo: false,
            isopenInfo1: false,
            startDetail: '',
            dialogue: false,
            remaintime: '',
            storagedecodeTime: '',
            storagesignatureTime: '',
            decodeTime: '',
            signatureTime: '',
            isMessge: false,
            pageObj: {
                size: 10,
                currentPage: 1,
                func: (currentPage) => {
                    this.pageTurning(currentPage);
                }
            },
            nopagecolumns: [
                {
                    label: '投标人名称',
                    prop: 'companyName'
                },
                {
                    label: '投标报价(元)',
                    prop: 'price'
                },
                {
                    label: '是否签名',
                    prop: 'isSign'
                }
            ], //
            columns: [
                {
                    label: '投标公司',
                    prop: 'companyName'
                },
                {
                    label: '联系人',
                    prop: 'contactsName'
                },
                {
                    label: '手机号',
                    prop: 'phone'
                },
                {
                    slot: 'operate'
                }
            ], //
            isOpenbid: false,
            buttonWords: '立即开标',
            openbidButton: false,
            halList: [],
            minutes: '',
            seconds: '',
            currentTime: '',
            breads: ['招标管理', '招标项目管理', '工作台'],
            websock: null,
            content: '',
            dialogueList: [],
            myId: '',
            leftmessage: '',
            timer: ''
        };
    },
    created() {
        this.projectCode = localStorage.getItem('projectCode');
        this.projectName = localStorage.getItem('projectName');
        this.userName = JSON.parse(localStorage.getItem('userInfo')).name;
        // this.gettimeInfo();
        this.getsigndetail();
        this.myId = JSON.parse(localStorage.getItem('userInfo')).userId;
        this.pageObj.companyId = localStorage.getItem('companyId');
        this.pageObj.projectId = localStorage.getItem('projectId');
        // 中国标准时间
        let currentTime = getTime();
        this.currentTime = currentTime;
        this.timer1 = setInterval(() => {
            let currentTime = getTime();
            this.currentTime = currentTime;
        }, 1000);
        // websocket
        this.createWebSocket();
        // 长轮训获取
        this.timer = setInterval(() => {
            this.getsigndetail();
        }, 5000);
    },
    methods: {
        openInfo() {
            this.isopenInfo = true;
            this.getopenInfo();
        },
        openInfo1() {
            this.isopenInfo1 = true;
            this.getopenInfo();
        },
        // 下发
        async issue() {
            let projectId = localStorage.getItem('projectId');
            try {
                const { msg, code } = await issueopenInfo(projectId);
                if (code == 200) {
                    this.getsigndetail();
                    this.$message({
                        message: msg,
                        type: 'success',
                        duration: 1500
                    });
                    this.isopenInfo1 = false;
                }
            } catch (e) {
                console.log(e);
            }
        },
        /* refrsh() {
				history.go(0)
			}, */
        async end() {
            try {
                let projectId = localStorage.getItem('projectId');
                const { msg, code } = await bidFinish(projectId);
                if (code == 200) {
                    this.$message({
                        message: msg,
                        type: 'success',
                        duration: 1500
                    });
                    setTimeout(() => {
                        this.$router.go(-1);
                    }, 1500);
                } else {
                    this.$message.error(msg);
                }
            } catch (e) {
                console.log(e);
            }
        },
        down(url) {
            window.open(url);
        },
        // 流标详情
        async failDetail() {
            this.isfailDetail = true;
            let projectId = localStorage.getItem('projectId');
            const { data, code } = await bidFaileddetail(projectId);
            if (code == 200) {
                this.faildetail = data;
            }
        },
        // 确定流标
        async failbid() {
            try {
                let valid = await this.$refs['form'].validate();
                if (valid) {
                    let form = this.form;
                    form.projectId = localStorage.getItem('projectId');
                    const { code, msg } = await openbidFailed(form);
                    if (code === 200) {
                        this.$message({
                            message: msg,
                            type: 'success',
                            duration: 1500
                        });
                        setTimeout(() => {
                            this.$router.push('/purchaser/bid/workbench');
                        }, 1500);
                        // this.isfailInfo = false;
                        // this.isFailed = false;
                    } else if (code === 500) {
                        this.$message.error(msg);
                        this.isfailInfo = false;
                        this.isFailed = false;
                    }
                }
            } catch (e) {
                console.log(e);
            }
        },
        isdialogue() {
            this.dialogue = !this.dialogue;
        },
        getfile(val) {
            this.form.filePOList = val;
        },
        // 时间信息
        // async gettimeInfo() {
        // 	try {
        // 		let projectId = localStorage.getItem("projectId")

        // 	} catch (e) {
        // 		console.log(e)
        // 	}
        // },
        // 开标按钮上三个信息（投标人数，缴纳保证金人数，签到人数）
        async getstartInfo() {
            try {
                let projectId = localStorage.getItem('projectId');
                const { data, code } = await startInfo(projectId);
                if (code == 200) {
                    this.startDetail = data;
                }
            } catch (e) {
                console.log(e);
            }
        },
        //签到解密略简
        async getsigndetail() {
            try {
                let projectId = localStorage.getItem('projectId');
                var { data, code, msg } = await timeInfo(projectId);
                if (code == 200) {
                    let remaintime = Number(data.remainTime);
                    if (remaintime < 0) {
                        this.openbidButton = true;
                    } else {
                        this.remaintime = 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.leftmessage = data;
                    this.openStatus = data.openStatus;
                    this.isFailed = data.isFailed;
                    this.issueTable = data.issueTable;
                    let localTime = new Date().getTime();
                    // 解密时间
                       let comparyTime = this.storagedecodeTime - (localTime - data.openBidTime) / 1000;
                    if(data.issueTable){
                        // 签名时间
                       this.signatureTime = this.storagesignatureTime - (localTime - data.openBidTime) / 1000+this.storagedecodeTime;
                    }
                    if (data.openStatus == 2) {
                        console.log(this.storagedecodeTime, '..............');
                         this.decodeTime = comparyTime;
                        if (comparyTime > 0) {
                            console.log('大于');
                        } else {
                            console.log('小于');
                            this.endbidButton = true;
                           
                        }
                    }
                }
            } catch (e) {
                console.log(e);
            }
        },
        // 开标一栏表
        async getopenInfo() {
            try {
                let projectId = localStorage.getItem('projectId');
                const { data, code } = await openInfo(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);
            }
        },
        back() {
            this.$router.go(-1);
        },
        // 计算分秒倒计时
        // 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)
        // },
        // 截标时间到了
        remaintimeEnd(val) {
            this.openbidButton = val;
            console.log('截标时间到了');
        },
        // 解密时间到了
        decodeTimeEnd(val) {
            this.endbidButton = val;
            console.log('解密时间到了');
        },
        // 签名时间到了
        signatureTimeEnd(val) {},
        // 开标
        async openbid() {
            try {
                let projectId = localStorage.getItem('projectId');
                const { code, msg } = await startbid(projectId);
                if (code == 200) {
                    this.isOpenbid = false;
                    this.openbidButton = false;
                    this.buttonWords = '停止开标';
                    // this.decodeTime = this.storagedecodeTime
                    // this.signatureTime = this.storagesignatureTime
                    this.getsigndetail();
                    this.$message({
                        message: '开标成功',
                        type: 'success'
                    });
                } else {
                    this.$message({
                        message: msg,
                        type: 'error'
                    });
                }
            } catch (e) {
                console.log(e);
            }
        },
        // 开标提示
        confirm() {
            // this.$alert('请立即开标', '请立即开标', {
            //     confirmButtonText: '知道了',
            //     callback: (action) => {
            //         if (action === 'confirm') {
            //         }
            //     }
            // });
            this.isOpenbid = true;
            this.getstartInfo();
        },
        // 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);
        }
    },

    destroyed() {
        //清除定时器
        clearInterval(this.timer);
        clearInterval(this.timer1);
        console.log('定时器关闭');
        this.websocket.close();
    }
};
</script>

<style scoped>
ul {
    list-style-type: decimal !important;
}
.time {
    height: 48px;
    margin-bottom: 10px;
}
.abs {
    position: absolute;
    right: 100px;
    bottom: -91px;
}
.flex-left {
    display: flex;
    justify-content: flex-start;
}

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

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

.hal {
    position: relative;
}
.hal > h2 {
    width: 100%;
    height: 55px;
    line-height: 55px;
    border-bottom: 1px solid #dadada;
}

.back-fff {
    background: #fff;
}

.buttons {
    margin: 100px 0;
}
.buttons > div {
    margin-right: 20px;
}
.hal-left {
    width: 198px;
    height: 218px;
    background: #ffffff;
}
/* 
	.hal-left>div:first-child {
		width: 100%;
		height: 300px;
		border: 1px solid #000;
		box-sizing: border-box;
		padding: 40px 20px
	}

	.hal-left>div:last-child {
		width: 100%;
		height: 50px;
		line-height: 50px;
		font-size: 18px;
		text-align: center;
		border: 1px solid #000;
		margin-top: 50px;
	} */

.hal-right {
    width: 150px;
    height: 500px;
}
.hal-right > button {
    margin-bottom: 16px;
}

.hal-center {
    flex: 1;
    height: 500px;
    margin: 0 14px;
    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: 0px auto;
    font-size: 16px;
}

.hal-left h1 {
    margin-bottom: 24px;
    /* 	letter-spacing:5px */
    font-size: 18px;
}

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

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

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

.dialogueList > li {
    margin-bottom: 20px;
}
.textheight {
    line-height: 20.8px;
    display: flex;
    justify-content: flex-start;
}
</style>
