<template>
	<view class="app-container">
		<uni-nav-bar class="bar-word" dark :fixed="true" shadow background-color="#007AFF" status-bar :title="title"
							:left-text="taskData.taskCode==null || taskData.taskCode=='' ? '任务' : taskData.taskCode" @clickLeft="handleReload" leftWidth="120px"
							:right-text="workstationName==null || workstationName=='' ? '工站' : workstationName" @clickRight="handleWork" rightWidth="120px"/>
		<view class="scan-header" style="z-index: auto;">
			<uni-forms-item  name="barCode" label="条码" :label-width="lableWidth" labelAlign="right" 
					style="margin-bottom: 0px; padding: 0px 15px 0px 15px;" >
				<uni-easyinput type="text" :inputBorder="true" v-model="barCode"
					:clearable="false" @confirm="scanSearch"></uni-easyinput>
				<view class="icon">
					<uni-icons type="scan" size="20"></uni-icons>
				</view>
			</uni-forms-item>
		</view>
		
		<view class="cpck-content" v-if="isPopupTask">
			<scroll-view scroll-top="0" :show-scrollbar="true" scroll-y="true" class="scroll-Y">
				<uni-card v-for="(item, index) in taskList" :key="index" @click="shiftTask(item)" :style="item.taskId===taskData.taskId ? 'background: #fffbc7;' : ''" style="margin: 0px 15px 15px 15px">
					<text class="uni-body" style="font-size: 16px;">
						<p><span class="titleV">任务编码：</span><span class="detailV">{{item.taskCode}}</span></p>
						<p><span class="titleV">产品编码：</span><span class="detailV">{{item.itemCode}}</span></p>
						<p><span class="titleV">产品名称：</span><span class="detailV">{{item.itemName}}</span></p>
						<p><span class="titleV">规格：</span><span class="detailV">{{item.specification}}</span></p>
						<p><span class="titleV">单位：</span><span class="detailV">{{item.unitOfMeasure}}</span></p>
						<p><span class="titleV">任务数量：</span><span class="detailV">{{item.quantity}}</span></p>
						<p><span class="titleV">生产数量：</span><span class="detailV">{{item.quantityProduced}}</span></p>
						<p><span class="titleV">良品数量：</span><span class="detailV">{{item.quantityQuanlify}}</span></p>
						<p><span class="titleV">不良数量：</span><span class="detailV">{{item.quantityUnquanlify}}</span></p>
						<p><span class="titleV">排产时间：</span><span class="detailV">{{item.startTime}}</span></p>
						<p><span class="titleV">需求日期：</span><span class="detailV">{{item.requestDate}}</span></p>
					</text>
				</uni-card>
			</scroll-view>
			<view class="page-bottom">
				<view class="p-b-btn" @click="changeStatus('START')" v-if="taskData.status =='NORMAL'">
					<text class="box-text">开始</text> 
				</view> 
				<view class="p-b-btn" @click="changeStatus('PAUSE')" v-else-if="taskData.status =='START'">
					<text class="box-text">暂停</text> 
				</view> 
				<view class="p-b-btn" @click="changeStatus('START')" v-else-if="taskData.status =='PAUSE'">
					<text class="box-text">继续</text> 
				</view> 
				<view class="p-b-btn" v-else></view>
				
				<view class="p-b-btn" @click="changeStatus('FINISHED')" v-if="taskData.status!=null && taskData.status!=''">
					<text class="box-text">完成</text> 
				</view> 
				<view class="p-b-btn" v-else></view>
				
				<view class="p-b-btn" @click="doFeedback" v-if="taskData.status!=null && taskData.status!=''">
					<text class="box-text">报工</text> 
				</view> 
				<view class="p-b-btn" v-else></view>
				
				<view class="p-b-btn" @click="handleBack">
					<text class="box-text">返回</text> 
				</view> 
			</view>
		</view>
		
		<view class="cpck-content" v-if="!isPopupTask">
			<scroll-view scroll-top="0" :show-scrollbar="true" scroll-y="true" class="scroll-Y">
				<uni-card v-for="(item, index) in itemList" :key="index" @click="shiftItem(item)" :style="item.recordId===itemData.recordId ? 'background: #fffbc7;' : ''" style="margin: 0px 15px 15px 15px">
					<text class="uni-body" style="font-size: 16px;">
						<p><span class="titleV">物料编码：</span><span class="detailV">{{item.itemCode}}</span></p>
						<p><span class="titleV">物料名称：</span><span class="detailV">{{item.itemName}}</span></p>
						<p><span class="titleV">规格型号：</span><span class="detailV">{{item.specification}}</span></p>
						<p><span class="titleV">单位：</span><span class="detailV">{{item.unitOfMeasure}}</span></p>
						<p><span class="titleV">可用数量：</span>
							<uni-easyinput v-if="isEditItemQty && item.recordId===itemData.recordId" type="number" :inputBorder="true"
								v-model="editItemQty" focus @change="handleEditItemQty(editItemQty,item)"></uni-easyinput>
							<span class="detailV" v-else>{{item.quantityAvailable}}</span>
						</p>
					</text>
				</uni-card>
			</scroll-view>
			<view class="page-bottom">
				<view class="p-b-btn" @click="handleRemove" v-if="Object.keys(taskData).length !== 0">
					<text class="box-text">移除</text> 
				</view> 
				<view class="p-b-btn" v-else></view>
				
				<view class="p-b-btn" @click="handleConsume" v-if="Object.keys(taskData).length !== 0">
					<text class="box-text">消耗</text> 
				</view> 
				<view class="p-b-btn" v-else></view>
				
				<view class="p-b-btn"></view>
				
				<view class="p-b-btn" @click="handleBack">
					<text class="box-text">返回</text> 
				</view> 
			</view>
		</view>
			
		<uni-popup ref="popup" type="top" :animation="true" style="" background-color="#ffffff">
			<div style="height:50px"/>
			<uni-forms-item  name="process" label="工序" :label-width="lableWidth" style="margin:5px;width:300px"  labelAlign="right">
				<uni-data-select
					v-model="processCode"
					:localdata="processList"
					@change="changeProcess"
				></uni-data-select>
			</uni-forms-item>
			<uni-forms-item  name="workstation" label="工作站" :label-width="lableWidth" style="margin:5px;width:300px"  labelAlign="right">
				<uni-data-select
					v-model="workstationCode"
					:localdata="workstationList"
					@change="changeWorksta"
				></uni-data-select>
			</uni-forms-item>
		</uni-popup>
		
		<uni-popup ref="feedbackPopup" type="top" :animation="true" background-color="#ffffff">
			<uni-forms-item name="stockQty" label="合格品数" :label-width="lableWidth" labelAlign="right">
				<uni-easyinput type="number" :inputBorder="true"
					v-model="feedbackForm.quantityQualify" @input="bqslInputHandle" ></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="stockQty" label="不良品数" :label-width="lableWidth" labelAlign="right">
				<uni-easyinput type="number" :inputBorder="true"
					v-model="feedbackForm.quantityUnqualify" @input="bqslInputHandle" ></uni-easyinput>
			</uni-forms-item>
			<button type="primary" plain="true" @click="handlefeedback">确定</button>
		</uni-popup>

		<uni-popup ref="consumeFormPopup" type="top" :animation="true" background-color="#ffffff">
			<uni-forms-item name="stockQty" label="消耗数量" :label-width="lableWidth" labelAlign="right">
				<uni-easyinput type="number" :inputBorder="true"
					v-model="consumeForm.quantityConsumed" @input="bqslInputHandle" ></uni-easyinput>
			</uni-forms-item>
			<button type="primary" plain="true" @click="handleConsumeForm">确定</button>
		</uni-popup>

	</view>
</template>

<script>
	import { processList,workstationList,taskList,changeTaskStatus,feedback,addIssue,updateIssue,taskIssueList,removeTaskIssue,consumeTaskIssue,getMaterial } from '@/api/mes/pro.js'
	export default {
		onLoad(option) {
			this.processName = uni.getStorageSync('processName');
			this.processCode = uni.getStorageSync('processCode');
			this.processId = uni.getStorageSync('processId');
			this.workstationName = uni.getStorageSync('workstationName');
			this.workstationCode = uni.getStorageSync('workstationCode');
			this.workstationId = uni.getStorageSync('workstationId');
			//进入加载任务
			this.getTaskList()
		},
		data() {
			return {
				title:"生产",
				lableWidth:"80px",
				barCode:'',//条码值
				//切换工作站
				showWorkstationFlag:false,
				processName:null,//当前工序
				processCode:null,
				processId:null,//当前工序id
				workstationName:null,//当前工作站
				workstationCode:null,//
				workstationId:null,//当前工作站id
				processList: [], //工序清单
				workstationList: [], //工作站清单
				currentFlag: 0,
				//任务卡片
				taskList: [],
				taskData:{},//选中的任务
				taskId:null,//任务id
				//报工
				feedbackForm:{quantityQualify:0,quantityUnqualify:0},
				//投料卡片
				itemList: [],//投料清单
				itemData:{},//选中的投料
				isEditItemQty:false,//当前卡片是否修改数量
				editItemQty:0,//修改数量
				//消耗弹窗
				consumeForm: {quantityConsumed:0},
				//显示任务还是投料
				isPopupTask: true,
			}
		},
		methods: {
			//刷新按钮
			handleReload(){
				this.getTaskList();
				this.isPopupTask=true;
				uni.showToast({
					title: '刷新成功',
					icon: 'none',
					duration: 1500
				});
			},
			handleWork(){
				//查询工序
				processList().then(res => {
					if(res.code === 200){
						this.processList = res.data.map(item => ({
							value: item.processCode,
							text: item.processName,
							id: item.processId
						}));
						//显示工站弹出窗
						this.$refs.popup.open('top')
					}
				});
				//如果有工序id，查询工作站
				if(this.processId !== null && this.processId !== ''){
					//查询工作站
					this.getWorkstationList();
				}
			},
			//工序变更，获取工作站
			changeProcess() {
				//赋值工序id
				let process = this.processList.find(item => item.value === this.processCode)
				this.processName = process==null ? null:process.text;
				this.processId = process==null ? null:process.id;
				uni.setStorageSync('processName', this.processName);
				uni.setStorageSync('processCode', this.processCode);
				uni.setStorageSync('processId', this.processId);
				//查询工作站
				this.getWorkstationList();
				//清空工作站
				this.workstationName=null
				this.workstationCode=null
				this.workstationId=null
				uni.setStorageSync('workstationName', '');
				uni.setStorageSync('workstationCode', '');
				uni.setStorageSync('workstationId', '');
			},
			//查询工作站
			getWorkstationList(){
				workstationList({processCode: this.processCode}).then(res => {
					if(res.code === 200){
						this.workstationList = res.data.map(item => ({
							value: item.workstationCode,
							text: item.workstationName,
							id: item.workstationId
						}));
					}
				});
			},
			//工作站变更
			changeWorksta(){
				let workstation = this.workstationList.find(item => item.value === this.workstationCode)
				this.workstationName = workstation==null ? null:workstation.text;
				this.workstationId = workstation==null ? null:workstation.id;
				uni.setStorageSync('workstationName', this.workstationName);
				uni.setStorageSync('workstationCode', this.workstationCode);
				uni.setStorageSync('workstationId', this.workstationId);
				//查询任务
				this.getTaskList();
			},
			
			
			//生产-任务卡片相关-----------------------
			//查询任务列表
			getTaskList() {
				taskList({workstationId: this.workstationId}).then(res => {
					if(res.code === 200){
						this.taskList = res.rows;
					}
				});
			},
			//选中任务
			shiftTask(task){
				if(task.taskId == this.taskData.taskId){
					this.isPopupTask = false
					return true
				}
				this.taskData = task
				this.taskId = task.taskId
				this.getIssueList()
				this.itemData={}
			},
			//状态按钮
			changeStatus(status) {
				this.taskData.status = status;
				let params = {
					taskId: this.taskData.taskId,
					taskCode: this.taskData.taskCode,
					workstationId: this.workstationId,
					workstationCode: this.workstationCode,
					workstationName: this.workstationName,
					status: status
				};
				changeTaskStatus(params).then(res => {
					if (res.code == '200') {
						uni.showToast({
							title: '变更成功',
							icon: 'none'
						});
						this.getTaskList();//刷新任务
						//清空选中任务
						if(status=='FINISHED'){
							this.taskData={};
						}
					}
				});
			},
			//生产报工按钮
			doFeedback() {
				this.$refs.feedbackPopup.open('bottom')
			},
			
			//工序-投料卡片相关-----------------------
			//选中投料清单
			shiftItem(item){
				if(item.recordId == this.itemData.recordId){
					this.editItemQty = item.quantityAvailable;
					this.isEditItemQty=true
				}else{
					this.editItemQty = 0;
					this.isEditItemQty=false
				}
				this.itemData = item
			},
			//添加领料单的某行到当前的投料清单
			handleAdd(row) {
				let params = {
					taskId: this.taskId,
					workstationId: this.workstationId,
					//孙一石 工站id修改
					sourceDocId: row.sourceDocId,
					sourceDocType: 'ISSUE',
					sourceLineId: row.sourceLineId,
					itemCode: row.itemCode,
					itemName: row.itemName,
					unitOfMeasure: row.unitOfMeasure,
					batchCode: row.batchCode,
					quantityIssued: row.quantityIssued,
					quantityAvailable: row.quantityIssued
				}

				addIssue(params).then(res => {
					if(res.code === 200){
						this.getIssueList();
						uni.showToast({
							title: '操作成功',
							icon:'none',
							duration: 1500
						})
					}
				});
			},
			
			// 从投料清单中删除一条
			handleRemove() {
			  let item = this.itemData;
				removeTaskIssue({recordId: item.recordId}).then(res => {
					if(res.code === 200){
						this.getIssueList();
						uni.showToast({
							title: '操作成功',
							icon:'none',
							duration: 1500
						})
					}
				});
			},
			
			// 从投料清单中消耗数量
			handleConsume() {
			  let item = this.itemData;
			  this.consumeForm.itemName = item.itemName
			  this.consumeForm.itemCode = item.itemCode
			  this.consumeForm.unitOfMeasure = item.unitOfMeasure
			  this.consumeForm.quantityConsumed = item.quantityAvailable
			  this.consumeForm.sourceDocId = item.sourceDocId
			  this.consumeForm.sourceLineId = item.sourceLineId
			  this.consumeForm.taskId = item.taskId
			  this.consumeForm.workstationId = item.workstationId
			  this.consumeForm.sourceBatchCode = item.batchCode
				this.$refs.consumeFormPopup.open('bottom')
			},
			//添加消耗
			handleConsumeForm(){
				let params= {
					sourceDocId: this.consumeForm.sourceDocId,
					sourceLineId: this.consumeForm.sourceLineId,
					itemName: this.consumeForm.itemName,
					itemCode: this.consumeForm.itemCode,
					unitOfMeasure: this.consumeForm.unitOfMeasure,
					quantityConsumed: this.consumeForm.quantityConsumed,
					taskId: this.consumeForm.taskId,
					workstationId: this.consumeForm.workstationId,
					sourceBatchCode: this.consumeForm.sourceBatchCode
				}
				this.isEditItemQty=false;
				consumeTaskIssue(params).then(res => {
					if(res.code === 200){
						this.getIssueList();
						uni.showToast({
							title: '操作成功',
							icon:'none',
							duration: 1500
						})
					}
				});
			},
			//获取当前工作台、当前生产任务的投料清单
			getIssueList() {
				taskIssueList({workstationId:this.workstationId}).then(res => {
					if(res.code === 200){
						this.itemList = res.data;
					}
				});
			},
			
			// 条码框 回车
			scanSearch(remark){
				this.getDataByRemark(remark);
			},
			
			//扫码
			getDataByRemark(remark){
				remark = remark.replace(/^\s+|\s+$/g, '');
				let parts = remark.split("|");

				let splitPre = parts[0];
				let splitLast = parts[1];
				let splitLast2 = parts.length > 2 ? parts[2] : null;
				
				// 条码空 不执行
				if(splitLast == ""){
					return true;
				}
				// 扫码
				switch (splitPre){
					case "m": //物料
						this.getScanWlList(splitLast,splitLast2);
						break;
					default:
						uni.showToast({
							title: "条码不合法",
							icon: "none"
						})
						break;
				}
			},
			
			//物料扫码
			getScanWlList(barCode,barCode2){
				let that = this;
				// 物料网络请求
				getMaterial(barCode).then(res => {
					if(res.code === 200){
						let data = res.data;
						if(data && Object.keys(data).length !== 0){
							let row = {
								sourceDocType: 'ISSUE',
								itemCode: data.materialCode,
								itemName: data.materialName,
								unitOfMeasure: data.materialSpecification,
								batchCode: barCode2,
								quantityIssued: 10,
								quantityAvailable: 10,
								sourceDocId:0,
							}
						console.log(row)
							this.handleAdd(row)
						}else{
							uni.showToast({
								title: "物料编码无效",
								icon: "none"
							})
						}
					}
				});
			},
			
			//返回按钮
			handleBack(){
				uni.showModal({
					title: '提示',
					content: '确认返回?',
					success: function (res) {
						if (res.confirm) {
							uni.navigateBack();
						} else if (res.cancel) {
						
						}
					}
				});
			},
			//提交按钮
			handlefeedback(){
				//汇总数量
				let quantityQualify = this.feedbackForm.quantityQualify==null || this.feedbackForm.quantityQualify=='' ? 0:this.feedbackForm.quantityQualify
				let quantityUnqualify = this.feedbackForm.quantityUnqualify==null || this.feedbackForm.quantityUnqualify=='' ? 0:this.feedbackForm.quantityUnqualify
				let quantity = 0 + parseFloat(quantityQualify) + parseFloat(quantityUnqualify);
				if(quantityQualify<0 || quantityUnqualify<0){
					uni.showToast({
						title: "数量有误！",
						icon: 'none'
					});
					return true;
				}
				if(quantity===0){
					uni.showToast({
						title: "请输入合格品数量或者不良品数量！",
						icon: 'none'
					});
					return true;
				}
				
				let userName = uni.getStorageSync('u1')
				let nickName = uni.getStorageSync('name')
				let params = {
					taskId: this.taskData.taskId,
					quantityFeedback: quantity,
					quantityQualified: quantityQualify,
					quantityUnquanlified: quantityUnqualify,
					userName: userName,
					nickName: nickName,

					// 报工类型  : UNI  SELF
					feedbackType: 'SELF',

					//工序
					processId: this.processId,
					processName: this.processName,
					itemId: this.taskData.itemId,
					itemName: this.taskData.itemName,
					itemCode: this.taskData.itemCode
				}
				
				feedback(params).then(res => {
					if(res.code === 200){
						uni.showToast({
							title: '上报成功',
							icon: 'none'
						});
					}
					this.getTaskList();
				});
			},
			//数量输入完成校验
			bqslInputHandle(value){ 
				if(value < 0){
					uni.showToast({
						title: "数量有误",
						icon: "none"
					})
					return;
				}
			},
			//投料数量输入框
			handleEditItemQty(value,item) {
				if(value < 0){
					uni.showToast({
						title: "数量有误",
						icon: "none"
					})
					return;
				}else{
					//获取数量差，用差修改两个数量
					let qty = this.editItemQty - item.quantityAvailable
					if(qty===0){
						return true
					}
					//修改
					let params={};
					params.recordId = this.itemData.recordId
					params.quantityIssued = item.quantityIssued + parseFloat(qty)
					params.quantityAvailable = item.quantityAvailable + parseFloat(qty)
					updateIssue(params).then(res => {
						if(res.code === 200){
							this.getIssueList();
							uni.showToast({
								title: '操作成功',
								icon:'none',
								duration: 1500
							})
						}
					});
				}
			},
		}
	}
</script>

<style>
	@import "@/static/scss/stock.css";
	::v-deep .uni-nav-bar-text,::v-deep .uni-nav-bar-right-text,::v-deep .uni-nav-bar-left-text{
			font-size: 16px;    
		}
/* 	::v-deep .bar-word .uni-navbar__header-btns .uni-navbar-btn-icon-right uni-text{
		font-size: 16px!important;
	} */
	::v-deep .bar-word .uni-navbar__header-btns .uni-navbar-btn-icon-left uni-text{
		font-size: 16px!important;
	}
</style>

<!-- uni-navbar-btn-text uni-navbar-btn-icon-left -->
