<template>
	<view class="">
		<com-empty-view v-if="jobList.length==0"></com-empty-view>
		<job-filter ref="filter" otherTitle="" @switchChangeToday="switchChangeToday"
			@switchChangeWait="switchChangeWait" @onScanNumber="getScanNumber" :checkedToday="checkedToday"
			:checkedWaitTask="checkedWaitTask">
		</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:detailOptions"
						@click="swipeClick($event,item)">
						<comOverPackJobCard :dataContent="item" @click='openJobDetail(item)'></comOverPackJobCard>
					</uni-swipe-action-item>
				</view>
			</uni-swipe-action>

			<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' 
		:isCheckLocationBalance="false"
		:bussinessCode="businessTypeCode">
		</winComScanBalance>
		<!-- <winScanPackJob ref="scanPopup" @getResult='getScanResult'></winScanPackJob> -->
		<jobList ref="jobList" @selectItem="selectItem"></jobList>
		<comMessage ref="comMessage"></comMessage>
	</view>
</template>

<script>
	import {
		cancleTakeOverPageJob,
		getOverPageJobList,
	} from '@/api/request2.js';
	import {
		goHome,
		updateTitle
	} from '@/common/basic.js';
	
	import {
		getBusinessType
	} from '@/common/record.js';
	import {
		planRefreshTime
	} from '@/common/config.js';

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

	import comEmptyView from '@/mycomponents/common/comEmptyView.vue'
	import jobFilter from '@/mycomponents/job/jobFilter.vue'
	import comOverPackJobCard from '@/pages/package/coms/comOverPackJobCard.vue'
	import jobInfoPopup from '@/pages/issue/coms/jobInfoPopup.vue'
	import winScanButton from '@/mycomponents/scan/winScanButton.vue'
	import winComScanBalance from '@/mycomponents/scan/winComScanBalance.vue'
	import jobList from '@/mycomponents/jobList/jobList.vue'

	export default {
		name: 'issue',
		components: {
			comEmptyView,
			jobFilter,
			comOverPackJobCard,
			jobInfoPopup,
			winComScanBalance,
			winScanButton,
			jobList
		},
		data() {
			return {
				jobList: [],
				pageNo: 1,
				pageSize: 10,
				totalCount: 0,
				loadingType: "nomore",
				checkedToday: false,
				checkedWaitTask: false,
				todayTime: "",
				status: '1,2', //待处理 、进行中
				detailOptions: [],
				detailGiveupOptions: [],
				title:'',
				businessTypeCode: "OverPackage",
				businessType: null,
				timer:null,
				scanMessage:""
				
			};
		},
			
		onLoad(option){
			this.title = option.title
		},

		onShow() {
			
			this.timerRefresh();
		},
		
		onHide() {
			this.stopRefresh();
		},
		
		onUnload(){
			this.stopRefresh();
		},

		onReady() {
			this.detailOptions = getDetailOption();
			this.detailGiveupOptions = getDetailGiveupOption();
		},
		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.openFilter();
			}
		},

		methods: {
			getBusinessTypeFunc() {
				getBusinessType(this.businessTypeCode, res => {
					if (res.success) {
						this.businessType = res.businessType;
						this.openScanPopup();
					} else {
						this.showErrorMessage(res.message)
					}
				});
			},
			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;
				}
			},
			getList(type) {
				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
				})

				var params = {
					filters: filters,
					pageNo: this.pageNo,
					pageSize: this.pageSize,
				}
				getOverPageJobList(params).then(res => {
					uni.hideLoading();
					if (type === "refresh") {
						uni.stopPullDownRefresh();
					}
					var list = res.data.list;
					this.totalCount = res.data.total
					this.loadingType = "loadmore";
					if (list == null || list.length == 0) {
						this.loadingType = "nomore";
						return;
					}
					this.jobList = type === "refresh" ? list : this.jobList.concat(list);
					this.pageNo++;
					updateTitle(this.title+"(" + this.totalCount + ")");

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

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

				getPurchasereceiptByAsnNumber(code).then(res => {
					uni.hideLoading();
					if (res.data.total == 0) {
						that.showMessage('未查找到' + '【' + code + '】的收货任务');
					} else if (res.data.total == 1) {
						this.$refs.scanAsnNumber.closeScanPopup();
						that.openJobDetail(res.data.list[0]);
					} else {
						this.$refs.scanAsnNumber.closeScanPopup();
						that.showItemList(res.data.list);
					}

				}).catch(error => {
					uni.hideLoading();
					that.showErrorMessage(error);
				})
			},


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

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

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

			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);
							}
						});
				}
			},

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

			cancleJob(id) {
				cancleTakeOverPageJob(id).then(res => {
					if(res.data){
						this.getList("refresh")
						uni.showToast({
							title:"放弃任务成功"
						})
					}else {
						this.showMessage("放弃任务失败")
					}
				}).catch(error => {
					this.showMessage(error)
				})
			},

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

			switchChangeWait(state, jobStatus) {
				this.checkedWaitTask = state;
				this.status = jobStatus;
				this.getList("refresh");
			},

			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,
				}
				getOverPageJobList(params).then(res => {
					uni.hideLoading();
					if (res.data.list.length == 0) {
						that.showMessage('未查找到' + '【' + code + '】的发料任务');
					} else if (res.data.list.length == 1) {
						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);
				}
			},
			
			getJobInfoByNumber(number,scanMessage){
				console.log("扫描",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,
				}
				getOverPageJobList(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) {
									this.getList('refresh')
								}
							});
							
							return;
						}
						uni.navigateTo({
							url: './overPackageJobDetail?id=' + result.masterId + '&status=' + result.status+'&title='+this.title+'&scanMessage=' +
								scanMessage 
						});
						this.scanMessage=""
					}
				}).catch(error => {
					uni.hideLoading();
					that.showMessage(error);
				})
			},
			
			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
							}
						]
						getOverPageJobList({
							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>
