<template>
	<view class="page">
		<view v-for="(item,index) in dataList" :key="index">
			<view class=" myContainer myContentBox dev-block">
				<view class="">
					<view class=" uni-padding-wrap">
						<view class="uni-flex uni-row">
							<view class=" fz36">工序计划单号:{{workOrderNo}}</view>
							<view class=" fz36">派工{{index+1}}</view>
						</view>
					</view>
				</view>
				<view class="item item_line">
					<view class="itemname redMi" v-if="isOutsource==1">业务员</view>
					<view class="itemname redMi" v-else>操作工</view>
					<!-- <view class="itemtext" @click="selectOperater(index)">
						<input class="iteminput InputRightMargin" disabled placeholder="请选择" v-model='item.operatorName' />
						<img src="../../static/img/personlistIcon.png" class="dateIcon" />
					</view> -->
					<view class="itemtext"  @click="selectOperater(index)" >
						<input class="iteminput InputRightMargin" disabled placeholder="请选择" :value="formatCsrName(targetList)"/>
						<img src="../../static/img/personlistIcon.png" class="dateIcon" />
					</view>
				</view>
				<view class="item item_line" v-if="isOutsource==1">
					<view class="itemname redMi">供应商</view>
					<view class="itemtext">
						<input class="iteminput" placeholder="请选择" disabled @click='selectSupplier(index)' v-model="item.spplierName" />
					</view>
				</view>
				<view class="item item_line" v-else>
					<view class="itemname">生产设备</view>
					<view class="itemtext">
						<input class="iteminput" placeholder="请选择" disabled @click='selectDevice(index)' v-model="item.deviceName" />
					</view>
				</view>
				
				
				
				
				<view class="item item_line">
					<view class="itemname redMi">生产数量</view>
					<view class="itemtext">
						<input type="number" class="iteminput" @change='toFixed1(index)' v-model="item.planCount" placeholder="请输入数量" />
					</view>
				</view>
				<view class="item item_line" @click="onShowDatePicker(1,index)">
					<view class="itemname">计划开工日期</view>
					<view class="itemtext">
						<view>
							<input class="iteminput InputRightMargin" disabled placeholder="请选择" v-model='item.startTime' />
							<img src="../../static/img/dateIcon.png" class="dateIcon" />
						</view>
					</view>
				</view>
				<view class="item item_line" @click="onShowDatePicker(2,index)">
					<view class="itemname">计划完工日期</view>
					<view class="itemtext">
						<view>
							<input class="iteminput InputRightMargin" disabled placeholder="请选择" v-model='item.endTime' />
							<img src="../../static/img/dateIcon.png" class="dateIcon" />
						</view>
					</view>
				</view>
				<view class="item item_line">
					<view class="itemname">备注</view>
					<view class="itemtext">
						<input class="iteminput" @change='infoChange' v-model="item.remark" placeholder="请输入备注信息" />
					</view>
				</view>
				<!-- <uni-load-more :status="loading_status"></uni-load-more> -->
				<uni-calendar ref="calendar" :lunar="false" :range="true" @confirm="confirmDate" />
			</view>
		</view>
		<view class="fixBottom">
			<view style="-webkit-flex:1;flex: 1;">
				<button type="primary" plain="true" style="width: 90%; background: #fff;" @click="addDispatching">添加派工</button>
			</view>
		</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="gotoPlan">取消</button>
				</view>
				<view style="-webkit-flex:1;flex: 1;">
					<button type="primary" style="width: 90%;" @click="save">确认提交</button>
				</view>
			</view>
		</view>
		<mx-datepicker type="datetime" :value="value_time" :show="showPicker" @confirm="onSelected" @cancel="onSelected"></mx-datepicker>
		<view class="goHome" @click='goMain()'>
			<img src="../../static/img/gohome.png">
		</view>
		<view class="mysearchlist" style="z-index: 10000;">
			<!-- <chooseUserSingle ref="mysearchlist" 
				:showsearch.sync="show_search_user"
				:itemInfo_.sync="search_value_user">
			</chooseUserSingle> -->
			<chooseUserMulti ref="mysearchlist"
				:deptId='deptId'
				:showsearch.sync="show_search_user"
				:itemInfo_.sync="search_value_user">
			</chooseUserMulti>
		</view>
		<view class="mysearchlist" style="z-index: 10000;">
			<chooseSupplierSingle ref="mysearchlist" 
				:showsearch.sync="show_search_user2"
				:itemInfo_.sync="search_value_user2">
			</chooseSupplierSingle>
		</view>
		<view class="mysearchlist" style="z-index: 10000;">
			<chooseEquipmentSingle ref="mysearchlist" 
				:showsearch.sync="show_search_user3"
				:deptId='deptId'
				:device_type='device_type'
				:itemInfo_.sync="search_value_user3">
			</chooseEquipmentSingle>
		</view>
	</view>
</template>

<script>
	import chooseUserMulti from './selectOperator.vue'
	import chooseSupplierSingle from '@/components/xinsoft-search-list/chooseSupplierSingle.vue';
	import chooseUserSingle from '@/components/xinsoft-search-list/chooseUserSingle.vue';
	import chooseEquipmentSingle from './selectEquipment.vue';
	import uniCalendar from '@/components/uni-calendar/uni-calendar.vue';
	import mpvuePicker from '@/components/mpvue-picker/mpvuePicker.vue';
	import mxDatepicker from '@/components/mx-datepicker/mx-datepicker.vue'
	export default {
		components: {
			uniCalendar,
			mpvuePicker,
			mxDatepicker,
			chooseUserSingle,
			chooseEquipmentSingle,
			chooseSupplierSingle,
			chooseUserMulti
		},
		data() {
			return {
				device_type:'',//设备类型
				dataList: [{
					operator: '',
					deviceId: '',
					planCount: '',
					startTime: '',
					endTime: '',
					remark: '',
				}],
				deptId:'',
				targetList: [],
				show_search_user:false,
				search_value_user:"",
				show_search_user2:false,
				search_value_user2:"",
				show_search_user3:false,
				search_value_user3:"",
				currentIndex: '',
				info: {},
				loading_status: 'more', //more（loading前）、loading（loading中）、noMore（没有更多了）
				showPicker: false,
				planItemId: '',
				isOutsource: '',
				totalCount: '',
				workOrderNo: '',
				planStartTime:'',
				planEndTime:'',
				planCount:'',
				alreadyCount:"",
				value_time:'',
				devInfo:{},
				quantityAccuracy:'',
				dispatchDetal1: [],
				dispatchDetal2: [],
			}
		},
		onLoad(option) {
					var dispatchingInfo =  uni.getStorageSync('dispatchingInfo');
					if(dispatchingInfo!=''&&dispatchingInfo!=undefined){
						this.dataList=dispatchingInfo;
					}
			this.planItemId = option.planItemId;
			this.isOutsource = option.isOutsource;
			this.getDispatch();
			uni.getStorage({
				key: 'userInfo',
				success: function (res) {
					this.deptId = res.data.deptId
				}
			});
		},
		watch:{
			// search_value_user(newv){
			// 	this.$set(this.dataList[this.currentIndex],'operator',newv.userId);
			// 	this.$set(this.dataList[this.currentIndex],'operatorName',newv.NAME);
			// 	uni.removeStorageSync('dispatchingInfo');							
			// 	uni.setStorage({
			// 		key: 'dispatchingInfo',
			// 		data: this.dataList,
			// 		success: function () {

			// 		}
			// 	});		
			// },
			search_value_user(newv){
				var detail = [];
				newv.forEach(item=>{
					let obj = {user_id: item.userId, name: item.NAME};
					detail.push(obj);
				})
				if(newv.length>0){
					var leaveInfo =  uni.getStorageSync('leaveInfo');
					if(!leaveInfo){
						leaveInfo = {}
					}
					this.targetList=detail
					}
				},
			search_value_user3(newv){
				this.$set(this.dataList[this.currentIndex],'deviceId',newv.id);
				this.$set(this.dataList[this.currentIndex],'deviceName',newv.name);
				uni.removeStorageSync('dispatchingInfo');							
				uni.setStorage({
					key: 'dispatchingInfo',
					data: this.dataList,
					success: function () {

					}
				});		
			},
			search_value_user2(newv){
				this.$set(this.dataList[this.currentIndex],'supplierId',newv.id);
				this.$set(this.dataList[this.currentIndex],'spplierName',newv.name);
				uni.removeStorageSync('dispatchingInfo');							
				uni.setStorage({
					key: 'dispatchingInfo',
					data: this.dataList,
					success: function () {

					}
				});		
			}
		},
		methods: {
			toFixed1(index) {
				this.$set(this.dataList[index],'planCount',Number(this.dataList[index].planCount).toFixed(this.quantityAccuracy))
			},
			
			formatCsrName(data){
				console.log(data)
				var returnName = '';
				for(var i=0;i<data.length;i++){
					if(i == 3){
						returnName += data[i].name+'等等';
						 break;
					}else{
						returnName += data[i].name+','
					}
				}
				returnName = returnName.substring(0,returnName.length-1);
				return returnName;
			},

			getDispatch() {
				this.loading_status = "loading";
				var filterRes = {};
				filterRes.planItemId = this.planItemId
				this.$http.request({
						url: 'apis/mes/dispatch/sendButton',
						params: filterRes,
					})
					.then(res => {
						if (res.data) {
							this.alreadyCount = res.data.alreadyCount;
							this.totalCount = res.data.planCount;
							this.remark = res.data.remark?res.data.remark:'';
							this.workOrderNo = res.data.workOrderNo;
							this.device_type= res.data.deviceType?res.data.deviceType:''
							this.quantityAccuracy = res.data.quantityAccuracy
							this.planCount = res.data.planCount?res.data.planCount:0
							this.alreadyCount = res.data.alreadyCount?res.data.alreadyCount:0
							this.planStartTime = res.data.planStartTime?res.data.planStartTime:''
							this.planEndTime = res.data.planEndTime?res.data.planEndTime:''
							this.dataList[0].planCount = res.data.planCount-res.data.alreadyCount
							this.dataList[0].startTime = res.data.planStartTime?res.data.planStartTime.substr(0,10):'' 
							this.dataList[0].endTime = res.data.planEndTime?res.data.planEndTime.substr(0,10):'' 
						}
					})
			},
			onShowDatePicker(n,index) { //显示
			this.currentIndex=index;
				this.time_index=n;
				this.showPicker = true;
			},
			onSelected(e) {
				//选择
				this.showPicker = false;
				if (e) {
					if(this.time_index==1){
						this.dataList[this.currentIndex].startTime = e.value.substr(0,10);
					}else if(this.time_index==2){
						this.dataList[this.currentIndex].endTime = e.value.substr(0,10);
					}
				}
			},
			// 选择设备
			selectDevice(index){
				this.show_search_user3=true;
				this.currentIndex=index;
				uni.removeStorageSync('dispatchingInfo');
				// uni.setStorage({
				// 	key: 'dispatchingInfo',
				// 	data: this.dataList,
				// 	success: function () {
				// 		console.log('dispatchingInfo success');
				// 	}
				// })
				// uni.navigateTo({
				//     url: "selectEquipment?flag=dispatching"+"&planItemId="+this.planItemId+"&currentIndex="+this.currentIndex
				// });
			},
			// 选择供应商
			selectSupplier(index) {
				this.show_search_user2=true;
				this.currentIndex=index;
				uni.removeStorageSync('dispatchingInfo');
				// this.currentIndex=index;
				// console.log(this.dataList)
				// uni.removeStorageSync('dispatchingInfo');
							
				// uni.setStorage({
				// 	key: 'dispatchingInfo',
				// 	data: this.dataList,
				// 	success: function () {
				// 		console.log('dispatchingInfo success');
				// 	}
				// })
				// uni.navigateTo({
				// 	url: "selectSupplier?" +"planItemId="+this.planItemId+"&currentIndex="+this.currentIndex+"&isOutsource="+this.isOutsource
				// });
			},
			// 选择操作工
			selectOperater(index){
				this.show_search_user=true;
				this.currentIndex=index;
				uni.removeStorageSync('dispatchingInfo');
			
				// uni.setStorage({
				// 	key: 'dispatchingInfo',
				// 	data: this.dataList,
				// 	success: function () {
				// 		console.log('dispatchingInfo success');
				// 	}
				// })
				// uni.navigateTo({
				// 	url: "selectOperator?" +"planItemId="+this.planItemId+"&currentIndex="+this.currentIndex+"&isOutsource="+this.isOutsource
				// });
			},
			infoChange:function(){
				// //保存当前修改信息
				// var dispatchingInfo =  uni.getStorageSync('dispatchingInfo');
				// if(!dispatchingInfo){
				// 	dispatchingInfo = {}
				// }
				// dispatchingInfo.info = this.dataList ;
				// uni.setStorage({
				//     key: 'dispatchingInfo',
				//     data: dispatchingInfo,
				//     success: function () {
				//         console.log('dispatchingInfo success');
				//     }
				// });
			},

			addDispatching() {
				let j = {
					planCount: this.planCount-this.alreadyCount,
					startTime: this.planStartTime.substr(0,10),
					endTime: this.planEndTime.substr(0,10),
				};
				this.dataList.push(j)
			},
			// 取消返回代派计划
			gotoPlan() {
				uni.removeStorageSync('dispatchingInfo');
				uni.navigateTo({
				    url: 'plan'
				});
			},
			// 保存
			save() {
				let flag = true;
				this.dataList.forEach(item=>{
					if(this.isOutsource == 0) {
						if(this.targetList.length == 0) {
							uni.showToast({
								title: '请选择操作工',
								duration: 2000,
								icon: "none"
							});
							flag = false
							return
						}
						// if(!item.deviceId) {
						// 	uni.showToast({
						// 		title: '请选择生产设备',
						// 		duration: 2000,
						// 		icon: "none"
						// 	});
						// 	flag = false
						// 	return
						// }
						if(!item.planCount) {
							uni.showToast({
								title: '请填写生产数量',
								duration: 2000,
								icon: "none"
							});
							flag = false
							return
						}
					} else {
						if(!item.operator) {
							uni.showToast({
								title: '请选择业务员',
								duration: 2000,
								icon: "none"
							});
							flag = false
							return
						}
						if(!item.supplierId) {
							uni.showToast({
								title: '请选择供应商',
								duration: 2000,
								icon: "none"
							});
							flag = false
							return
						}
						if(!item.planCount) {
							uni.showToast({
								title: '请填写生产数量',
								duration: 2000,
								icon: "none"
							});
							flag = false
							return
						}
					}
				})
				if(flag) {
					var result = 0;
					this.dataList.forEach( item=>{
						result += +item.planCount;	
					})
					if(this.totalCount<result+this.alreadyCount) {
						uni.showToast({
							title: '派工数量应小于等于待派工数量',
							duration: 	2000,
							icon:"none"
						});
						return
					}
					if(this.isOutsource == 0) {
						console.log(this.targetList)
						let arr = []
						this.targetList.forEach(item => {
							arr.push(item.user_id)
						})
						let detail = [];
						this.dataList.forEach(p=>{
							let obj = { operator: arr.toString(), deviceId: p.deviceId, 
							planCount: p.planCount, startTime: p.startTime, endTime: p.endTime,remark: p.remark};
							detail.push(obj);
							this.dispatchDetal1 = encodeURIComponent(JSON.stringify(detail))
							
						})
						this.$http.request({
							url: 'apis/mes/dispatch/submitDispatchDetail',
							params: {
								planItemId: this.planItemId,
								dispatchDetal: this.dispatchDetal1
							}
						}).then(res=>{
							uni.removeStorageSync('dispatchingInfo');
							uni.showToast({
								title: res.data.msg ? res.data.msg : '操作成功',
								duration: 	1000,
								icon:"none"
							});
							setTimeout( function(){
								uni.redirectTo({
								    url: 'plan'
								});
							},1000)
						})
						.catch(err=>{
							uni.showToast({
								title: res.data.msg ? res.data.msg : '操作失败',
								duration: 	2000,
								icon:"none"
							});
						});
					}	else {
						let arr = []
						this.targetList.forEach(item => {
							arr.push(item.user_id)
						})
						let detail = [];
						this.dataList.forEach(p=>{
							let obj = { operator: arr.toString(), supplierId: p.supplierId, 
							planCount: p.planCount, startTime: p.startTime, endTime: p.endTime,remark:p.remark};
							detail.push(obj);
							this.dispatchDetal2 = encodeURIComponent(JSON.stringify(detail))
						})
						this.$http.request({
							url: 'apis/mes/dispatch/submitDispatchDetail',
							params: {
								planItemId: this.planItemId,
								dispatchDetal: this.dispatchDetal2
							}
						}).then(res=>{
							if (res.data.code === 0) {
								uni.removeStorageSync('dispatchingInfo');
								uni.showToast({
									title: res.data.msg ? res.data.msg : '操作成功',
									duration: 1000,
									icon: "none"
								});
								setTimeout( function(){
									uni.redirectTo({
									    url: 'plan'
									});
								},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: 'plan'
				});
				return true;	
			}		
		},
	}
</script>

<style scoped>

	.fz36 {
		font-size: 32upx !important;
	}

</style>
