<template>
	<view class="page">
		<view class="example-b">
			<view class="item">
				<view class="itemname fz36">派工单编号:</view>
				<view class="itemtext">
					<input class="iteminput" disabled v-model="code" />
				</view>
			</view>
		</view>

		<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" disabled placeholder="请选择" @click='selectMaterial(index)' v-model="item.typeName" />
				</view>
			</view>
			<view class="item">
				<view class="itemname">规格型号</view>
				<view class="itemtext">
					<input class="iteminput" disabled v-model="item.specification"  />
				</view>
			</view>
			<view class="item">
				<view class="itemname">计量单位(主单位)</view>
				<view class="itemtext">
					<input class="iteminput" disabled v-model="item.unitUomName"  />
				</view>
			</view>
			<view class="item redMi">
				<view class="itemname">辅助单位</view>
				<view class="itemtext">
					<picker @change="(item0)=>{bindPickerChange(item0,item,index)}" :range="arrayName" >	
						 <label class="">{{item.supportUomName?item.supportUomName:"请选择辅单位"}}</label>
					</picker>
				</view>
			</view>
			<view class="item redMi">
				<view class="itemname">换算系数</view>
				<view class="itemtext">  
					<input type="number" class="iteminput" v-model="item.convCoefficient" placeholder="请输入换算系数" @input='dataChangeConv(index)'/>
				</view>
			</view>
			<view class="item">
				<view class="itemname">主单位数量</view>
				<view class="itemtext">
					<input class="iteminput" disabled v-model="item.materiaCount"  />
				</view>
			</view>
			<view class="item redMi">
				<view class="itemname">数量(辅单位)</view>
				<view class="itemtext">
					<input type="number" class="iteminput" v-model="item.materiaCountSupport" placeholder="请输入辅单位数量" @input='toFixed1(index)' />
				</view>
			</view>
			<view class="item" >
				<view class="itemname">批次号</view>
				<view class="itemtext">
					<input class="iteminput" v-model="item.batch" placeholder="请输入批次号" @input='dataChangeBatch(index)'/>
				</view>
			</view>
			<view class="item">
				<view class="itemname">提供单位</view>
				<view class="itemtext">
					<input class="iteminput" disabled v-model="item.supplierName" />
				</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="addDetail">添加物料</button>
				</view>
				<view style="-webkit-flex:1;flex: 1;">
					<button type="primary"  style="width: 90%;" @click="save">提交</button>
				</view>
			</view>
		</view>
		<view class="goHome" @click='goMain()'>
			<img src="../../static/img/gohome.png">
		</view>
		<chooseMaterialSingle ref="mysearchlist"
			:showsearch.sync="show_search_user"
			:itemInfo_.sync="search_value_user">
		</chooseMaterialSingle>
	</view>
</template>

<script>
	import chooseMaterialSingle from '@/components/xinsoft-search-list/chooseMaterialSingle.vue'
	import uniIcons from '@/components/uni-icons/uni-icons.vue';
	import jweixin from '@/jweixin-module/index.js';
	export default {
		components: {
			uniIcons,
			chooseMaterialSingle
		},
		data() {
			return {
				from:'',
				isCollect: '',
				code: '',
				planNo: '',
				id: '',
				itemList: [],
				idList: [],
				dispatchItemId: '',
				deletDetailIds:[],
				processDetail: [],
				show_search_user:false,
				search_value_user:[],
				materialList: [],
				arrayName: [],
				array: [],
			}
		},
		onLoad(option) {
			console.log(option)
			this.dispatchItemId = option.dispatchItemId?option.dispatchItemId:''
			this.code = option.code?option.code:''
			this.from = option.from
			console.log(this.from)
			// this.planNo = option.planNo?option.planNo:''
			// this.code = this.planNo
			// this.id= option.id?option.id:''
			this.getMaterilalList()
			var materialCollectInfo =  uni.getStorageSync('materialCollectInfo');
			if(materialCollectInfo!=''&&materialCollectInfo!=undefined){
				this.itemList=materialCollectInfo;
			}
		},
		watch:{
			search_value_user(newv){
				var flag =1
				if(this.isCollect ==1) {
					flag=0;
					for (var i = 0; i < this.idList.length; i++) {
					    if(this.idList[i]==newv.id){
					        console.log(i);
					        flag=1;
					        break;
					    }
					}
				}
				if(flag==0){
				    uni.showToast({
				    	title: '当前使用的物料不是投料计划中的物料，请检查是否有物料品种领用错误',
				    	icon: 'none',
				    	duration: 2000
				    });
				} else {
					this.$set(this.itemList[this.currentIndex],'typeName',newv.name);
					this.$set(this.itemList[this.currentIndex],'materialId',newv.id);
					this.$set(this.itemList[this.currentIndex],'specification',newv.specification);
					this.$set(this.itemList[this.currentIndex],'unitUomName',newv.unitUomName);
					this.$set(this.itemList[this.currentIndex],'supplierName',newv.supplierName);
					this.$set(this.itemList[this.currentIndex],'quantityAccuracy',newv.quantityAccuracy);
					this.$set(this.itemList[this.currentIndex],'isLot',newv.isLot);
					
					this.$set(this.itemList[this.currentIndex], 'materiaCount', '0');
					this.$set(this.itemList[this.currentIndex], 'supportUom', newv.supportUom);
					this.$set(this.itemList[this.currentIndex], 'supportUomName', newv.supportUomName);
					this.$set(this.itemList[this.currentIndex], 'convCoefficient', newv.convCoefficient?newv.convCoefficient:1);
					this.$set(this.itemList[this.currentIndex], 'materiaCountSupport',);
			
					uni.removeStorageSync('materialCollectInfo');							
					uni.setStorage({
						key: 'materialCollectInfo',
						data: this.itemList,
						success: function () {
					
						}
					});
				}
						
			}
		},
		mounted() {
			this.initiateWX();
			this.getSpupportUnomName();
		},
		methods: {
			
			bindPickerChange:function(e,item,index){
				var indexNew=e.target.value
				let spupportName = this.arrayName[indexNew]
				console.log("======spupportName:"+spupportName)
				this.$set(this.itemList[index],'supportUomName',spupportName)
				let supportUnomId =0
				this.array.forEach(aa =>{
					if(aa.name==spupportName){
						supportUnomId=aa.id
					}
				})
				console.log("======supportUnomId:"+supportUnomId)
				this.$set(this.itemList[index],'supportUom',supportUnomId)
			},
			getSpupportUnomName(){
				let type ='uom_type'
				this.$http.request({
					url: '/apis/dict/getDictsByType',
					params: {type:type}
				})
				.then(res=>{
					this.array=res.data.datas
					let arr = []
					this.array.forEach(item=>{
						arr.push(item.name)
					})
					this.arrayName = arr
				})
			},
			toFixed1(index){
				this.$set(this.itemList[index],'materiaCountSupport',Number(this.itemList[index].materiaCountSupport).toFixed(this.itemList[index].quantityAccuracy))
				this.$set(this.itemList[index],'materiaCount',0)
				if(!isNaN(this.itemList[index].convCoefficient)&&!isNaN(this.itemList[index].materiaCountSupport)){
					this.$set(this.itemList[index],'materiaCount',Number(this.itemList[index].materiaCountSupport)*Number(this.itemList[index].convCoefficient).toFixed(this.itemList[index].quantityAccuracy))
				}
				//保存检验明细当前修改信息
				this.saveItemListOrMaterialCollectInfo();
			},
			dataChangeConv(index){
				this.$set(this.itemList[index],'convCoefficient',this.itemList[index].convCoefficient)
				if(!isNaN(this.itemList[index].convCoefficient)){
					this.toFixed1(index);
				}
				//保存检验明细当前修改信息
				this.saveItemListOrMaterialCollectInfo();
			}, 
			dataChangeBatch(index){
				this.$set(this.itemList[index],'batch',this.itemList[index].batch)
				//保存检验明细当前修改信息
				this.saveItemListOrMaterialCollectInfo();
			},
			saveItemListOrMaterialCollectInfo(){
				//保存检验明细当前修改信息
				var materialCollectInfo =  uni.getStorageSync('materialCollectInfo');
				if(!materialCollectInfo){
					materialCollectInfo = {}
				}
				materialCollectInfo = this.itemList;
				uni.setStorage({
					key: 'materialCollectInfo',
					data: materialCollectInfo,
					success: function () {
				
					}
				});
			},

			// 获取id对应的用料
			getMaterilalList() {
				let id = +this.dispatchItemId
				this.$http.request({
					url: '/apis/workingProcedurePlan/getMaterielByDispatch',
					params: {id:id}
					})
					.then(res => {
						this.isCollect = res.data.isCollect
						this.materialList = res.data.data
						let arr = []
						this.materialList.forEach(item=>{
							console.log(item)
							arr.push(item.materielId)
						})
						this.idList = arr
						console.log(this.idList)
					})
					
			},
			
			//获取微信相关
			initiateWX() {
				this.$http
					.request({
						url: '/apis/weChat/getSignature',
						params: {
							// url:"http://120.132.17.220:18093/gyhl-app/"
							url: window.location.href.split('#')[0]
						}
					})
					.then(res => {
						if (res.data.code == 0) {
							var s = res.data;
							jweixin.config({
								beta: true,
								debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
								appId: s.corpId, // 必填，公众号的唯一标识
								timestamp: s.timestamp, // 必填，生成签名的时间戳
								nonceStr: s.nonceStr, // 必填，生成签名的随机串
								signature: s.signature.toLowerCase(), // 必填，签名，见附录1
								jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'scanQRCode']
							});
						} else {
							uni.showToast({
								title: res.msg ? res.msg : '获取微信配置失败',
								icon: 'none',
								duration: 2000
							});
						}
					})
					.catch(err => {
						uni.showToast({
							title: err,
							icon: 'none',
							duration: 2000
						});
					});
			},
			
			/** 点击顶部按钮的方法 */
	        onNavigationBarButtonTap() {
	            console.log("你点击了按钮")
	            // 允许从相机和相册扫码
	            let _this = this;
				jweixin.scanQRCode({
					desc: 'scanQRCode desc',
					needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果，
					scanType: ['qrCode'], // 可以指定扫二维码还是条形码（一维码），默认二者都有"qrCode", "barCode"
					success: function(res) {
						if (res.errMsg != 'scanQRCode:ok') {
							uni.showToast({
								title: '扫描结果:' + res.resultStr,
								icon: 'none',
								duration: 2000
							});
						} else {
							//扫码正确
							let resultStr = res.resultStr;
							try {
								resultStr = JSON.parse(resultStr);
								if (resultStr.id) {
									
									_this.getQrCodeInfo(resultStr.id);
								} else {
									uni.showToast({
										title: '二维码错误，请扫描正确的二维码',
										icon: 'none',
										duration: 2000
									});
								}
							} catch (e) {
								uni.showToast({
									title: '二维码错误，请扫描正确的二维码',
									icon: 'none',
									duration: 2000
								});
							}
						}
						// 回调
					},
					error: function(res) {
						uni.showToast({
							title: 'error:' + res,
							icon: 'none',
							duration: 2000
						});
						if (res.errMsg.indexOf('function_not_exist') > 0) {
							alert('版本过低请升级');
						}
					}
				});
	        },
	
			//调用接口获取二维码信息
			getQrCodeInfo(id) {
				var _this = this
				if(this.isCollect ==1) {
					var flag=0;
					for (var i = 0; i < this.idList.length; i++) {
					    if(this.idList[i]==id){
					        flag=1;
					        break;
					    }
					}
					if(flag==0){
					    uni.showToast({
					    	title: '当前使用的物料不是投料计划中的物料，请检查是否有物料品种领用错误',
					    	icon: 'none',
					    	duration: 2000
					    });
						return
					}
				}
				this.$http
					.request({
						url: '/apis/materiel/detail',
						params: {
							id: id
						},
						method: 'POST'
					})
					.then(res => {
						if (res.data.code == 0) {
							console.log(res.data.supplierName)
							let j = {
								materiaId:res.data.id,
								typeName:res.data.name,
								specification: res.data.specification?res.data.specification:'',
								unitUomName:res.data.unitUomName?res.data.unitUomName:'',
								supplierName:res.data.supplierName?res.data.supplierName:'',
								
								materiaCount:0,
								supportUom:res.data.supportUom?res.data.supportUom:'',
								supportUomName:res.data.supportUomName?res.data.supportUomName:'',
								convCoefficient:res.data.convCoefficient?res.data.convCoefficient:'',
								materiaCountSupport:0,
							}
							_this.itemList.push(j)
						}else{
							uni.showToast({
								title: res.data.msg? res.data.msg:'扫码失败',
								icon: 'none',
								duration: 2000
							});
						}
					});
			},
			
			
			
			addDetail() {
				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 materialCollectInfo =  uni.getStorageSync('materialCollectInfo');
				if(!materialCollectInfo){
					materialCollectInfo = {}
				}
				materialCollectInfo = this.itemList;
				materialCollectInfo.deletDetailIds = this.deletDetailIds;
				uni.setStorage({
					key: 'materialCollectInfo',
					data: materialCollectInfo,
					success: function() {

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

				    }
				});
			},
			// 选择物料
			selectMaterial(index){
				this.show_search_user=true;
				this.currentIndex=index;
				uni.removeStorageSync('materialCollectInfo');
				// let arr = []
				// this.itemList.forEach(item=> {
				// 	arr.push(item.materialId)
				// })
				// this.idList
				// var mix = this.idList.filter(function(item){
				//     return arr.indexOf(item) != -1
				// });
				// console.log(mix)
				
			
			},
			// 保存
			save() {
				var _this = this
				let detail = [];
				let flag = true
				this.itemList.forEach(item => {
					if(item.materialId==undefined) {
						flag = false
					}
				})
				if(flag == false) {
					uni.showToast({
						title: '请选择物料',
						duration: 	2000,
						icon:"none"
					});
					return
				}
				let flag1 = true
				this.itemList.forEach(item => {
					if(item.materiaCountSupport==undefined || item.materiaCount=='') {
						flag1 = false
					}
				})
				if(flag1 == false) {
					uni.showToast({
						title: '请填写数量(辅单位)',
						duration: 	2000,
						icon:"none"
					});
					return
				}
				let flag2 = true
				this.itemList.forEach(item => {
					if(item.batch==undefined&&item.isLot==1) {
						flag2 = false
					}
				})
				if(flag2 == false) {
					uni.showToast({
						title: '有批次管理的请填写批次',
						duration: 	2000,
						icon:"none"
					});
					return
				}
				
				this.itemList.forEach(p=>{
					let obj = { materiaId: p.materialId, materiaCount: p.materiaCount,supportUom: p.supportUom,convCoefficient: p.convCoefficient,materiaCountSupport: p.materiaCountSupport,batch: p.batch};
					if(p.batch&&p.batch !='') {
						obj.batch=p.batch;
					  }
					detail.push(obj);
					this.processDetail = encodeURIComponent(JSON.stringify(detail))
				})
				this.$http.request({
					url: 'apis/mes/materialCollect/submitCollect',
					params: {
						dispatchItemId: this.dispatchItemId,
						colletDetails: this.processDetail
					}
				}).then(res=>{
					if (res.data.code === 0) {
						uni.removeStorageSync('materialCollectInfo');
						uni.showToast({
							title: res.data.msg ? res.data.msg : '操作成功',
							duration: 1000,
							icon: "none"
						});
						setTimeout( function(){
							if(_this.from == 'startWorking') {
								uni.redirectTo({
								    url: 'startWorking?+id='+_this.dispatchItemId
								});
							} else {
								uni.navigateTo({
								    // url: 'materialCollect?+dispatchItemId='+this.dataList.dispatchItemId
									url:'/pages/waitingMenu/waitingMenu'
								});
							}
						},1000)
					} else {
						uni.showToast({
							title: res.data.msg ? res.data.msg : '操作失败',
							duration: 2000,
							icon: "none"
						});
					}
					
				})
				.catch(err=>{
					uni.showToast({
						title: '操作失败',
						duration: 	2000,
						icon:"none"
					});
				})
			}
		}
	}
</script>

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