<template>
	<view class="">
		<com-empty-view v-if="jobList.length==0"></com-empty-view>
		<job-filter :isShowFromLocationCode="true" :isShowFromAreaCode="true" :isShowToAreaCode="true"
			:isShowProductionLineCode="true" 
			:productionline="productionlineList"
			ref="filter" otherTitle="" :isShowItemCode="true"
			@onQuery="getListByFilter" :isShowQurery='true'>
		</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-issue-job-card :dataContent="item" @click='openJobDetail(item)'></com-issue-job-card>

					</uni-swipe-action-item>
				</view>
			</uni-swipe-action>

			<job-list-popup ref="jobListPopup" @selectedItem="selectedItem"></job-list-popup>
			<job-info-popup ref='jobInfoPopup'></job-info-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> -->
		<jobList ref="jobList" @selectItem="selectItem"></jobList>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		cancleTakeIssueJob,
		getIssueJobList,
		getIssueJobByProductionline,
		closeTakeIssueJob
	} from '@/api/request2.js';
	import {
		goHome,
		updateTitle
	} from '@/common/basic.js';

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

	import {
		planRefreshTime,
		issueJobFilter
	} from '@/common/config.js';


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

	import comEmptyView from '@/mycomponents/common/comEmptyView.vue'
	import jobFilter from '@/mycomponents/job/jobFilter.vue'
	import comIssueJobCard from '@/pages/issue/coms/comIssueJobCard.vue'
	import jobListPopup from '@/pages/issue/coms/jobListPopup.vue'
	import jobInfoPopup from '@/pages/issue/coms/jobInfoPopup.vue'
	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import winScanPackJob from "@/mycomponents/scan/winScanPackJob.vue"
	import jobList from '@/mycomponents/jobList/jobList.vue'
	import winComScanBalance from '@/mycomponents/scan/winComScanBalance.vue'

	export default {
		name: 'issue',
		components: {
			comEmptyView,
			jobFilter,
			comIssueJobCard,
			jobListPopup,
			jobInfoPopup,
			winScanPackJob,
			winScanButton,
			jobList,
			winComScanBalance
		},
		data() {
			return {
				jobList: [],
				pageNo: 1,
				pageSize: 10,
				totalCount: 0,
				loadingType: "nomore",
				checkedToday: false,
				checkedWaitTask: false,
				todayTime: "",
				status: '1,2', //待处理 、进行中
				detailOptions: [],
				detailGiveupOptions: [],
				productionlineList: [],
				detailCloseOptions: [],
				title: '',
				productionLine: "",
				fromLocation: "",
				fromAreaCode: '', // 来源库区
				toAreaCode: '', // 到库区
				filterItemCode: "",
				businessTypeCode: "Issue",
				businessType: null,
				timer: null,
				productionLineCode:""
			};
		},
		onLoad(option) {
			this.title = option.title
			this.getIssueJobByProductionline()
		},
		onShow() {
			this.getList('refresh')
		},

		onHide() {
			// this.stopRefresh();
		},

		onUnload() {
			// this.stopRefresh();
		},

		onReady() {
			this.detailOptions = getDetailOption();
			this.detailGiveupOptions = getDetailGiveupOption();
			this.detailCloseOptions = getDetailCloseOption();
		},
		onReachBottom() {
			//避免多次触发
			if (this.loadingType == 'loading' || this.loadingType == 'nomore') {
				return;
			}

			this.getList('more')


		},

		onPullDownRefresh() {

			this.getList('refresh')
		},

		//后退按钮
		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.openFilterParams(uni.getStorageSync(issueJobFilter));
			}
		},

		methods: {
			timerRefresh() {
				this.getList('refresh')
				this.stopRefresh();
				var that = this;
				this.timer = setInterval(function() {
					that.getList('refresh')
					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();
						this.$refs.scanPopup.openScanPopup(this.businessType);
					} else {
						this.showErrorMessage(res.message)
					}
				});
			},

			getIssueJobByProductionline() {
				getIssueJobByProductionline().then(res => {
					if (res.code == 0) {
						this.productionlineList = res.data.map(item => ({
							value: item.value,
							text: item.name
						}))
						this.productionlineList.unshift({
							value: "",
							text: "全部"
						})
					} else {
						this.productionlineList = []
					}
				})
			},

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

				this.loadingType = "loading";
				if (type === "refresh") {
					this.pageNo = 1;
					this.jobList = [];
				}
				var queryFiltersParams =this.setQueryParam()
				var params = {
					filters: queryFiltersParams,
					pageNo: this.pageNo,
					pageSize: this.pageSize,
				}
				
				console.log("查询条件",JSON.stringify(params))
				getIssueJobList(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++;
					if (type === "refresh") {
						uni.stopPullDownRefresh();
					}
					if(this.jobList.length>0){
						this.openScanPopup()
					}
				}).catch(error => {
					if (type === "refresh") {
						uni.stopPullDownRefresh();
					}
					updateTitle(this.title);
					this.loadingType = "";
					uni.hideLoading();
					that.showMessage(error)
				})
			},

			setQueryParam() {
				var filterParams = []
				var queryParams=uni.getStorageSync(issueJobFilter)
				// if(!queryParams){
				// 	queryParams={
				// 	}
				// 	queryParams.status="1,2"
				// }
				
				//只看当天
				if (queryParams.creationTime ) {
					filterParams.push({
						column: "create_time",
						action: "betweeen",
						value: queryParams.creationTime
					})
				}
				//只看待处理
				if (queryParams.status) {
					filterParams.push({
						column: "status",
						action: "in",
						value: queryParams.status
					})
				}else {
					filterParams.push({
						column: "status",
						action: "in",
						value: "1,2"
					})
				}

				//生产线
				if (queryParams.productionLineCode) {
					filterParams.push({
						column: "productionLineCode",
						action: "==",
						value: queryParams.productionLineCode
					})
				}
				//物料代码
				if (queryParams.itemCode) {
					filterParams.push({
						column: "itemCode",
						action: "like",
						value: queryParams.itemCode
					})
				}

				//来源库位
				if (queryParams.fromLocationCode) {
					filterParams.push({
						column: "fromLocationCode",
						action: "==",
						value: queryParams.fromLocationCode
					})
				}

				//来源库区
				if (queryParams.fromAreaCode) {
					filterParams.push({
						column: "fromAreaCode",
						action: "==",
						value: queryParams.fromAreaCode
					})
				}
				//到库区
				if (queryParams.toAreaCode) {
					filterParams.push({
						column: "toAreaCode",
						action: "==",
						value: queryParams.toAreaCode
					})
				}
				return filterParams;

			},

			getListByFilter(params) {
				this.productionLineCode =params.productionLineCode
				uni.setStorageSync(issueJobFilter,params)
				this.getList('refresh')
			},


			openJobDetail(item, scanMessage = '') {
				this.getJobInfoByNumber(item.number, scanMessage)

			},

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

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

			selectItem(item) {
				this.$refs.scanPopup.closeScanPopup();
				this.openJobDetail(item, this.scanMessage);
			},

			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) {
				cancleTakeIssueJob(id).then(res => {
					if (res.data) {
						this.getList('refresh')

						uni.showToast({
							title: "放弃任务成功"
						})
					} else {
						this.showMessage("放弃任务失败")
					}
				}).catch(error => {
					this.showMessage(error)
				})
			},
			closeJob(id) {
				uni.showLoading({
					title: "加载中....",
					mask: true
				});

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

			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: this.pageSize,
				}
				getIssueJobList(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')
									}
								});

							return;
						}
						uni.navigateTo({
							url: './issueDetail?id=' + result.masterId + '&status=' + result.status +
								'&scanMessage=' +
								scanMessage + '&title=' + this.title
						});
						this.scanMessage = ""
					}
				}).catch(error => {
					uni.hideLoading();
					that.showMessage(error);
				})
			},


			showMessage(message) {
				this.$refs.comMessage.showErrorMessage(message, res => {
					if (res) {
						if (this.$refs.scanPopup) {
							this.$refs.scanPopup.getfocus()
						}
					}
				});
			},
			openScanPopup() {
				if (this.businessType == null) {
					this.getBusinessTypeFunc()
				} else {
					this.$refs.scanPopup.openScanPopup(this.businessType);
				}
			},
			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
							}
						]
						if(productionLineCode){
							filters.push({
								column: "productionLineCode",
								action: "==",
								value: productionLineCode
							})
						}
						
						getIssueJobList({
							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)
					}
				}
			},
		}
	}
</script>

<style scoped lang="scss">

</style>