<template>
	<view class="page">
		<view class="uni-flex uni-row">
			<sl-filter :ref="'slFilter'" :menuList.sync="menuList" @result="filterConfirm"></sl-filter>
			<view class="otherFixed1">
				<view class="text "  @click="selectOperater">{{userName.name}}</view>
				<view class="text "  @click="showSinglePicker">{{deptResult.name}}</view>
				<view class="text"  @click="filterDate">{{timeData.begin==''?'填报时间':(timeData.begin+'~'+timeData.end)}}</view>
			</view>
		</view>
		<view class="mybox" v-if="listCards.length>0">
			<view v-for="(item,index) in listCards" :key="index" class="example-box" style="position: relative;"  @click="clickDetail(item)">
				<dev-block :title="item.title" :titleNumber="item.titleNumber" :note="item.note" 
				:extra="item.extra"  :tagType="item.tagType"
				:contentList="item.contentList"></dev-block>
			</view>
			<uni-load-more  :status="loading_status" ></uni-load-more>
		</view>
		<view class="mybox" v-else>
			<no-record ></no-record>
		</view>
		<view class="goHome" @click='goMain("purchaseInfo")'>
			<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>
		<uni-calendar ref="calendar" :lunar="false" :range="true"  @confirm="confirmDate"  @cancel='cancleData'/>
		<lb-picker ref="picker" mode="multiSelector" :level="level" :pickerValueDefault="[0,0]"
		  @confirm="pickerConfirm" :props="myProps" :list="deptArray"></lb-picker>
	</view>
</template>

<script>
	import LbPicker from '@/components/lb-picker'
	import mpvuePicker from '@/components/mpvue-picker/mpvuePicker.vue';
	import slFilter from '@/components/xinsoft-sl-filter/xinsoft-sl-filter.vue';
	import devBlock from '@/components/xinsoft-dev-block/xinsoft-dev-block.vue'
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import noRecord from '@/components/xinsoft-no-record/xinsoft-no-record';
	import uniBadge from '@/components/uni-badge/uni-badge.vue'
	import uniCalendar from '@/components/uni-calendar/uni-calendar.vue'
	import chooseUserSingle from '@/components/xinsoft-search-list/chooseUserSingle.vue';
	export default {
		components: {
			chooseUserSingle,LbPicker,devBlock,uniLoadMore,noRecord,uniBadge,uniCalendar,mpvuePicker,slFilter
		},
		data() {
			return {
				show_search_user:false,
				search_value_user:"",
				current_num:2,
				deptArray:[],
				level:4,
				myProps: {
				      label: 'text',
				      value: 'id',
				      children: 'children'
				    },
				menuList: [{
						'title': '我审批的',
						'isMutiple': false,
						'key': 'num',
						'detailList': [
							{
								'title': '我发起的',
								'value': 1
							},
							{
								'title': '我审批的',
								'value': 2
							},
							{
								'title': '我的团队',
								'value': 3
							}
						],
						'defaultSelectedIndex':[1]
					},
					// {
					// 	'title': '填报人',
					// 	'isMutiple': false,
					// 	'key': 'userName',
					// 	'detailList': [],
					// 	'defaultSelectedIndex':[]
					// }
				],
				listCards: [],
				//上拉刷新，下拉加载
				loading_status: 'more',//more（loading前）、loading（loading中）、noMore（没有更多了）
				pageSize:5,
				page:1,
				filter:{},
				//日历变量。
				timeData:{
					begin:"",
					end:'' 
				},
				deptResult:{
					value:'',
					name:'部门'
				},
				userName:{
					value:'',
					name:'填报人'
				},
				userInfo:{}
			}
		},
		onLoad() {
			var _this = this;
			this.userInfo  = uni.getStorageSync('userInfo');
			this.filter = {
				approveUserId :this.userInfo.userId
			}
			
			// this.getDept('');
			this.getDept(this.userInfo.deptId);
			
			//人员
			this.$http.request({
			  url: '/apis/common/getUsers',
			  params:{
				  deptId:this.userInfo.deptId
			  }
			}).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,
								'value': useType[i].name
					    	}
					    _this.menuList[1].detailList.push(myVal);
					}
				}
			}).catch(err=>{
			});
			//初始化当前列表。
			this.dataList(this.current_num);
		},
		onReachBottom: function() {
			//下拉刷新的时候请求一次数据
			if(this.loading_status=='noMore'){
				return false;
			}
			this.page++;
		    if(this.current_num == 2){
		    	this.dataList(2);
		    }else{
		    	this.dataList();
		    }
		},
		onPullDownRefresh: function() {
			this.listCards=[];
			this.page=1;
			this.loading_status="more";
			//触底的时候请求数据，即为上拉加载更多
			if(this.current_num == 2){
				this.dataList(2);
			}else{
				this.dataList();
			}
		},
		watch:{
			search_value_user(newv){
				// this.$set(this.dataList[this.currentIndex],'operator',newv.userId);
				this.$set(this.userName,'name',newv.NAME);
				this.filter.userName = newv.NAME;
				this.listCards=[];
				this.page=1;
				this.loading_status="more";
				if(this.current_num == 2){
					this.dataList(2);
				}else{
					this.dataList();
				}
			},
		},
		methods: {
			// 选择填表人
			selectOperater(){
				this.show_search_user=true;
			},
			getDept(deptId){
				//使用部门
				this.$http.request({
				  url: '/apis/dept/tree',
				  params:{
					 deptId:deptId 
				  },
				  method:'GET',
				}).then(res=>{
					if(res.statusCode == '200'){	
						this.deptArray =res.data.data.children
					}
				}).catch(err=>{
					console.log(err);
				});
			},
			
			filterConfirm(f){
				console.log(f)
				//筛选成功。
				var num = f.num;
				if(num == 1 || num == ''){
					this.filter = {
						userId :this.userInfo.userId,
						tabType: 0
					}
				}else if(num == 2){
					this.filter = {
						approveUserId:this.userInfo.userId,
					}
				}else if(num == 3){
					this.filter = {
						deptId:this.userInfo.deptId,
						tabType: 1
					}
				}
				this.current_num = num;
				// this.filter.userName = f.userName;
				this.listCards=[];
				this.page=1;
				this.loading_status="more";
				this.dataList(num);
			},
			dataList(num){
				this.loading_status="loading";
				
				var filterRes = this.filter;
				filterRes.pageno = this.page;
				filterRes.pagesize = this.pageSize;
				filterRes.startTime = this.timeData.begin;
				filterRes.endTime = this.timeData.end;
				filterRes.deptId = (this.deptResult.value || this.filter.deptId || '' )
				if(num == 2){
					filterRes.type = 3;
					this.$http.request({
					  url: '/apis/approveFlow/myApproveList',
					  method:'POST',
					  params:filterRes,
					}).then(res=>{
						uni.stopPullDownRefresh();
						if(!res.data.data){
							this.loading_status="noMore";
						}else if(res.data.data.list.length<this.pagesize){
							this.loading_status="noMore";
						}else{
							this.loading_status="more";
						}
						if(res.data.code == 0){
							if(res.data.data.list.length>0){
								this.listCards =  this.listCards.concat(this.formaterData(res.data.data.list));
							}
						}
					}).catch(err=>{
						this.loading_status="noMore";
					});
				}else{
					this.$http.request({
					  url: '/apis/salesContractApi/salesContractList',
					  method:'GET',
					  params:filterRes,
					}).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){
							if(res.data.data.datas.length>0){
								this.listCards =  this.listCards.concat(this.formaterData(res.data.data.datas));
								
							}
						}
								
					}).catch(err=>{
						this.loading_status="noMore";
					});
				}
			},
			clickDetail(item){
				//点击详情
				if(item.approveState == 0 || item.approveState == 2){ //暂存和退回状态
					// //重置下
					// uni.removeStorageSync('saleContractInfo');
					// //再次编辑。
					// uni.navigateTo({
					// 	url: 'addPurchaseApply?id='+item.id
					// });
					uni.navigateTo({
					    url: 'saleContractDetail?id='+item.salesContractId+'&num='+this.current_num+'&taskId='+item.taskId+'&instanceId='+item.instanceId
					});
				}else{   
					uni.navigateTo({
					    url: 'saleContractDetail?id='+item.salesContractId+'&num='+this.current_num+'&taskId='+item.taskId+'&instanceId='+item.instanceId
					});
				}
			},
			showSinglePicker() {
				//关闭之前filter。
				// document.getElementById("popupRef").style.display="none";
				this.$refs.picker.show()
			},
			pickerConfirm(e){
				var value = e.value;	
				console.log(value)
				var name = ''
				this.filter.deptId = ''
				if(value[1] == '-') {
					name = e.item[0].text
					this.deptResult.value = value[0]
				} else {
					this.deptResult.value = value[2]?value[2]:value[1];
					if(value[2]){
						// name = name.substring(0,name.length-2);
						name = e.item[0].text+'/'+e.item[1].text+'/'+e.item[2].text
					} else {
						name = e.item[0].text+'/'+e.item[1].text
					}
				}
				console.log(this.deptResult.value)
				this.deptResult.name = name;
				this.listCards=[];
				this.page=1;
				this.loading_status="more";
				if(this.current_num == 2){
					this.dataList(2);
				}else{
					this.dataList();
				}
			},
			
			formaterData(data){
				var resData = [];
				data.forEach((vals,index)=>{
					if(vals.approveState ||vals.approveState == 0){
						console.log(vals)
						var approveState = ''
						if(vals.approveState==0){
							approveState = "暂存"
						  } else if(vals.approveState==1){
							approveState = "待审批"
						  }else if(vals.approveState==2){
							approveState = "已驳回"
						  }else if(vals.approveState==3){
							approveState = "审批通过"
						  }
						  console.log("cessss")
						var combineJSON = {//审批数据格式化
							id: vals.id,
							title: vals.approveTitle?vals.approveTitle:'销售合同',
							contentList: [
								{
									id:1,
									isDouble:false,
									labelName:'合同编号',
									labelContent:vals.contractCode?vals.contractCode:""
								},	
								{
									id:2,
									isDouble:false,
									labelName:'销售部门',
									labelContent:vals.salesPersonDeptName?vals.salesPersonDeptName:""
									
								},
								{
									id:3,
									isDouble:false,
									labelName:'合同日期',
									labelContent:vals.contractDate?vals.contractDate:""
								},	
								{
									id:4,
									isDouble:false,
									labelName:'备注',
									labelContent:vals.remarks||''
								}
							],
							extra: approveState,
							approveState:vals.approveState,
							taskId:vals.taskId,
							instanceId:vals.instanceId,
							salesContractId:vals.salesContractId,
							tagType:this.setTagType(vals.approveState),
							statusId:vals.statusId
						}
						
					}else{
						var combineJSON = {//列表数据格式化
							id: vals.id,
							title: vals.approveTitle?vals.approveTitle:'销售合同',
							contentList: [
								{
									id:1,
									isDouble:true,
									labelName:'单据编号',
									labelContent:vals.contractCode?vals.contractCode:""
								},	
								{
									id:2,
									isDouble:true,
									labelName:'申请时间',
									labelContent:vals.contractDate
								},
								{
									id:3,
									isDouble:false,
									labelName:'申请部门',
									labelContent:vals.deptName.substr(0,10)
								},	
								{
									id:4,
									isDouble:false,
									labelName:'备注',
									labelContent:vals.remarks||''
								}
							],
							extra: vals.statusname,
							tagType:this.setTagType(vals.statusid),
							statusId:vals.statusid
						}
					}
					resData.push(combineJSON);
				});
				return resData;
			},
			setTagType(status){
				if(status == '0'){   //暂存
					return '106'
				}else if(status == '1'){  //待审批
					return '107'
				}else if(status == '2'){ //已驳回
					return '108'
				}else{  //审批通过
					return '109'
				}
			},
			filterDate() {
				//关闭之前filter。
				// document.getElementById("popupRef").style.display="none";
				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.page=1;
					this.loading_status="more";
					if(this.current_num == 2){
						this.dataList(2);
					}else{
						this.dataList();
					}
				}
			}
		},
		onNavigationBarButtonTap(obj) {
			//重置下
			uni.removeStorageSync('purchaseInfo');
			console.log("-------------")
			uni.navigateTo({
			    url: 'addPurchaseApply'
			});
		},
		onBackPress(options) { //取消默认的返回事件.
			uni.switchTab({
				url: "../main/main"
			});
			return true;
		}
	}
</script>

<style scoped>
	>>>.select-tab-fixed-top{
		left: 0;
		width: 50%;
	}
	>>>.picker-item .lb-picker-column .lb-picker-column-label {
	    -webkit-transition: all 0.3s;
	    transition: all 0.3s;
	    line-height: 3.8 !important;
	}
</style>
