<template>
	<view class="content">
		<view class="filter_container">
			<view class="search_container" @click="toSearch()">
				<uni-icons class="search_icon" type="search" size="20" v-model="filterResult.materielName" color="#bdbdbd"></uni-icons>
				<input style="text1" class="input-" size="20" placeholder="物料名称" v-model="filterResult.materielName" />
			</view>
		</view>
		<xinsoft-sl-filter  ref="slFilter"  :menuList.sync="menuList" @result="getFilter"></xinsoft-sl-filter>
		<view class="example-body" v-if="listCards.length>0">
			<view v-for="(item,index) in listCards" :key="index" class="example-box" style="position: relative;flex: 1;" >
				<dev-block :title="item.title" :titleNumber="item.titleNumber" :note="item.note" :extra="item.extra" :tagType="item.tagType"
				 :contentList="item.contentList" @click="toIsDispatchin(item)" ></dev-block>
			</view>
			<uni-load-more  :status="loading_status"></uni-load-more>
			<view class="goHome" @click='goMain()'>
				<img src="../../static/img/gohome.png">
			</view>
		</view>
		<view class="example-body" v-else>
			<no-record ></no-record>
		</view>
	</view>
</template>

<script>
import noRecord from '@/components/xinsoft-no-record/xinsoft-no-record';
import slFilter from '@/components/xinsoft-sl-filter/xinsoft-sl-filter.vue';
import devBlock from '@/components/xinsoft-dev-block/xinsoft-dev-block.vue'
import uniIcons from '@/components/uni-icons/uni-icons.vue'
import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue'
import jweixin from '@/jweixin-module/index.js';
export default {
	components: {
		slFilter,noRecord,devBlock,uniIcons,uniLoadMore
	},
	data() {
		return {
		pagenumber:1,//当前第几页
		pagesize:5,//每页加载数据条数
		filterResult: {
			processCode: '',
			materielName:'',
			priority:'',
			workOrderNo:''
		},
		fixed: true,
		menuList: [{
				'title': '工序',
				'isMutiple': false,
				'key': 'processId',
				'detailList': [],
				'defaultSelectedIndex': []
			},
			{
				'title': '优先级',
				'isMutiple': false,
				'key': 'priority',
				'detailList': [],
				'defaultSelectedIndex': []
			}
		],
		listCards: [],
		dataList: [],
		loading_status: 'more',//more（loading前）、loading（loading中）、noMore（没有更多了）
		}
	},
	onShow(){
		var _this=this;
		this.$eventHub.$on('changestate', function (data) {
			var datajson=data;
			if(datajson.id){
				for(var i=0;i<_this.listCards.length;i++){
					if(_this.listCards[i].id==datajson.id){
						 var str=_this.listCards[i].title;
						_this.listCards[i].title=str.split('-')[0]+"-"+datajson.state;
					}
				}
			}
			_this.$eventHub.$off('changestate');
		});	
	},
	onLoad() {
		var userInfo =  uni.getStorageSync('userInfo');
		if(userInfo!=''&&userInfo!=undefined){

			this.dataList=userInfo;
		}
		this.getDispatch({});
	},
	//滚动到底部加载下一页
	onReachBottom(obj){
		if(this.loading_status=='noMore'){
			return false;
		}
		this.pagenumber++;
		this.getDispatch();
	},
	//下拉刷新
	onPullDownRefresh(){
		this.listCards=[];
		this.pagenumber=1;
		this.loading_status="more";
		this.getDispatch();
		  
	},
	mounted() {
		this.initiateWX()
	},
	created() {
		// 初始化工序
		var _this = this;
		this.$http.request({
			url: '/apis/mes/process/processOfList',
		}).then(res => {
			if (res.statusCode == '200') {
				_this.menuList[0].detailList = [{
					'title': '不限',
					'value': ''
				}];
				var useType = res.data.data.datas
				console.log(useType)
				for (let i = 0; i < useType.length; i++) {
					var myVal = {
						'title': useType[i].name,
						'value': useType[i].id
					}
					_this.menuList[0].detailList.push(myVal);
				}
			}
		}).catch(err => {
			console.log(err);
		});
		//优先级初始化
		this.$http.request({
		  url: '/apis/dict/getDictsByType',
		  params: {
		    type: 'priority'
		  },
		}).then(res=>{
			if(res.statusCode == '200'){
				_this.menuList[1].detailList = [
					{
						'title': '不限',
						'value': ''
					}
				];
				var useType = res.data.datas;
				for (let i = 0; i < useType.length; i++) {
				    var myVal=
				    	{
				    		'title': useType[i].name,
				    		'value': useType[i].id
				    	}
				    _this.menuList[1].detailList.push(myVal);
				}
			}
		}).catch(err=>{
			console.log(err);
		});
	},
	methods: {
		// 按物料名称查询
		toSearch() {
			this.getDispatch(1)
		},
		//筛选条件
		getFilter(filterRes) {
			this.filterResult.processId=filterRes.processId;
			this.filterResult.priority=filterRes.priority;
			this.listCards=[];
			this.pagenumber=1;
			this.loading_status="more";
			this.getDispatch();				
		},
		
		//获取微信相关
		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 {
							// alert(resultStr)
							resultStr = JSON.parse(resultStr);
							if (resultStr.code || resultStr.planNo) {
								if(resultStr.code) {
									_this.filterResult.processCode = resultStr.code
									_this.getQrCodeInfo();
								}
								if(resultStr.planNo) {
									_this.filterResult.workOrderNo = resultStr.planNo
									_this.getQrCodeInfo();
								}
							}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() {
			// this.filterResult.processCode = code
			this.getDispatch(1)
		},
		
		
		
		getDispatch(n) {
			if(n==1){
				this.pagenumber=1
				this.listCards=[]
			}
			this.loading_status="loading";
			// var filterRes = {};
			this.filterResult.pageno = this.pagenumber;
			this.filterResult.pagesize = this.pagesize;
			this.filterResult.deptId = this.dataList.deptId;
			this.filterResult.isDispatching = 1
			// alert("this.filterResult:"+JSON.stringify(this.filterResult))
			this.$http.request({
				url: '/apis/mes/dispatch/disptchOfList',
				params: this.filterResult,
				})
				.then(res => {
					uni.stopPullDownRefresh();
					if(!res.data.data){
					this.loading_status="noMore";
					}else if(res.data.data.datas.length<this.pagesize){
						this.loading_status="noMore";
					}else{
						this.loading_status="more";
					}
					
					if (res.data.code == 0) {
						this.listCards = this.listCards.concat(this.formaterData(res.data.data.datas));
					}
				}).catch(err => {
					this.loading_status="noMore";
				});
			},
		setTag(val) {
			if (val == '派工完毕') {
				return "106";
			} else {
				return "108";
			} 
		},
		formaterData(data) {
			var resData = [];
			data.forEach((vals, index) => {
				var combineJSON = {
					id: vals.planItemId,
					title: "工序计划单号"+":"+vals.workOrderNo,
					titleNumber: vals.processName?"工序名称"+":"+vals.processName:' ',
					contentList: [{
							id: 1,
							isDouble: false,
							labelName: '物料名称',
							labelContent: vals.materielName
						},
						{
							id: 2,
							isDouble: false,
							labelName: '规格型号',
							labelContent: vals.specification
						},
						{
							id: 3,
							isDouble: false,
							labelName: '批次号',
							labelContent: vals.batchNo
						},
						{
							id: 4,
							isDouble: false,
							labelName: '已派/待派/计划',
							labelContent: vals.alreadyCount+"/"+(vals.planCount-vals.alreadyCount)+"/"+vals.planCount
						},
						{
							id: 5,
							isDouble: false,
							labelName: '优先级',
							labelContent: vals.priorityName
						},
						{
							id: 6,
							isDouble: false,
							labelName: '计划开工日期',
							labelContent: vals.planStartTime?vals.planStartTime.substr(0,10):''
						},
						{
							id: 7,
							isDouble: false,
							labelName: '计划完工日期',
							labelContent: vals.planEndTime?vals.planEndTime.substr(0,10):''
						}
					],
					note:vals.planCount-vals.alreadyCount != 0?'派工':'',
					extra: vals.isDispatchin,
					alreadyCount:vals.alreadyCount,
					tagType: this.setTag(vals.isDispatchingName),
					planCount:vals.planCount,
					isOutsource: vals.isOutsource
				}
				resData.push(combineJSON);
			});
			return resData;
		},
		toIsDispatchin(item) {
			if(item.planCount-item.alreadyCount == 0) {
				return
			} else {
				uni.removeStorageSync('dispatchingInfo');
				uni.navigateTo({
				    url: 'dispatching?planItemId='+item.id+"&isOutsource="+item.isOutsource
				});
			}
		}
	},
	
	
	onBackPress(options) { //取消默认的返回事件.
		uni.switchTab({
			url: "../main/main"
		});
		return true;
	}
}
</script>

<style scoped>
	uni-input {
	    position: relative;
	    top: 4px;
		color: rgb(102, 102, 102);
	    display: block;
	    font-size: 13px;
	    line-height: 1.4em;
	    height: 1.4em;
	    min-height: 1.4em;
	    overflow: hidden;
	}
	.content{
		position: relative;
	}
	.filter_container {
		position: fixed;
		width: 50%;
		top: var(--window-top);
		background-color: #fff;
		height: 40px;
		z-index: 2;
		padding-top: 7px;
		box-sizing: border-box;
	}
	>>>.doubleList:nth-of-type(1) {
			width: 60%;
		}
	
		>>>.doubleList:nth-of-type(2) {
			width: 40%;
		}
	
		>>>.doubleList:nth-of-type(3) {
			width: 60%;
		}
		>>>.doubleList:nth-of-type(4) {
			width: 40%;
		}
		>>>.dev-label{
			white-space: nowrap;
		}
	>>>.select-tab-fixed-top{
		right: 0;
		width: 50%;
		z-index: 2;
		top:var(--window-top);
		white-space: nowrap
	}
	>>>.popup-layer{
		position: fixed;
		top: var(--window-top);
		margin-top: 40px;
	}
	>>>.filter-content-detail{
	/* 	position: relative;
		height: 90px;
		overflow: scroll; */
	}
		.search_container {
			position: relative;
			padding-left: 30px;
			box-sizing: border-box;
			color: #bdbdbd;
			margin: auto;
			width: 80%;
			height: 26px;
			background-color: #F6F6F6;
			border-radius: 26px;
			font-size: 14px;
			line-height: 26px;
		}
	.search_icon{
		position: absolute;
		left: 5px;
		top: 3px;
	}
		.fliter_content {
			position: absolute;
			right: 15px;
			left: 85px;
			height: 100%;
			z-index: 2;
		}
		.arrowright{
			position: absolute;
			right: 30upx;
			bottom: 30upx;
			font-size: 40upx !important;
		}
		>>>.dev-block__content{
			padding-right: 36upx;
		}
		>>>.dev-block__header-title-text{
			overflow: auto;
			white-space: pre-wrap !important;
			
		}
	
	
	
	/* >>>.select-tab >>>.select-tab-item[data-v-fe683d44],
	>>>.select-tab-fixed-top >>>.select-tab-item[data-v-fe683d44] {
	    width: 100% !important;
	} */
	.arrowright{
		position: absolute;
		right: 30upx;
		bottom: 30upx;
		font-size: 40upx !important;
	}
	>>>.dev-block__content{
		padding-right: 36upx;
	}
	>>>.popup-layer{
		position: fixed;
		top: var(--window-top);
		margin-top: 40px;
	}
</style>

