<template>
	<view>
		<div class="head">
			<table>
				<tr>
					<td colspan='2'>
						<uni-easyinput type="text" prefixIcon="scan"
							placeholder="请扫描作业!" 
							v-model="machineCode"
							@iconClick="iconClick('machineCode')"
							@change="changeInput('machineCode',$event)"
						/>
					</td>
				</tr>
				<tr>
					<td>作业编码：{{form.pwoJobCode}}</td>
				</tr>
				<tr>
					<td>制&emsp;&emsp;程：{{form.opTitle}}</td>
				</tr>
				<tr>
					<td>物料编码：{{form.pwoCode}}</td>
				</tr>
				<tr>
					<td>物料名称：{{form.ptTitleTar}}</td>
				</tr>
			</table>
			<div @click="clickButton('qualified')" :class="{bgColor:bgColor === 'qualified'}">合格</div>
			<div @click="clickButton('bad')" :class="{bgColor:bgColor === 'bad'}">不良</div>
			<div @click="clickButton('scrap')" :class="{bgColor:bgColor === 'scrap'}">报废</div>
			<view class="uni-px-5 uni-pb-5" v-show="bgColor === 'bad'">
				<uni-data-checkbox mode="button" v-model="form.reason" :localdata="reason.bad"></uni-data-checkbox>
			</view>
			<view class="uni-px-5 uni-pb-5" v-show="bgColor === 'scrap'">
				<uni-data-checkbox mode="button" v-model="form.reason" :localdata="reason.scrap"></uni-data-checkbox>
			</view>
		</div>
		<div class="body">
			<uni-easyinput type="text" prefixIcon="scan"
				placeholder="请扫描件号!" 
				v-model="pieceNo"
				@iconClick="iconClick('pieceNo')"
				@change="changeInput('pieceNo',$event)"
			/>
			<uni-table ref="table"  border  stripe>
				<uni-tr>
					<uni-th align="center">序号</uni-th>
					<uni-th style="width: 80%"align="center">件号</uni-th>
				</uni-tr>
				<uni-tr v-for="(item, index) in pieceNoList" :key="index">
					<uni-td align="center">{{ index+1 }}</uni-td>
					<uni-td align="center"> {{item}} </uni-td>
				</uni-tr>
			</uni-table>
		</div>
		
		
		<uni-popup ref="message" type="message">
			<uni-popup-message :type="message.msgType" :message="message.messageText" :duration="2000"></uni-popup-message>
		</uni-popup>
		<uni-popup ref="popup" type="center" background-color="#fff" :is-mask-click="false">
			<!-- 加载动画 -->
			<loding-vue/>
		</uni-popup>
	</view>
</template>

<script>
	import {
		listPwoJob
	} from '@/api/mes/jobReport.js'
	import {
		getDicts
	} from '@/api/system/dict/dictData.js'
	import {
		addReport,listEquipment
	} from '@/api/mes/jobReport.js'
	//引入加载动画
	import lodingVue from "@/utils/loding/loding.vue";
	export default {
		components:{
			lodingVue
		},
		//页面加载生命周期
		onLoad: async function (option) { //option为object类型，会序列化上个页面传递的参数
			const _self = this;
			if(option.status) _self.state = true
		},
		data() {
			return {
				machineCode: null , //扫描作业
				isPieceIn: true, //判断哪个路由进来
				form:{
				}, //头部展示数据
				message:{
					msgType:'warn',
					messageText:'请先查询设备信息'
				},
				bgColor: null,//决定按钮颜色
				reason:{},//不良以及报废原因
				pieceNo:null,//件号
				pieceNoList:new Set(), //table展示数据
				listEquipment:[],//设备信息
			}
		},
		/**
		 * vue生命周期
		 * 当组件挂载后触发
		 */
		async mounted() {
			const _self = this;
			const data = await Promise.all([
				//获取不良品原因
				_self.getApi('getDicts','mes_job_report_defect'),
				//报废品
				_self.getApi('getDicts','mes_job_report_scrap'),
				_self.getApi('listEquipment')
			])
			const [bad,scrap,listEquipment] = data
			bad.forEach(item=>{
				item.text = item.dictLabel,
				item.value = item.dictValue
			});
			scrap.forEach(item=>{
				item.text = item.dictLabel,
				item.value = item.dictValue
			})
			_self.listEquipment = listEquipment
			_self.reason = Object.assign({},{bad,scrap})
		},	
		methods: {
			/**
			 * 扫码方法
			 * @param {string} value {'equipment' ||  }
			 */
			iconClick(value){
				const _this = this;
				uni.scanCode({
					// 是否只能从相机扫码，不允许从相册选择图片
					onlyFromCamera:true,
					// 扫码类型
					scanType: ['barCode', 'qrCode'],
					success: function(res) {
						const obj = {
							machineCode:getMachineCode,
							pieceNo:getPieceNo,
						}
						_self.obj(value)(res.result)
					}
				})
			},
			/**
			 * input框change事件
			 * @param {string} key
			 * @param {Object} value
			 */
			changeInput(key,value){
				if(value === null || value === '') return
				const _self = this;
				const obj = {
					machineCode : 'getMachineCode',
					pieceNo: 'getPieceNo',
				}
				_self[obj[key]](value)
			},
			/**
			 * 扫描作业方法
			 * @param {Object} value
			 */
			async getMachineCode(value){
				if(value === null) return
				const _self = this;
				//清空数据
				_self.bgColo =null;
				_self.pieceNoList = new Set();
				
				const rows = await _self.getApi('listPwoJob',{code:value})
				if(rows.length != 0){
					const {code : pwoJobCode,opTitle,pwoCode,ptTitleTar,ptNoTar,opCode,batchNo,eqpId} = rows[0]
					_self.form = Object.assign({},{
						pwoJobCode,opTitle,pwoCode,ptTitleTar,ptNoTar,opCode,batchNo,
						isPieceIn:_self.state
					})
					//获取设备信息，并选择该作业的设备
					const listEquipment = _self.listEquipment
					for(let i in listEquipment){
						if(listEquipment[i].id === eqpId)return _self.form.machineId = listEquipment[i].equipmentCode
					}
				}
			},
			/**
			 * 扫描件号方法
			 * @param {Object} value
			 */
			async getPieceNo(value){
				const _self = this;
				_self.pieceNo = null
				if(_self.form.reason === null && _self.form.type != '合格品'){
					_self.messageType({
						msgType:'warn',
						messageText:'请选择一个问题'
					})
					return 
				}
				const pieceNoList = _self.pieceNoList
				if(pieceNoList.has(value)){
					_self.messageType({
						msgType:'error',
						messageText:'该件号已被扫描'
					})
					return 
				}
				_self.submit(value).then(res=>{
					if(res != undefined) return pieceNoList.add(value)
				}).finally(()=>{
				})
			},
			/**
			 * 按钮点击方法
			 * @param {Object} key
			 * @param {Object} evnet
			 */
			clickButton(key){
				const _self = this;
				_self.clickState(key)
			},
			/**
			 * 产品状态按钮点击事件
			 * @param {Object} key
			 */
			clickState(key){
				const _self = this;
				_self.bgColor = key
				const obj = {
					qualified:'合格品',
					bad:'不良品',
					scrap:'报废'
				}
				_self.form.reason = null
				_self.form.type = obj[key]
			},
			/**
			 * 件号扫描后提交事件
			 * @param {Object} value 当前扫描的值
			 */
			async submit(pieceNo){
				const _self = this;
				// 获取当前北京时间的时间戳（单位为毫秒）
				var stamp= new Date().getTime() + 8 * 60 * 60 * 1000;
				var endTime = new Date(stamp).toISOString().replace(/T/, ' ').replace(/\..+/, '').substring(0, 19);
				//获取账户名
				const createByName = uni.getStorageSync('HBusername');
				const reportNumber = 1;
				const way = "人工报工";
				const form = Object.assign(_self.form,{
					endTime,createByName,reportNumber,way,pieceNo
				})
				return await _self.getApi('addReport',form)
			},
			/**
			 * 接口调用管理方法
			 * 所有向后端发送的请求全部从这里调用
			 * @param {Object} api api接口
			 * @param {Object} value 带入的参数
			 */
			async getApi(api,value){
				const _self = this;
				const objApi = {
					listPwoJob,
					getDicts,
					addReport,
					listEquipment
				}
				try{
					//打开蒙层
					_self.$refs.popup.open()
					//查询接口
					const data = await objApi[api](value)
					if(api === 'addReport'){
						return data
					}
					return data.rows ? data.rows : data.data 
				}catch(e){
					_self.messageType({
						msgType:'error',
						messageText:'接口请求出错'
					})
				}finally{
					//关闭蒙层
					_self.$refs.popup.close()
				}
			},
			/**
			 * 提示信息
			 * @param {Object} obj
			 */
			messageType(obj){
				const _self = this;
				let message ={}
				if(obj === undefined){
					message = {
						msgType:'error',
						messageText:'请填写设备代码'
					}	
				}else{
					message = {
						msgType:obj.msgType,
						messageText:obj.messageText
					}
				}
				_self.message = Object.assign({},message)
				return _self.$refs.message.open()
			},
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #ffffff;
		color: #585858;
		font-size: 4vw;
	}
	view {
		width: 95vw;
		margin: 0 auto;
	}
	.head {
		display: flex;
		justify-content: space-between;
		flex-wrap:  wrap;
		table{
			width: 100%;
		}
		&>div{
			border: 1vw solid #21cfff;
			border-radius: 20%;
			width: 20vw;
			text-align:center;
			line-height: 8vw;
		}
	}
	.body{
		margin-top: 1vw;
		&>* {
			margin-top: 2vw;
		}
		.td{
			text-align:center;
		}
	}
	.bgColor {
		background-color: #c4ffd0;
	}
</style>
