<template>
	<view class="">
		<com-empty-view v-if="jobList.length==0"></com-empty-view>
		<!-- 	<job-filter :isShowFromLocationCode="true" ref="filter" otherTitle="ASN" @switchChangeToday="switchChangeToday"
			@switchChangeWait="switchChangeWait" @onScanNumber="getScanNumber" :checkedToday="checkedToday" :isShowItemCode="true"
			:checkedWaitTask="checkedWaitTask" @fromLocationCode="fromLocationCode">
		</job-filter> -->

		<job-filter :isShowFromLocationCode="true" :isShowProductionLineCode="false"
			:productionline="productionlineList" ref="filter" otherTitle="" @switchChangeToday="switchChangeToday"
			@switchChangeWait="switchChangeWait" @onScanNumber="getScanNumber" :checkedToday="checkedToday"
			:checkedWaitTask="checkedWaitTask" :isShowItemCode="true" @productionLineCode="productionLineCode"
			@fromLocationCode="fromLocationCodeQuery" :isShowQurery='true' @onQuery="getListByFilter">
		</job-filter>
		<view v-if="jobList.length>0">
			<uni-swipe-action ref="swipeAction">
				<view v-for="(item, index) in jobList" :key="index">
					<uni-swipe-action-item
						:right-options="item.status=='2'?detailGiveupOptions:item.status=='1'?detailCloseOptions:detailOptions"
						@click="swipeClick($event,item)">
						<com-repleinsh-job-card :dataContent="item"
							@click='openJobDetail(item)'></com-repleinsh-job-card>
					</uni-swipe-action-item>
				</view>
			</uni-swipe-action>

			<repleinsh-info-popup ref='jobInfoPopup'></repleinsh-info-popup>
			<repleinsh-job-list-popup ref="jobListPopup" @selectedItem="selectedItem"></repleinsh-job-list-popup>
			<uni-load-more :status="loadingType" v-if="jobList.length>0" />

		</view>
		<win-scan-button @goScan='openScanPopup' v-if="jobList.length>0"></win-scan-button>
		<winComScanBalance ref="scanPopup" @getBalance='getScanResult' :bussinessCode="businessTypeCode">
		</winComScanBalance>
		<!-- <winScanPackJob ref="scanPopup" @getResult='getScanResult' ></winScanPackJob> -->
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		getRepleinshJobList,
		cancleTakeRepleinshJob,
		closeTakeRepleinshJob,
	} from '@/api/request2.js';

	import {
		goHome,
		updateTitle
	} from '@/common/basic.js';

	import {
		getBusinessType
	} from '@/common/record.js';

	import {
		getDetailOption,
		getDetailGiveupOption,
		getDetailCloseOption
	} from '@/common/array.js';
	
	import {
		planRefreshTime
	} from '@/common/config.js';

	import comEmptyView from '@/mycomponents/common/comEmptyView.vue'
	import jobFilter from '@/mycomponents/job/jobFilter.vue'
	import comRepleinshJobCard from '@/pages/repleinsh/coms/comRepleinshJobCard.vue'
	import repleinshJobListPopup from '@/pages/repleinsh/coms/repleinshJobListPopup.vue'
	import repleinshInfoPopup from '@/pages/repleinsh/coms/repleinshInfoPopup.vue'
	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import winScanPackJob from "@/mycomponents/scan/winScanPackJob.vue"
	import winComScanBalance from '@/mycomponents/scan/winComScanBalance.vue'

	export default {
		name: 'repleinsh',
		components: {
			comEmptyView,
			jobFilter,
			comRepleinshJobCard,
			repleinshJobListPopup,
			repleinshInfoPopup,
			winScanPackJob,
			winScanButton,
			winComScanBalance
		},
		data() {
			return {
				jobList: [],
				pageNo: 1,
				pageSize: 10,
				totalCount: 0,
				loadingType: "nomore",
				checkedToday: false,
				checkedWaitTask: false,
				todayTime: "",
				status: '1,2', //待处理 、进行中
				detailOptions: [],
				detailGiveupOptions: [],
				detailCloseOptions: [],
				title: '',
				scanMessage: "",
				businessTypeCode: "Repleinment",
				businessType: null,
				scanBalance: {},
				inInventoryStatus: "", //目标入库库存状态
				outInventoryStatus: "", //来源出库库存状态
				productionLineCode: "",
				productionlineList: [],
				fromLocationCode:'',
				filterItemCode:'',
				timer:null
			};
		},
		onLoad(option) {
			this.title = option.title
			this.getBusinessTypeFunc()
		},

		
		onShow() {
			this.timerRefresh();
		},
		
		onHide() {
			this.stopRefresh();
		},
		onUnload(){
			this.stopRefresh();
		},
		onReady() {
			this.detailOptions = getDetailOption();
			this.detailGiveupOptions = getDetailGiveupOption();
			this.detailCloseOptions = getDetailCloseOption();
		},

		//后退按钮
		onBackPress(options) {
			if (options.from === 'navigateBack') {
				uni.navigateBack({
					delta: 1
				})
				return false;
			}
		},

		//返回首页
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				goHome();
			} else if (e.index == 1) {
				this.$refs.filter.openFilter();
			}
		},
		onReachBottom() {
			//避免多次触发
			if (this.loadingType == 'loading' || this.loadingType == 'nomore') {
				return;
			}
			this.getList('more', this.fromLocationCode, this.filterItemCode)
			
		},
		onPullDownRefresh() {
			this.getList('refresh', this.fromLocationCode, this.filterItemCode)
			
		},

		methods: {
			timerRefresh() {
				this.getList('refresh', this.fromLocationCode, this.filterItemCode)
				this.stopRefresh();
				var that = this;
				this.timer = setInterval(function() {
					that.getList('refresh', that.fromLocationCode, that.filterItemCode)
					console.log('补料刷新');
				}, planRefreshTime)
			},
			stopRefresh() {
				if (this.timer) {
					clearInterval(this.timer);
					this.timer = null;
				}
			},
			getBusinessTypeFunc() {
				getBusinessType(this.businessTypeCode, res => {
					if (res.success) {
						this.businessType = res.businessType;
						this.fromInventoryStatuses = res.fromInventoryStatuses.split(',');
						this.fromLocationAreaTypeList = res.fromLocationAreaTypeList
						// this.openScanPopup();
					} else {
						this.showErrorMessage(res.message)
					}
				});
			},

			getList(type, fromLocationCode = '',filterItemCode='') {
				
				let that = this;
				uni.showLoading({
					title: "加载中­....",
					mask: true
				});

				this.loadingType = "loading";
				if (type === "refresh") {
					this.pageNo = 1;
					this.jobList = [];
				}

				var filters = []
				if (this.checkedToday) {
					filters.push({
						column: "create_time",
						action: "betweeen",
						value: this.todayTime
					})
				}

				filters.push({
					column: "status",
					action: "in",
					value: this.status
				})

				if (fromLocationCode != '') {
					// 来源库位
					filters.push({
						column: "fromLocationCode",
						action: "==",
						value: fromLocationCode
					})
				}
				if (filterItemCode != '') {
					// 物料代码
					filters.push({
						column: "itemCode",
						action: "like",
						value: filterItemCode
					})
				}
				var params = {
					filters: filters,
					pageNo: this.pageNo,
					pageSize: this.pageSize,
					// sort: 'number',
					// by: 'desc'
				}

				getRepleinshJobList(params).then(res => {
					uni.hideLoading();
					if (type === "refresh") {
						uni.stopPullDownRefresh();
					}

					var list = res.data.list;
					this.totalCount = res.data.total
					updateTitle(this.title + "(" + this.totalCount + ")");
					this.loadingType = "loadmore";
					if (list == null || list.length == 0) {
						this.loadingType = "nomore";
						return;
					}
					this.jobList = type === "refresh" ? list : this.jobList.concat(list);
					this.pageNo++;

				}).catch(error => {
					if (type === "refresh") {
						uni.stopPullDownRefresh();
					}
					this.loadingType = "";
					updateTitle(this.title);
					uni.hideLoading();
					that.showMessage(error)
				})
			},

			getListByFilter(params) {
				let that = this;
				uni.showLoading({
					title: "加载中­....",
					mask: true
				});
				// var filters = []
				// if (this.checkedToday) {
				// 	filters.push({
				// 		column: "create_time",
				// 		action: "betweeen",
				// 		value: this.todayTime
				// 	})
				// }

				// filters.push({
				// 	column: "status",
				// 	action: "in",
				// 	value: this.status
				// })
				if (params.status) {
					this.status  = params.status
				}else{
					this.status  = "1,2"
				}
				if(params.creationTime==""){
					this.checkedToday = false;
				}

				if (params.fromLocationCode) {
					// 来源库位
					this.fromLocationCode = params.fromLocationCode
					// filters.push({
					// 	column: "fromLocationCode",
					// 	action: "==",
					// 	value: params.fromLocationCode
					// })
				}else{
					this.fromLocationCode = ''
				}

				if (params.itemCode) {
					// 物料代码
					this.filterItemCode = params.itemCode
					// filters.push({
					// 	column: "itemCode",
					// 	action: "like",
					// 	value: params.itemCode
					// })
				}else{
					this.filterItemCode = ''
				}
				// var params = {
				// 	filters: filters,
				// 	pageNo: 1,
				// 	pageSize: 100,
				// }
				this.getList('refresh', this.fromLocationCode, this.filterItemCode)
			
				// getRepleinshJobList(params).then(res => {
				// 	uni.hideLoading();
				// 	if (res.data.total == 0) {
				// 		that.showMessage('未查找到补料任务');
				// 	} else if (res.data.total == 1) {
				// 		that.openJobDetail(res.data.list[0]);
				// 	} else {
				// 		that.showItemList(res.data.list);
				// 	}
				// }).catch(error => {

				// 	that.showMessage(error)
				// })
			},



			fromLocationCodeQuery(fromLocationCode) {
				console.log('fromLocationCode', fromLocationCode)
				this.fromLocationCode = fromLocationCode
				this.getList('refresh', this.fromLocationCode, this.filterItemCode)
			},

			openJobDetail(item, scanMessage = '') {
				this.getJobInfoByNumber(item.number,scanMessage )
				
			},
			
			getJobInfoByNumber(number,scanMessage){
				let that = this;
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				var filters = []
				filters.push({
					column: "status",
					action: "in",
					value: '1,2'
				})
				filters.push({
					column: "number",
					action: "==",
					value: number
				})
				
				var params = {
					filters: filters,
					pageNo: 1,
					pageSize: 100,
				}
				getRepleinshJobList(params).then(res => {
					uni.hideLoading();
					if (res.data.list.length == 0) {
						that.showMessage('未查找到' + '【' + number + '】的发料任务');
					} else  {
						var result =res.data.list[0];
						if(result.acceptUserId&&result.acceptUserId!=this.$store.state.user.id){
							this.$refs.comMessage.showErrorMessage("任务号["+result.number+"]已经被["+result.acceptUserName+"]承接,无法执行", res => {
								if (res) {
									if (this.$refs.scanPopup) {
										this.$refs.scanPopup.getfocus()
									}
									this.getList('refresh', this.fromLocationCode, this.filterItemCode)
								}
							});
							
							return;
						}
						
						uni.navigateTo({
							url: './repleinshDetail?id=' + result.masterId + '&status=' + result.status + '&scanMessage=' +
								scanMessage + '&title=' + this.title
						});
						this.scanMessage = ""
					}
				}).catch(error => {
					uni.hideLoading();
					that.showMessage(error);
				})
			},

			showItemList(itemList) {
				this.$refs.jobListPopup.openPopup(itemList);
			},

			selectedItem(item) {
				this.openJobDetail(item);
			},

			swipeClick(e, dataContent) {
				if (e.content.text == "详情") {
					this.openjobInfoPopup(dataContent);
				} else if (e.content.text == "放弃") {
					this.$refs.comMessage.showQuestionMessage("确定要放弃当前任务?",
						res => {
							if (res) {
								this.cancleJob(dataContent.masterId);
							}
						});
				} else if (e.content.text == "关闭") {
					this.$refs.comMessage.showQuestionMessage("确定要关闭当前任务?",
						res => {
							if (res) {
								this.closeJob(dataContent.masterId);
							}
						});
				}
			},

			openjobInfoPopup(item) {
				this.$refs.jobInfoPopup.openPopup(item)
			},

			cancleJob(id) {
				cancleTakeRepleinshJob(id).then(res => {
					if (res.data) {
						this.getList('refresh', this.fromLocationCode, this.filterItemCode)
						uni.showToast({
							title: "放弃任务成功"
						})
					} else {
						this.showMessage("放弃任务失败")
					}
				}).catch(error => {
					this.showMessage(error)
				})
			},
			closeJob(id) {
				uni.showLoading({
					title: "加载中....",
					mask: true
				});

				closeTakeRepleinshJob(id).then(res => {
					uni.hideLoading()
					if (res.data) {
						this.getList('refresh', this.fromLocationCode, this.filterItemCode)
						uni.showToast({
							title: "关闭任务成功"
						})
					} else {
						this.showMessage("关闭任务失败")
					}
				}).catch(error => {
					uni.hideLoading()
					this.showMessage(error)
				})
			},

			switchChangeToday(state, creationTime) {
				this.checkedToday = state;
				this.todayTime = creationTime;
				this.getList('refresh', this.fromLocationCode, this.filterItemCode)
			},

			switchChangeWait(state, jobStatus) {
				this.checkedWaitTask = state;
				this.status = jobStatus;
				this.getList('refresh', this.fromLocationCode, this.filterItemCode)
			},
			getScanNumber(code) {
				this.getDataListByType(code)
			},
			getDataListByType(code) {
				let that = this;
				uni.showLoading({
					title: "加载中....",
					mask: true
				});
				var filters = []
				filters.push({
					column: "status",
					action: "in",
					value: '1,2'
				})
				filters.push({
					column: "number",
					action: "==",
					value: code
				})

				var params = {
					filters: filters,
					pageNo: 1,
					pageSize: 100,
					sort: 'number',
					by: 'desc'
				}
				getRepleinshJobList(params).then(res => {
					uni.hideLoading();
					if (res.data.list.length == 0) {
						that.showMessage('未查找到' + '【' + code + '】的补料任务');
					} else {
						that.openJobDetail(res.data.list[0]);
					}
				}).catch(error => {
					uni.hideLoading();
					that.showMessage(error);
				})
			},

			showMessage(message) {
				this.$refs.comMessage.showErrorMessage(message, res => {
					if (res) {

					}
				});
			},
			openScanPopup() {
				if (this.businessType == null) {
					this.getBusinessTypeFunc()
				} else {
					this.$refs.scanPopup.openScanPopup(this.businessType);
				}
			},
			selectItem(item) {
				this.$refs.scanPopup.closeScanPopup();
				this.openJobDetail(item, this.scanMessage);
			},
			getScanResult(result) {
				let balance = result.balance;
				if (balance != null) {
					this.scanMessage = ""
					if (!result.label.batch) {
						this.showMessage("批次为空")
						return;
					}
					if (!result.label.itemCode) {
						this.showMessage("物料号为空")
						return;
					}
					try {
						var filters = [{
								column: "status",
								action: "in",
								value: '1,2'
							},
							{
								column: "batch",
								action: "==",
								value: result.label.batch
							},
							{
								column: "itemCode",
								action: "==",
								value: result.label.itemCode
							},
							{
								column: "fromLocationCode",
								action: "==",
								value: balance.locationCode
							}
						]
						getRepleinshJobList({
							filters: filters,
							pageNo: 1,
							pageSize: 1000,
							sort: 'createTime',
							by: 'asc'
						}).then(res => {
							this.scanMessage = result.scanMessage
							let resultList = res.data.list;
							if (resultList.length > 0) {
								resultList.forEach(item => {
									item.title = item.number;
									item.selected = false
								})
								let list = []
								resultList.forEach(item => {
									if (!list.find(subItem => subItem.title == item.title)) {
										list.push(item)
									}
								})
								if (list.length > 0) {
									this.selectItem(list[0])
								}
							} else {
								this.showMessage("按来源库位[" + balance.locationCode + "]批次[" + result.label.batch +
									"]物料号[" + result.label.itemCode + "]未查找到任务\n" + "扫描[" + result
									.scanMessage + "]")			
							}
						}).catch(error => {
							this.showMessage(error + "\n扫描[" + result.scanMessage + "]")
						})

					} catch (e) {
						this.showMessage(e.message)
					}
				}
				// else
				// {
				// 	this.showMessage(error + "\n扫描[" + result.scanMessage + "]")
				// }
			},
		}
	}
</script>

<style scoped lang="scss">

</style>