<template>
	<view class="page">

		<view class="mt">
			<view v-for="(item,index) in itemList" :key="index" class="example-box mt">
				<view class="item">
					<view class="itemname">检验明细{{index+1}}</view>
					<view class="itemtext" style="color:#007aff;" @click="deleteItem(index)">
						<uni-icons type="trash" class="myarrowright" style="right:56upx; font-size: 36upx;color:#007aff;"></uni-icons>删除
					</view>
				</view>
				<view class="item">
					<view class="itemname">不良原因</view>
					<view class="itemtext">
						<input class="iteminput" placeholder="请选择" @click='selectPoor(index)' :value="item.poorName" />
					</view>
				</view>
				<view class="item">
					<view class="itemname">不良数量</view>
					<view class="itemtext">
						<input type="number" class="iteminput" placeholder="请输入不良数量" v-model="item.rejectsCount" @change='toFixed1(index)' />
					</view>
				</view>
				<view class="item" v-if="item.old">
					<view class="itemname redMi">检验项目</view>
					<view class="itemtext">
						<input class="iteminput" disabled v-model="item.project" />
					</view>
				</view>
				<view class="item" v-else>
					<view class="itemname">检验项目</view>
					<view class="itemtext">
						<input class="iteminput" placeholder="请选择" disabled @click='selectCheck(index)' :value="item.project" />
					</view>
				</view>
				<view class="item">
					<view class="itemname">检验方法</view>
					<view class="itemtext">
						<input class="iteminput" disabled v-model="item.method" />
					</view>
				</view>
				<view class="item" v-if="item.old">
					<view class="itemname">是否必检</view>
					<view class="itemtext">
						{{item.whetherCheck==1?'是':'否'}}
					</view>
				</view>
				<view class="item" v-else>
					<view class="itemname">是否必检</view>
					<view class="itemtext">
						<checkbox-group @change="checkboxChange($event,index)">
							<checkbox value="1" :checked="item.whetherCheck==1" />
						</checkbox-group>
					</view>
				</view>

				<view class="item">
					<view class="itemname">单位</view>
					<view class="itemtext">
						<input class="iteminput" placeholder="请输入单位" v-model="item.unit" @change='dataChange' />
					</view>
				</view>
				<view class="item">
					<view class="itemname">目标值</view>
					<view class="itemtext">
						<input type="number" class="iteminput" placeholder="请输入目标值" v-model="item.normn" @change='dataChange' />
					</view>
				</view>
				<view class="item">
					<view class="itemname">实际检验值</view>
					<view class="itemtext">
						<input type="number" class="iteminput" placeholder="请输入实际检验值" v-model="item.actualValue" @change='dataChange' />
					</view>
				</view>
				<view class="item">
					<view class="itemname redMi">检验结果</view>
					<view class="itemtext">
						<input class="iteminput InputRightMargin" disabled placeholder="请选择" @click="showSinglePicker(index)" v-model="item.result" />
						<uni-icons type="arrowright" class="myarrowright" style="right: 0px;"></uni-icons>
					</view>
				</view>
				<view class="item">
					<view class="itemname">处理方式</view>
					<view class="itemtext">
						<input class="iteminput InputRightMargin" disabled placeholder="请选择" @click="showSinglePickerType(index)" v-model="item.dispose" />
						<uni-icons type="arrowright" class="myarrowright" style="right: 0px;"></uni-icons>
					</view>
				</view>
			</view>
		</view>

		<view class="fixMargin"></view>
		<view class="fixBottom">
			<view class="uni-flex uni-row">
				<view style="-webkit-flex:1;flex: 1;">
					<button type="primary" plain="true" style="width: 90%; background: #fff;" @click="goProcessCheckout">取消</button>
				</view>
				<view style="-webkit-flex:1;flex: 1;">
					<button type="primary" style="width: 90%;" @click="save">提交</button>
				</view>
			</view>
		</view>
		<mpvue-picker themeColor="#007AFF" ref="mpvuePicker" mode="selector" :deepLength="deepLength" @onConfirm="pickerConfirm"
		 :pickerValueArray="check_type"></mpvue-picker>
		<mpvue-picker themeColor="#007AFF" ref="mpvuePicker2" mode="selector" :deepLength="deepLength" @onConfirm="pickerConfirmType"
		 :pickerValueArray="process_type"></mpvue-picker>
		<view class="goHome" @click='goMain()'>
			<img src="../../static/img/gohome.png">
		</view>
		<view class="mysearchlist" style="z-index: 10000;">
			<choosePoorSingle ref="mysearchlist" 
				:showsearch.sync="show_search_user"
				:itemInfo_.sync="search_value_user">
			</choosePoorSingle>
		</view>
		<view class="mysearchlist" style="z-index: 10000;">
			<chooseProjectSingle ref="mysearchlist" 
				:showsearch.sync="show_search_user2"
				:itemInfo_.sync="search_value_user2">
			</chooseProjectSingle>
		</view>
	</view>
</template>

<script>
	import uniIcons from '@/components/uni-icons/uni-icons.vue';
	import mpvuePicker from '@/components/mpvue-picker/mpvuePicker.vue';
	import mpvuePicker1 from '@/components/mpvue-picker/mpvuePicker.vue';
	import choosePoorSingle from '@/components/xinsoft-search-list/choosePoorSingle.vue';
	import chooseProjectSingle from '@/components/xinsoft-search-list/chooseProjectSingle.vue';
	export default {
		components: {
			uniIcons,
			mpvuePicker,
			choosePoorSingle,
			chooseProjectSingle
		},
		data() {
			return {
				showPicker: false,
				deepLength: 1,
				check_type: [],
				process_type: [],
				reportId: '',
				code: '',
				processName: '',
				checkPlanName: '',
				checkPlanId: '',
				supplierName: '',
				supplierId: '',
				materielName: '',
				materielId: '',
				reworkCount: '',
				checkCount: '',
				scrapCount: '',
				conformityCount: '',
				conformityCountSupport:'',
				reworkCountSupport:"",
				scrapCountSupport:"",
				checkCountSupport:'',
				info: {},
				itemList: [],
				deletDetailIds: [],
				currentIndex: 0,
				processDetail: [],
				show_search_user:false,
				search_value_user:"",
				show_search_user2:false,
				search_value_user2:"",
				result: '',
				quantityAccuracy:"",
			}
		},
		onLoad(option) {
			this.reportId = option.reportId
			this.conformityCount = option.conformityCount
			this.reworkCount = option.reworkCount
			this.scrapCount = option.scrapCount
			this.conformityCountSupport = option.conformityCountSupport
			this.reworkCountSupport = option.reworkCountSupport
			this.scrapCountSupport = option.scrapCountSupport
			this.checkCountSupport = option.checkCountSupport
			var processCheckoutInfo = uni.getStorageSync('processCheckoutInfo');
			if (processCheckoutInfo != '' && processCheckoutInfo != undefined) {
				this.itemList = processCheckoutInfo;
			}
			this.getReport();
			//初始化获取 检验结果
			var _this = this;
			this.$http.request({
				url: '/apis/dict/getDictsByType',
				params: {
					type: 'check_result'
				},
			}).then(res => {
				if (res.statusCode == '200') {
					var useType = res.data.datas;
					for (let i = 0; i < useType.length; i++) {
						var myVal = {
							'label': useType[i].name,
							'value': useType[i].id
						}
						_this.check_type.push(myVal);
					}
				}
			}).catch(err => {
				console.log(err);
			});
			//初始化获取 处理方式
			var _this = this;
			this.$http.request({
				url: '/apis/dict/getDictsByType',
				params: {
					type: 'process_mode'
				},
			}).then(res => {
				if (res.statusCode == '200') {
					var useType = res.data.datas;
					for (let i = 0; i < useType.length; i++) {
						var myVal = {
							'label': useType[i].name,
							'value': useType[i].id
						}
						_this.process_type.push(myVal);
					}
				}
			}).catch(err => {
				console.log(err);
			});
		},
		watch: {
			search_value_user(newv){
				this.$set(this.itemList[this.currentIndex],'poorId',newv.id);
				this.$set(this.itemList[this.currentIndex],'poorName',newv.name);
				uni.removeStorageSync('processCheckoutInfo');							
				uni.setStorage({
					key: 'processCheckoutInfo',
					data: this.itemList,
					success: function () {

					}
				});		
			},
			search_value_user2(newv){
				this.$set(this.itemList[this.currentIndex],'projectId',newv.id);
				this.$set(this.itemList[this.currentIndex],'project',newv.name);
				this.$set(this.itemList[this.currentIndex],'method',newv.method);
				uni.removeStorageSync('processCheckoutInfo');							
				uni.setStorage({
					key: 'processCheckoutInfo',
					data: this.itemList,
					success: function () {

					}
				});		
			},
		},
		methods: {
			toFixed1(index) {
				this.$set(this.itemList[index],'rejectsCount',Number(this.itemList[index].rejectsCount).toFixed(this.quantityAccuracy))
				//保存检验明细当前修改信息
				var processCheckoutInfo = uni.getStorageSync('processCheckoutInfo');
				if (!processCheckoutInfo) {
					processCheckoutInfo = {}
				}
				processCheckoutInfo = this.itemList;
				uni.setStorage({
					key: 'processCheckoutInfo',
					data: processCheckoutInfo,
					success: function() {

					}
				});
			},

			//是否检验
			checkboxChange(e, index) {
				if (e.detail.value.length == 0) {
					this.$set(this.itemList[index], 'whetherCheck', 0)
				} else {
					this.$set(this.itemList[index], 'whetherCheck', 1)
				}

			},
			getReport() {
				var filterRes = {};
				filterRes.reportId = this.reportId
				this.$http.request({
						url: '/apis/mes/reportCheck/buttonOfCheck',
						params: filterRes,
					})
					.then(res => {
						if (res.data.code == 0) {
							this.code = res.data.HeadDetail.code ? res.data.HeadDetail.code : ''
							this.processName = res.data.HeadDetail.processName ? res.data.HeadDetail.processName : ''
							this.checkPlanName = res.data.HeadDetail.checkPlanName ? res.data.HeadDetail.checkPlanName : ''
							this.checkPlanId = res.data.HeadDetail.checkPlanId ? res.data.HeadDetail.checkPlanId : ''
							this.supplierName = res.data.HeadDetail.supplierName ? res.data.HeadDetail.supplierName : ''
							this.supplierId = res.data.HeadDetail.supplierId ? res.data.HeadDetail.supplierId : ''
							this.materielName = res.data.HeadDetail.materielName ? res.data.HeadDetail.materielName : ''
							this.materielId = res.data.HeadDetail.materielId ? res.data.HeadDetail.materielId : ''
							this.checkCount = res.data.HeadDetail.checkCount ? res.data.HeadDetail.checkCount : 0
							this.quantityAccuracy = res.data.HeadDetail.quantityAccuracy
							res.data.BadyDetail.forEach(item => {
								this.$set(item, 'old', true);
								this.$set(item, 'rejectsCount', 0);
							})
							this.itemList = this.itemList.length == 0 ? res.data.BadyDetail : this.itemList
						}
					})
			},
			onNavigationBarButtonTap(obj) {
				let j = {};
				this.itemList.push(j)
			},
			deleteItem(index) {
				var thisItem = this.itemList[index];
				if (thisItem && thisItem.id) {
					this.deletDetailIds.push(thisItem.id);
				}
				this.itemList.splice(index, 1);
				//保存当前修改信息  保存删除信息
				var processCheckoutInfo = uni.getStorageSync('processCheckoutInfo');
				if (!processCheckoutInfo) {
					processCheckoutInfo = {}
				}
				processCheckoutInfo = this.itemList;
				processCheckoutInfo.deletDetailIds = this.deletDetailIds;
				uni.setStorage({
					key: 'processCheckoutInfo',
					data: processCheckoutInfo,
					success: function() {

					}
				})
			},
			// 选择不良原因
			selectPoor(index) {
				this.show_search_user=true;
				this.currentIndex = index;
				uni.removeStorageSync('processCheckoutInfo');

				// uni.setStorage({
				// 	key: 'processCheckoutInfo',
				// 	data: this.itemList,
				// 	success: function() {
				// 		console.log('processCheckoutInfo success');
				// 	}
				// })
				// uni.navigateTo({
				// 	url: "selectPoor?" + "reportId=" + this.reportId + "&currentIndex=" + this.currentIndex + "&reworkCount=" + this
				// 		.reworkCount + "&scrapCount=" + this.scrapCount + "&conformityCount=" + this.conformityCount
				// });
			},
			// 选择检验项目
			selectCheck(index) {
				this.show_search_user2=true;
				this.currentIndex = index;
				uni.removeStorageSync('processCheckoutInfo');

				// uni.setStorage({
				// 	key: 'processCheckoutInfo',
				// 	data: this.itemList,
				// 	success: function() {
				// 		console.log('processCheckoutInfo success');
				// 	}
				// })
				// uni.navigateTo({
				// 	url: "selectCheck?" + "reportId=" + this.reportId + "&currentIndex=" + this.currentIndex + "&reworkCount=" +
				// 		this.reworkCount + "&scrapCount=" + this.scrapCount + "&conformityCount=" + this.conformityCount
				// });
			},
			pickerConfirm(e) {
				var n = this.currentIndex;
				this.$set(this.itemList[n], 'result', e.label)
				this.$set(this.itemList[n], 'resultType', e.value[0])
				// this.itemList[n].resultType = e.value[0];  //我也不知道为什么这边是数组，可能改picker框架支持多选。
				var processCheckoutInfo = uni.getStorageSync('processCheckoutInfo');
				if (!processCheckoutInfo) {
					processCheckoutInfo = {}
				}
				processCheckoutInfo = this.itemList;
				uni.setStorage({
					key: 'processCheckoutInfo',
					data: processCheckoutInfo,
					success: function() {

					}
				});
			},

			showSinglePicker(index) {
				this.pickerValueArray = this.check_type
				this.currentIndex = index;
				this.pickerValueDefault = [0]
				this.$refs.mpvuePicker.show()
			},
			showSinglePickerType(index) {
				this.pickerValueArray = this.process_type
				this.currentIndex = index;
				this.pickerValueDefault = [0]
				this.$refs.mpvuePicker2.show()
			},
			pickerConfirmType(e) {
				var n = this.currentIndex;
				this.$set(this.itemList[n], 'dispose', e.label)
				this.$set(this.itemList[n], 'disposeType', e.value[0])
				// this.itemList[n].dispose = e.label;
				// this.itemList[n].disposeType = e.value[0];  //我也不知道为什么这边是数组，可能改picker框架支持多选。
				var processCheckoutInfo = uni.getStorageSync('processCheckoutInfo');
				if (!processCheckoutInfo) {
					processCheckoutInfo = {}
				}
				processCheckoutInfo = this.itemList;
				uni.setStorage({
					key: 'processCheckoutInfo',
					data: processCheckoutInfo,
					success: function() {

					}
				});
			},
			dataChange() {
				//保存检验明细当前修改信息
				var processCheckoutInfo = uni.getStorageSync('processCheckoutInfo');
				if (!processCheckoutInfo) {
					processCheckoutInfo = {}
				}
				processCheckoutInfo = this.itemList;
				uni.setStorage({
					key: 'processCheckoutInfo',
					data: processCheckoutInfo,
					success: function() {

					}
				});
			},
			goProcessCheckout() {
				uni.navigateTo({
					url: 'processCheckout',
					url: 'processCheckout?id=' + this.reportId
				});
			},

			// 提交
			save() {
				let flag = true;
				this.itemList.forEach(item => {
					if (!item.project) {
						uni.showToast({
							title: '请选择检验项目',
							duration: 2000,
							icon: "none"
						});
						flag = false
						return
					}
					if (!item.resultType) {
						uni.showToast({
							title: '请填写检验结果',
							duration: 2000,
							icon: "none"
						});
						flag = false
						return
					}
				})
				if(flag) {
					let detail = [];
					let sum = 0;
					this.itemList.forEach(p => {
						var obj = {
							rejectsReason: p.poorId,
							rejectsCount: p.rejectsCount?p.rejectsCount:0,
							dispose: p.disposeType,
							projectId: p.projectId,
							actualValue: p.actualValue,
							unit: p.unit,
							whetherCheck: p.whetherCheck,
							normn: p.normn?p.normn:0,
							result: p.resultType
						};
						sum += +(p.rejectsCount)
						detail.push(obj);
						this.processDetail = encodeURIComponent(JSON.stringify(detail))
					})
					this.result = sum;
					this.reworkCount = +this.reworkCount
					this.scrapCount = +this.scrapCount
					if((this.reworkCount+this.scrapCount) != this.result) {
						uni.showToast({
							title: '不良数量必须要等于返工数量+报废数量',
							duration: 2000,
							icon: "none"
						});
						return
					}
					this.$http.request({
							url: 'apis/mes/reportCheck/submitAddOrChange',
							params: {
								bodyDetail: this.processDetail,
								code: this.code,
								processReportId: this.reportId,
								materiaId: this.materielId,
								supplierId: this.supplierId,
								checkPlanId: this.checkPlanId,
								conformityCount: this.conformityCount,
								reworkCount: this.reworkCount,
								scrapCount: this.scrapCount,
								checkCount: this.checkCount,
								conformityCountSupport:this.conformityCountSupport,
								reworkCountSupport:this.reworkCountSupport,
								scrapCountSupport:this.scrapCountSupport,
								checkCountSupport:this.checkCountSupport,
							}
						}).then(res => {
							if (res.data.code === 0) {
								uni.removeStorageSync('processCheckoutInfo');
								uni.showToast({
									title: res.data.msg ? res.data.msg : '操作成功',
									duration: 1000,
									icon: "none"
								});
								setTimeout(function() {
									uni.redirectTo({
										url: 'reportList'
									});
								}, 1000)
							} else {
								uni.showToast({
									title: res.data.msg ? res.data.msg : '操作失败',
									duration: 2000,
									icon: "none"
								});
							}
						})
						.catch(err => {
							uni.showToast({
								title: '操作失败',
								duration: 2000,
								icon: "none"
							});
						})
				}
				
			}
		},
		onBackPress(options) { //取消默认的返回事件.用来返回上一页时重新加载页面，删除本地缓存的巡检操作
			if (options.from === 'backButton' || options.from === 'backbutton' || options.from === 'navigateBack') {
				uni.redirectTo({
					url: 'reportList'
				});
				return true;
			}
		},
	}
</script>

<style scoped>
	.fz36 {
		font-size: 32upx !important;
		font-weight: 700;
	}

	.mt {
		margin-top: 20upx !important;
	}
</style>
