<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="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">
						<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 @click="isMessge=true">签到解密签名情况</div>
					</div>
					<div class="hal-center">
						<ul id="chatRecord1">
							<li v-for="(item,index) in halList" :key="index" class="flex-item">
								<div>{{item.time}}</div>
								<div>{{item.name}}</div>
								<div>{{item.behavior}}</div>
							</li>
						</ul>
					</div>
					<div class="hal-right">
						<el-button @click="isdialogue">在线对话<i class="el-icon-chat-dot-round"></i></el-button>
						<div class="button-pos">
							<el-button v-if="openStatus==1" type="primary" @click="confirm" style="margin-left: 10px;" :disabled="!openbidButton">立即开标</el-button>
							<el-button v-if="openStatus==2" type="primary" @click="end" style="margin-top: 10px;" :disabled="!endbidButton">结束开标</el-button>
						</div>
					</div>
					<!-- 在线对话 -->
					<div class="dialogue" style="margin-top: 30px;" v-show="dialogue">
						<ul class="dialogueList" id="chatRecord">
							<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-between buttons">
					<el-button @click="isfailInfo=true" v-if="!isFailed">流标</el-button>
					<el-button @click="failDetail" v-else>流标信息</el-button>
					<div>
						<el-button icon="el-icon-refresh">刷新</el-button>
						<el-button>下发开标一览表</el-button>
						<el-button @click="isopenInfo=true">查看开标一览表</el-button>
					</div>
					<el-button @click="back">退出大厅<i class="el-icon-right"></i></el-button>
				</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="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 {
		getTime
	} from '@utils/time'
	import {
		timeInfo,
		startInfo,
		openInfo,
		signdetail,
		startbid,
		openbidFailed,
		bidFaileddetail,
		bidFinish
	} 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 {
				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,
				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: 'project'
					},
					{
						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.getstartInfo();
			this.getopenInfo();
			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.getstartInfo()
			}, 5000);
		},
		methods: {
			 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.success(msg)
							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")
					const {
						data,
						code
					} = await timeInfo(projectId)
					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)
				} 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
						this.openStatus=data.openStatus
						this.isFailed=data.isFailed
					}
				} catch (e) {
					console.log(e)
				}
			},
			//签到解密略简
			async getsigndetail() {
				try {
					let projectId = localStorage.getItem("projectId")
					const {
						data,
						code
					} = await signdetail(projectId)
					if (code == 200) {
						this.leftmessage = data
					}
				} 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
			},
			// 解密时间到了
			decodeTimeEnd(val) {

			},
			// 签名时间到了
			signatureTimeEnd(val) {
				this.endbidButton = 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.$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

						}
					}
				})
			},
			// websocket
			createWebSocket() {
				let token = localStorage.getItem("token")
				let projectId = localStorage.getItem("projectId")
				// 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);
					if (data.type == 1) {
						this.content = ""
						this.dialogueList.push(data)
					} else {
						this.halList.push(data)
					}
				}
				this.websocket.onclose = function() {
					console.log('关闭了')
				}
				// 路由跳转时结束websocket链接
				this.$router.afterEach(function() {
					this.websocket.close()
				})
				// 监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常
				// window.onbeforeunload = function() {
				// 	this.websocket.close()
				// }
			},
			send() {
				let content = this.content;
				if(content.split(" ").join("").length == 0){
				  this.$message.error("请输入内容")
				}else{
					this.websocket.send(content)
				}
			}
		},
		 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);
		}
	}
</script>

<style scoped>
	.flex-left {
		display: flex;
		justify-content: flex-start;
	}

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

	.dialogue {
		position: absolute;
		top: 10%;
		right: 10%;
	}

	.dialogue>.dialogueList {
		border: 1px solid #DCDFE6;
		width: 400px;
		height: 300px;
		/* overflow: auto; */
	}

	.hal {
		position: relative;
	}

	.buttons {
		margin: 100px 0;
	}

	.hal-left {
		width: 150px;

	}

	.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-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 */
		font-size: 24px;
	}

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

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