<template>
	<div class="container">
		<my-nav
			@listener-in="inHandle"
			@listener-helper="helperHandle"
		></my-nav>
		<div class="content">
			<div class="reading" v-if="reading">
				入库扫描中<br />
				请将需要入库的物料推入感应门
			</div>
			<div v-else style="height: 100%">
				<div
					style="
						display: flex;
						justify-content: space-between;
						align-items: center;
					"
				>
					<div style="width: 108px"></div>
					<div class="title">入库扫描</div>
					<div style="padding: 0 10px">
						<Button
							type="primary"
							style="margin-right: 10px"
							@click="purContractPageListModal = true"
							>手动入库</Button
						>
						<Button type="primary" @click="scanShow = true"
							>辅助扫描</Button
						>
					</div>
				</div>
				<div class="main">
					<div class="list-wrap">
						<div class="list" style="margin-right: 20px">
							<div class="sub-title">已贴标物料</div>
							<div
								style="
									height: calc(100% - 46px);
									overflow: auto;
								"
							>
								<div
									class="row"
									v-for="(item, index) in data"
									:key="index"
								>
									<div
										class="col"
										style="width: 50px; align-items: center"
									>
										<Icon
											type="ios-checkmark-circle"
											color="red"
											size="18"
											v-if="item.checked"
										/>
									</div>
									<div class="col" style="flex: 1">
										<div>{{ item.materialName }}</div>
										<div>
											物料长度：{{ item.quantity }}米
										</div>
									</div>
								</div>
							</div>
						</div>
						<div class="list">
							<div class="sub-title">本次入库</div>
							<div
								style="
									height: calc(100% - 46px);
									overflow: auto;
								"
							>
								<div
									class="row"
									v-for="(
										item, index
									) in scanData.rfidTagItems"
									:key="index"
								>
									<div
										class="col"
										style="width: 50px; align-items: center"
									></div>
									<div
										class="col"
										style="flex: 1"
										:style="{
											color:
												item.scanRfidStatus === 1
													? 'orange'
													: item.scanRfidStatus === 2
													? 'red'
													: '#fff',
										}"
									>
										<div>{{ item.materialName }}</div>
										<div>
											物料长度：{{ item.quantity || 0 }}米
										</div>
									</div>
									<div
										class="col"
										style="flex: 1"
										:style="{
											color:
												item.scanRfidStatus === 1
													? 'orange'
													: item.scanRfidStatus === 2
													? 'red'
													: '#fff',
										}"
									>
										<div>标签值：{{ item.rfid }}</div>
									</div>
									<div class="col" style="width: 50px">
										<Icon
											type="ios-trash"
											size="20"
											color="red"
											@click="del(item, index)"
											style="cursor: pointer"
										/>
									</div>
								</div>
							</div>
						</div>
					</div>
					<div class="list-wrap bottom">
						<div class="list">
							<div class="sub-title">
								本次统计
								<a class="remark" href="#" @click="show = true"
									>填写备注</a
								>
							</div>
							<div
								style="
									height: calc(100% - 46px);
									overflow: auto;
								"
							>
								<div
									class="row"
									v-for="(item, index) in materialItemsCopy"
									:key="index"
								>
									<div
										class="col"
										style="flex: 3"
										:style="{
											color:
												item.scanRfidStatus === 1
													? 'orange'
													: item.scanRfidStatus === 2
													? 'red'
													: '#fff',
										}"
									>
										<div>{{ item.materialName }}</div>
									</div>
									<div
										class="col"
										style="flex: 2"
										:style="{
											color:
												item.scanRfidStatus === 1
													? 'orange'
													: item.scanRfidStatus === 2
													? 'red'
													: '#fff',
										}"
									>
										<div>入库件数：{{ item.tagCount }}</div>
									</div>
									<div
										class="col"
										style="flex: 2"
										:style="{
											color:
												item.scanRfidStatus === 1
													? 'orange'
													: item.scanRfidStatus === 2
													? 'red'
													: '#fff',
										}"
									>
										<div>
											入库数量：{{ item.quantity }}米
										</div>
									</div>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="footer">
					<Button
						type="error"
						size="large"
						style="margin-right: 20px"
						@click="pass(0)"
						>重新扫描</Button
					>
					<Button type="success" size="large" @click="pass(1)"
						>确认无误</Button
					>
				</div>
			</div>
		</div>
		<div class="remark-content">
			<Modal
				v-model="modal"
				:mask-closable="false"
				:closable="false"
				:fullscreen="true"
				:footer-hide="true"
			>
				<Progress
					:percent="percent"
					:stroke-color="['#108ee9', '#87d068']"
					:hide-info="true"
					style="width: 400px"
				/>
			</Modal>
		</div>
		<!-- 填写备注 -->
		<Modal
			v-model="show"
			:closable="false"
			:footer-hide="true"
			class-name="vertical-center-modal"
			@on-cancel="cancel"
		>
			<div class="remark-content">
				<div class="title">填写备注</div>
				<Input v-model="remark" type="textarea" :rows="10" />
				<div class="btn">
					<Button @click="cfm" type="success" style="width: 120px"
						>确定</Button
					>
				</div>
			</div>
		</Modal>
		<!-- 手动入库 -->
		<Modal
			v-model="purContractPageListModal"
			title="手动入库"
			okText="关闭"
			class-name="purContractPageList"
			@on-cancel="purContractPageListModal = false"
			width="90%"
		>
			<my-table
				:data="purContractPageListData"
				:columns="purContractPageListColumns"
				:table-filter="tableFilter"
				:table-page="params"
				@event-handle="eventHandle"
				@on-change="changePage"
			></my-table>
		</Modal>
		<my-manege-modal
			v-model="showInfo"
			:data="formData"
			@approval-handle="approvalHandle"
		>
		</my-manege-modal>
		<!-- 辅助扫描 -->
		<Modal
			v-model="scanShow"
			class-name="vertical-center-modal"
			@on-cancel="cancel"
		>
			<div class="scan-title" slot="header">辅助扫描</div>
			<div class="scan-btn" slot="footer">
				<Button
					type="primary"
					style="width: 80px"
					@click="scanShow = false"
					>关闭</Button
				>
			</div>
			<div class="scan-content" v-if="otherData.length > 0">
				<div
					class="item"
					v-for="(item, index) in otherData"
					:key="index"
				>
					<div class="left">
						<div class="row">RFID标签：{{ item.rfidCode }}</div>
						<div class="row">物料编码：{{ item.materialCode }}</div>
						<div class="row">物料名称：{{ item.materialName }}</div>
						<div class="row">最近操作：{{ item.lastOpera }}</div>
					</div>
					<div class="right">
						<Button
							type="primary"
							ghost
							@click="add(item)"
							v-if="item.lastOpera.indexOf('入库') === -1"
							>入库</Button
						>
					</div>
				</div>
			</div>
			<div v-else style="padding: 10px 0; color: #ffffff">暂无数据</div>
		</Modal>
	</div>
</template>
  
  <script>
import MyNav from '@/components/my-nav'
import * as signalR from '@microsoft/signalr'
import { MessagePackHubProtocol } from '@microsoft/signalr-protocol-msgpack'
import withUrl from '@/config/withUrl'
import MyTable from '@/components/my-table/my-table'
import {
	GetHasTagMaterialList,
	PlcStorageIn,
	ReScan,
	GetScanRfidStocInOut,
	DelScanRfid,
	GetPurContractPageList,
} from '@/api/integrated'
import store from '@/store'
import { logOut } from '@/libs/util'
import MyManegeModal from './my-manage-modal'
export default {
	name: 'store-in',
	components: {
		MyTable,
		MyNav,
		MyManegeModal,
	},
	

	data() {
		return {
			scanShow: false,
			show: false,
			modal: false,
			percent: 0,
			addTimer: null,
			overTimer: null,
			reading: false,
			connection: null,
			data: [], // 左侧数据列表
			scanData: {
				rfidTagItems: [],
				materialItems: [],
			}, // 扫描数据
			otherData: [], // 扫描辅助数据
			tempDelData: [], // 临时删除列表
			remark: '',
			materialItemsCopy: [],
			// 手动入库
			showInfo: false,
			formData: {},
			purContractPageListModal: false,
			purContractPageListData: [],
			purContractPageListColumns: [
				{
					title: '序号',
					type: 'index',
					width: 60,
					align: 'center',
				},
				{
					title: '合同编号',
					key: 'purchaseBillNo',
					minWidth: 200,
					render: (h, params) => {
						let _this = this
						return h(
							'a',
							{
								on: {
									click() {},
								},
							},
							params.row.purchaseBillNo
						)
					},
				},
				{
					title: '合同状态',
					key: 'supplierShipState',
					minWidth: 150,
				},
				{
					title: '交货日期',
					key: 'deliverTime',
					minWidth: 150,
				},
				{
					title: '件号',
					key: 'materialCode',
					minWidth: 150,
				},
				{
					title: '物料名称',
					key: 'materialName',
					minWidth: 150,
				},
				{
					title: '规格',
					key: 'spec',
					minWidth: 150,
				},
				{
					title: '单位',
					key: 'unitName',
					minWidth: 150,
				},
				{
					title: '采购数量',
					key: 'purchaseQty',
					minWidth: 150,
				},
				{
					title: '单价',
					key: 'price',
					minWidth: 150,
				},
				{
					title: '小计',
					key: 'totalAmount',
					minWidth: 150,
				},
				{
					title: '已出货',
					key: 'shipQuantity',
					minWidth: 150,
				},
				{
					title: '已出货金额',
					key: 'shipAmount',
					minWidth: 150,
				},
				{
					title: '操作',
					key: 'takeState',
					minWidth: 180,
					align: 'center',
					fixed: 'right',
					render: (h, params) => {
						let _this = this
						return h('div', [
							h(
								'Button',
								{
									props: {
										type: 'primary',
										size: 'small',
									},
									style: {
										marginRight: '10px',
									},
									on: {
										click: () => {
											_this.formData = {
												...params.row,
											}
											_this.showInfo = true
										},
									},
								},
								'查看批次'
							),
						])
					},
				},
			],
			tableFilter: [
				{
					name: 'Input',
					value: 'key',
					placeholder: '请输入关键字',
				},
				{
					name: 'Button',
					type: 'primary',
					text: '查询',
					e: 'search',
				},
			],
			params: {
				pageIndex: 1,
				pageSize: 10,
				total: 0,
				supplierShipState: 0,
			},
			ws:null,
		}
	},
	methods: {
		add(item) {
			item.totalQuantity = item.qty
			item.quantity = item.qty
			// 辅助扫描的添加一个isTemp 标识以供删除区分
			if (
				this.scanData.rfidTagItems.find(
					(scan) => scan.materialCode === item.materialCode
				)
			) {
				this.$Message.error('物料已添加')
			} else {
				this.scanData.rfidTagItems.push({ ...item, isTemp: true })
				this.scanData.materialItems.push({ ...item, isTemp: true })
				this.$Message.info('添加成功')
			}
		},
		cancel() {
			this.remark = ''
		},
		cfm() {
			this.show = false
		},
		/* 临时删除 */
		del(item, index) {
			// if (item.isTemp) {
			this.scanData.rfidTagItems.splice(index, 1)
			this.scanData.materialItems.splice(index, 1)
			/* 添加一个临时删除数据 用于再次扫描数据时过滤已临时删除的数据 */
			this.tempDelData.push(item)
			this.materialItemsCopy = []
			for (
				let i = 0;
				i < this.scanData.rfidTagItems.length;
				i++
			) {
				const element = this.scanData.rfidTagItems[i]
				
				if (this.materialItemsCopy.length == 0) {
					this.materialItemsCopy.push({
						...element,
						tagCount: 1,
					})
				} else {
					var isTotal = false

					for (
						let j = 0;
						j < this.materialItemsCopy.length;
						j++
					) {
						const jelement = this.materialItemsCopy[j]
						if (
							element.materialCode ===
							jelement.materialCode
						) {
							isTotal = true
							jelement.tagCount++
							jelement.quantity += element.quantity
						}
					}
					if (!isTotal)
						this.materialItemsCopy.push({
							...element,
							tagCount: 1,
						})
				}
			}
		},
		/* 辅助扫描通知 */
		helperHandle(data) {
			this.otherData = data
		},
		/* 入库通知 */
		inHandle() {
			this.getScanList()
			clearTimeout(this.overTimer)
			this.overTimer = setTimeout(() => {
				clearInterval(this.addTimer)
				this.percent = 100
				setTimeout(() => {
					this.modal = false
				}, 500)
			}, 3000)
		},
		/* 是否通过 0否 1是 */
		pass(type) {
			if (type === 0) {
				this.$Message.info('请重新扫描入库！')
				this.scanData.rfidTagItems = []
				this.scanData.materialItems = []
				this.materialItemsCopy = []
				this.tempDelData = []
				if(window.ws) window.ws.close()
				setTimeout(() => {
					this.socketInit()
				}, 500);
			} else if (type === 1) {
				// 入库
				PlcStorageIn({
					storageDoor: sessionStorage.getItem('door'),
					plcStationCode: sessionStorage.getItem('plcCode'),
					rfidList: this.scanData.rfidTagItems.map(
						(item) => item.rfid
					),
					remark: this.remark,
				}).then((res) => {
					if (res.code === 0) {
						this.$Message.info('入库成功！')
						logOut()
						// this.$store.commit('setHasGetInfo', false)
						// this.$store.commit('setToken', '')
						// setTimeout(() => {
						//   this.$router.push({
						//     name: 'Home',
						//     query: {
						//       plcCode: sessionStorage.getItem('plcCode'),
						//       door: sessionStorage.getItem('door')
						//     }
						//   })
						// }, 500)
					}
				})
			}
		},
		getList() {
			/* 获取已贴标数据 */
			GetHasTagMaterialList().then((res) => {
				if (res.code === 0) {
					this.data = res.result
				}
			})
		},
		// 检索条件事件处理
		eventHandle(option) {
			switch (option._evnet) {
				case 'search':
					this.params.pageIndex = 1
					this.params.purchaseBillNo = option.key
					this.params.supplierShipState = option.supplierShipState
					this.gePurContractPage()
					break
				case 'add':
					this.formType = 'add'
					this.show = true
					break
				case 'back':
					this.$router.go(-1)
					break
				case 'download':
					window.open(
						'https://fzjx.oss-cn-hangzhou.aliyuncs.com/order/20211014/211014041759903892.xlsx'
					)
					break
				case 'ip':
					this.ipShow = true
					break
			}
		},
		/* 点击删除 出货后触发审批流操作 */
		approvalHandle() {
			this.getList()
		},
		changePage(pageIndex) {
			this.params.pageIndex = pageIndex
			this.gePurContractPage()
		},
		gePurContractPage() {
			GetPurContractPageList(this.params).then((res) => {
				if (res.code === 0) {
					this.purContractPageListData = res.result.list
					this.params.total = res.result.totalCount
				}
			})
		},
		unique(arr, val) {
			const res = new Map()
			return arr.filter(
				(item) => !res.has(item[val]) && res.set(item[val], 1)
			)
		},
		getScanList(rfidTagItems) {
			if(!rfidTagItems) return
			this.reading = false
			console.log(rfidTagItems)
			this.scanData.rfidTagItems = [
				...this.scanData.rfidTagItems,
				...rfidTagItems,
			]
			this.scanData.materialItems = [
				...this.scanData.materialItems,
			]
			this.scanData.rfidTagItems = this.unique(
				this.scanData.rfidTagItems,
				'rfid'
			)
			/* 临时删除的数据不可再添加到出入库列表中 */
			this.tempDelData.forEach((temp) => {
				for (const index in this.scanData.rfidTagItems) {
					if (
						temp.rfid ===
						this.scanData.rfidTagItems[index].rfid
					) {
						this.scanData.rfidTagItems.splice(index, 1)
					}
				}

				for (const index in this.scanData.materialItems) {
					if (
						temp.materialCode ===
						this.scanData.materialItems[index].materialCode
					) {
						this.scanData.materialItems.splice(index, 1)
					}
				}
			})
			this.materialItemsCopy = []
			for (
				let i = 0;
				i < this.scanData.rfidTagItems.length;
				i++
			) {
				const element = this.scanData.rfidTagItems[i]
				
				if (this.materialItemsCopy.length == 0) {
					this.materialItemsCopy.push({
						...element,
						tagCount: 1,
					})
				} else {
					var isTotal = false

					for (
						let j = 0;
						j < this.materialItemsCopy.length;
						j++
					) {
						const jelement = this.materialItemsCopy[j]
						if (
							element.materialCode ===
							jelement.materialCode
						) {
							isTotal = true
							jelement.tagCount++
							jelement.quantity += element.quantity
						}
					}
					if (!isTotal)
						this.materialItemsCopy.push({
							...element,
							tagCount: 1,
						})
				}
			}
			
			this.data.forEach((item) => {
				this.scanData.rfidTagItems.forEach((scan) => {
					if (item.rfid === scan.rfid) {
						item.checked = true
					}
				})
			})
		},
		socketInit() {
			const v = this
			window.ws = new WebSocket(
				'ws://120.79.80.64:8050/cloudApi/webStock/' + window.localStorage.getItem('jobNo')
				//'ws://192.168.1.97:8300/webStock/' + window.localStorage.getItem('token')
			)
			//申请一个WebSocket对象，参数是服务端地址，同http协议使用http://开头一样，WebSocket协议的url使用ws://开头，另外安全的WebSocket协议使用wss://开头
			window.ws.onopen = function () {
				//当WebSocket创建成功时，触发onopen事件
				console.log('open')
				
			}
			window.ws.onmessage = function (e) {
				//当客户端收到服务端发来的消息时，触发onmessage事件，参数e.data包含server传递过来的数据
				
				var msg = JSON.parse(e.data)
				if (msg.type == 1) {
					msg.data.instructions = 'in' + sessionStorage.getItem('plcCode')
					msg.data.businessType = 1
					// 仓库id： 一楼仓库'c185883dba22478cb593d33f6b66cc53' 四楼仓库'0b8f584250bb4b40b72d641ce4849d15'
					msg.data.stockHouseId = sessionStorage.getItem('plcCode') == 2 ? '0b8f584250bb4b40b72d641ce4849d15' : 'c185883dba22478cb593d33f6b66cc53',
					msg.data.type = 2
					msg.type = 2
					window.ws.send(JSON.stringify(msg))
				}
				if(msg.type == 3){
					console.log(msg.data.rfidData)
					v.getScanList(msg.data.rfidData)
				}
			}
			window.ws.onclose = function (e) {
				//当客户端收到服务端发送的关闭连接请求时，触发onclose事件
				console.log('close')
			}
			window.ws.onerror = function (e) {
				//如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
				console.log(error)
			}
		},
	},
	
	mounted() {
		this.gePurContractPage()
		this.socketInit()
		this.tempDelData = []
		this.getList()
		//this.getScanList()
		this.addTimer = setInterval(() => {
			this.percent += 1
			if (this.percent === 100) {
				clearInterval(this.addTimer)
				clearTimeout(this.overTimer)
				this.modal = false
			}
		}, 100)
		this.overTimer = setTimeout(() => {
			clearInterval(this.addTimer)
			this.percent = 100
			setTimeout(() => {
				this.modal = false
			}, 500)
		}, 3000)
	},
	destroyed() {},
	
}
</script>
<style>
.purContractPageList .table-filter,
.purContractPageList .table-page,
.purContractPageList .ivu-modal-footer,
.purContractPageList .ivu-modal-header {
	background: #fff;
}

.purContractPageList .table-content,
.purContractPageList .container {
	height: auto !important;
}
</style>
  <style lang="scss" scoped>
.container {
	width: 100vw;
	height: 100vh;
	overflow: auto;
	//background: rgba(2, 125, 180, 1);
	background-image: linear-gradient(
		270deg,
		#2c3034 0%,
		#50575e 49%,
		#2c3034 100%
	);
	.content {
		margin: 10px;
		height: calc(100% - 121.6px);
		overflow: hidden;
		box-sizing: border-box;
		//background: rgba(1, 84, 120, 1);
		border-radius: 10px;
		.reading {
			height: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 36px;
			font-weight: bold;
			color: #00ffff;
		}
		.title {
			padding-bottom: 10px;
			text-align: center;
			font-size: 36px;
			font-weight: bold;
			color: #2dc57c;
		}
		.main {
			height: calc(100% - 113.6px);
			display: flex;
			flex-direction: column;
			.list-wrap {
				flex: 2;
				overflow: hidden;
				padding: 0 10px;
				width: 100%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				.list {
					position: relative;
					//padding: 0 10px;
					flex: 1;
					height: 100%;
					overflow: hidden;
					//background: rgba(2, 125, 180, 0.486274509803922);
					background: #2c3034;
					border-radius: 4px;
					border: solid 1px #3879e7;
					.sub-title {
						position: relative;
						padding: 5px 0;
						font-size: 24px;
						color: #0077ff;
						font-weight: bold;
						.remark {
							position: absolute;
							right: 10px;
							top: 50%;
							transform: translateY(-50%);
							font-size: 16px;
							font-weight: normal;
							color: #0077ff;
						}
					}
					.row {
						padding: 5px 0;
						display: flex;
						justify-content: space-between;
						align-items: center;
						//background: rgba(2, 167, 240, 1);
						border-top: 1px solid #2655ad;
						//border-radius: 5px;
						&:last-child {
							border-bottom: 1px solid #2655ad;
						}
						.col {
							padding: 0 5px;
							display: flex;
							flex-direction: column;
							align-items: flex-start;
							justify-content: center;
							text-align: left;
							color: #ffffff;
						}
					}
					.total {
						padding: 5px 10px;
						//position: absolute;
						left: 0;
						bottom: 0;
						text-align: left;
						font-size: 20px;
						font-weight: bold;
						color: #f59a23;
						.top {
							font-size: 24px;
						}
						.label {
							margin-left: 40px;
							display: inline-block;
							width: 100px;
						}
					}
				}
			}
			.bottom {
				margin-top: 20px;
				flex: 1;
				.row {
					border: none !important;
				}
				.col {
					padding: 0 20px !important;
				}
			}
		}
		.footer {
			padding: 10px 0;
			padding-bottom: 0;
			/deep/ .ivu-btn-large {
				border-radius: 20px;
				font-weight: bold;
				width: 150px;
			}
		}
	}
}
/deep/.ivu-modal-content {
	background: #2c3034;
}
/deep/.ivu-modal-body {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0;
}
/deep/.remark-content {
	padding: 16px;
	width: 100%;
	.title {
		font-size: 24px;
		font-weight: bold;
		text-align: center;
		color: #ffffff;
		padding-bottom: 10px;
	}
	.btn {
		text-align: center;
		padding-top: 10px;
	}
}
/deep/ .ivu-modal-header {
	border-bottom: none;
}
/deep/ .ivu-modal-footer {
	border-top: none;
}
.scan-title {
	font-size: 18px;
	font-weight: bold;
	color: #ffffff;
}
.scan-btn {
	text-align: center;
}
.scan-content {
	padding: 10px 16px;
	width: 100%;
	max-height: 40vh;
	overflow: auto;
	background-color: #3d3d3d;
	color: #ffffff;
	.item {
		margin-bottom: 5px;
		border-bottom: 1px solid #ffffff;
		display: flex;
		justify-content: space-between;
		align-items: center;
		&:last-child {
			margin-bottom: 0;
			border-bottom: none;
		}
		.left {
			flex: 1;
			overflow: hidden;
		}
		.right {
			width: 60px;
			/deep/ .ivu-btn-primary {
				background-color: rgb(204, 228, 255);
			}
		}
		.row {
			margin-bottom: 5px;
			word-break: break-all;
		}
	}
}
</style>
  