<template>
	<view class="page">
		<view class="uni-flex uni-row">
			<!-- 	<sl-filter :ref="'slFilter'" :menuList.sync="menuList" @result="getFilter"></sl-filter> -->
			<view class="otherFixed97">
				<view class="text "  @click="selectDevice">{{deviceName.name}}</view>
				<view class="text "  @click="selectMaterial">{{materielName.name}}</view>
				<view class="text "  @click="selectOperater">{{userName.name}}</view>
				<view class="text" @click="filterDate">{{timeData.begin==''?'报工时间':(timeData.begin+'~'+timeData.end)}}</view>
			</view>
		</view>
		<view class="example-body mt" 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="gotoProcessCheckout(item.id)"></dev-block>
		
			</view>
		</view>
		<view class="example-body mt" v-else>
			<no-record ></no-record>
		</view>
		<uni-calendar ref="calendar" :lunar="false" :range="true" @confirm="confirmDate" />
		<uni-load-more  :status="loading_status"></uni-load-more>
		<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>
		</view>
		<view class="mysearchlist" style="z-index: 10000;">
			<chooseEquipmentSingle ref="mysearchlist" 
				:showsearch.sync="show_search_user3"
				:device_type='device_type'
				:itemInfo_.sync="search_value_user3">
			</chooseEquipmentSingle>
		</view>
		<chooseMaterialSingle ref="mysearchlist"
			:showsearch.sync="show_search_user1"
			:itemInfo_.sync="search_value_user1">
		</chooseMaterialSingle>
	</view>
</template>

<script>
import noRecord from '@/components/xinsoft-no-record/xinsoft-no-record';
import chooseMaterialSingle from '@/components/xinsoft-search-list/chooseMaterialSingle.vue'
import chooseEquipmentSingle from '@/components/xinsoft-search-list/chooseEquipmentSingle.vue';
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 uniCalendar from '@/components/uni-calendar/uni-calendar.vue'
import jweixin from '@/jweixin-module/index.js';
import chooseUserSingle from '@/components/xinsoft-search-list/chooseUserSingle.vue';
export default {
	components:{
		chooseMaterialSingle,
		chooseEquipmentSingle,chooseUserSingle,noRecord,slFilter,devBlock,uniIcons,uniLoadMore,uniCalendar,
	},
	data() {
		return {
		device_type:'',//设备类型
		show_search_user:false,
		search_value_user:"",
		show_search_user1:false,
		search_value_user1:[],
		show_search_user3:false,
		search_value_user3:[],
		pagenumber:1,//当前第几页
		pagesize:5,//每页加载数据条数	
		filter:{},
		listCards: [],
		pickerValueDefault: [0, 0],
		deepLength: 2,
		fixed: true,
		filterResult: {
			processCode: '',
			// workOrderNo:''
		},
		menuList: [{
				'title': '设备',
				'isMutiple': false,
				'key': 'deviceName',
				'detailList': [],
				'defaultSelectedIndex': []
			},
			{
				'title': '产品名称',
				'isMutiple': false,
				'key': 'materielName',
				'detailList': [],
				'defaultSelectedIndex': []
			},
			// {
			// 	'title': '操作工',
			// 	'isMutiple': false,
			// 	'key': 'operatorName',
			// 	'detailList': [],
			// 	'defaultSelectedIndex': []
			// },
		],
		// deviceName: '',
		// materielName: '',
		operatorName: '',
		timeData: {
			begin: "",
			end: ''
		},
		userName:{
			value:'',
			name:'操作工'
		},
		deviceName:{
			value:'',
			name:'设备'
		},
		materielName:{
			value:'',
			name:'产品名称'
		},
		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() {
		
	},
	mounted() {
		this.initiateWX()
	},
	created() {
		this.getReportList()	
		var userInfo  = uni.getStorageSync('userInfo');
		this.filter = {
			status: 56,
			heldPerson: userInfo.name
		}
		// 初始化设备名称
		var _this = this;
		this.$http.request({
			url: 'apis/device/allDevice',
		}).then(res => {
			if (res.statusCode == '200') {
				_this.menuList[0].detailList = [{
					'title': '不限',
					'value': ''
				}];
				var useType = res.data.data;
				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/materiel/list',
			method: 'GET',
		}).then(res=>{
			if (res.statusCode == '200') {
				_this.menuList[1].detailList = [{
					'title': '不限',
					'value': ''
				}];
				var useType = res.data.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);
		});
		//操作工
		// this.$http.request({
		//   url: '/apis/common/getUsers',
		//   params:{
		// 	  deptId:userInfo.deptId
		//   }
		// }).then(res=>{
		// 	if(res.statusCode == '200'){
		// 		_this.menuList[2].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,
		// 					'value': useType[i].name
		// 		    	}
		// 			_this.menuList[2].detailList.push(myVal);
		// 		}
		// 	}
		// }).catch(err=>{
		// });
	},
	//滚动到底部加载下一页
	onReachBottom(obj){
		if(this.loading_status=='noMore'){
			return false;
		}
		this.pagenumber++;
		this.getReportList();
	},
	//下拉刷新
	onPullDownRefresh(){
		this.listCards=[];
		this.pagenumber=1;
		this.loading_status="more";
		this.getReportList();
		  
	},
	watch:{
		search_value_user(newv){
			// this.$set(this.dataList[this.currentIndex],'operator',newv.userId);
			this.$set(this.userName,'name',newv.NAME);
			this.operatorName = newv.NAME;
			this.listCards=[];
			this.page=1;
			this.loading_status="more";
			this.getReportList();
		},
		search_value_user3(newv){
			this.$set(this.deviceName,'value',newv.id);
			this.$set(this.deviceName,'name',newv.name);
			// this.filterResult.deviceName = newv.name;
			// this.filterResult.deviceId = newv.id;
			this.listCards=[];
			this.pagenumber=1;
			this.loading_status="more";
			this.getReportList();
		},
		search_value_user1(newv){
			// this.$set(this.dataList[this.currentIndex],'operator',newv.userId);
			this.$set(this.materielName,'name',newv.name);
			this.$set(this.materielName,'value',newv.id);
			// this.filterResult.materielName = newv.name;
			// this.filterResult.materielId = newv.id;
			this.listCards=[];
			this.pagenumber=1;
			this.loading_status="more";
			this.getReportList();
		},
	},
	methods: {
		// 选择填表人
		selectOperater(){
			this.show_search_user=true;
		},
		// 选择设备
		selectDevice(){
			this.show_search_user3=true;
		},
		// 选择物料
		selectMaterial(){
			this.show_search_user1=true;
		},
		
		//获取微信相关
				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 {
									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.getReportList(1)
				},
		
		
		getReportList(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.deviceId=this.deviceName.value;
			this.filterResult.materialId=this.materielName.value;
			this.filterResult.operatorName=this.operatorName;
			this.filterResult.createTime = this.timeData.begin;
			this.filterResult.isExamine = 1;
			this.$http.request({
				url: '/apis/mes/processReport/listOfReport',
				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";
			})
		},
		formaterData(data) {
			var resData = [];
			data.forEach((vals, index) => {
				var combineJSON = {
					id: vals.id,
					title: "报工单" + ":" + vals.code,
					titleNumber: "报工时间" + ":" + vals.createTime,
					contentList: [{
							id: 1,
							isDouble: false,
							labelName: '产品名称',
							labelContent: vals.materialName
						},
						{
							id: 2,
							isDouble: false,
							labelName: '规格型号',
							labelContent: vals.specification
						},
						{
							id: 3,
							isDouble: true,
							labelName: '计划数量',
							labelContent: vals.planCount
						},
						{
							id: 4,
							isDouble: true,
							labelName: '设备',
							labelContent: vals.deviceName
						},
						{
							id: 5,
							isDouble: true,
							labelName: '工序',
							labelContent: vals.processName
						},
						{
							id: 6,
							isDouble: true,
							labelName: '操作工',
							labelContent: vals.operatorName
						},
						{
							id: 7,
							isDouble: false,
							labelName: '计划开工日期',
							labelContent: vals.startTime?vals.startTime.substr(0,10):''
						},
						{
							id: 8,
							isDouble: false,
							labelName: '计划完工日期',
							labelContent: vals.endTime?vals.endTime.substr(0,10):''
						},
					],
					note: '检验',
					extra: vals.statusName,
					tagType: this.setTag(vals.status),
				}
				resData.push(combineJSON);
			});
			return resData;
		},
		setTag(val) {
			if (val == 148) {
				return "106";
			} 
			 else {
				return "107";
			}
		},
		//筛选条件
		getFilter(filterRes) {
			this.deviceName=filterRes.deviceName;
			this.materielName=filterRes.materielName;
			// this.operatorName=filterRes.operatorName;
			this.listCards=[];
			this.pagenumber=1;
			this.loading_status="more";
			this.getReportList()			
		},
		/*
		 * 日历相关方法。
		 */
		filterDate() {
			this.$refs.calendar.open()
		},
		confirmDate(e) {
			if (e.range.begin && e.range.end) {
				this.timeData = {
					begin: e.range.begin + ' 00:00:00',
					end: e.range.end + ' 00:00:00'
				}
				this.listCards=[];
				this.pagenumber=1;
				this.loading_status="more";
				this.getReportList()
			}
		},
		gotoProcessCheckout(id) {
			uni.removeStorageSync('processCheckoutInfo');
			uni.navigateTo({
			    url: 'processCheckout?id='+id
			});
		}
	}
}
</script>

<style scoped>
	>>>.select-tab-fixed-top{
		left: 0;
		width: 50%;
	}
	.mt {
		margin-top: 50px;
	}
</style>
