<template>
	<view>
		<uni-forms ref="form" labelPosition="left" labelAlign="left" @submit="submitForm">
			<view class="uni-form-item uni-column">
				<view class="title"><text class="uni-form-item__title">申请单名称</text></view>
				<view class="uni-input-wrapper">
					<input class="uni-input" focus placeholder="请填写申请单名称" v-model="requisitionName" name="requisitionName" />
				</view>
			</view>
			<view class="uni-form-item uni-column">
				<view class="title"><text class="uni-form-item__title">申请日期</text></view>
				<view class="uni-input-wrapper" style="justify-content: left;">
					<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange" v-model="requisitionDate"
					 name="requisitionDate" style="width: 100%;">
						<view class="uni-input">{{date}}</view>
					</picker>
				</view>
			</view>
			<view class="uni-form-item uni-column">
				<view class="title"><text class="uni-form-item__title">{{qianzhengName}}</text></view>
				<view class="uni-input-wrapper" style="justify-content: left;">
					<picker mode="selector" :value="index" :range="array" range-key="name" @change="bindPickerChange" v-model="changeType"
					 name="changeType" style="width: 100%;">
						<view class="uni-input">{{array.length>0?array[index]:''}}</view>
					</picker>
				</view>
			</view>


			<view class="uni-form-item uni-column">
				<view class="title"><text class="uni-form-item__title">原因</text></view>
				<view class="uni-textarea">
					<textarea focus placeholder="请输入原因" v-model="requisitionReason" auto-height="true" name="requisitionReason" />
					</view>
			</view>
			<view class="uni-form-item uni-column">
			    <view class="title"><text class="uni-form-item__title">备注</text></view>
			    <view class="uni-textarea">
			        <textarea  focus placeholder="请写备注"  v-model="remark"  auto-height="true" name="remark"/>
			    </view>
			</view>
			
			<view class="uni-form-item uni-column">
			    <view class="title"  style="background-color: #efefef;"><text class="uni-form-item__title">上传文件</text></view>
				<view class="content">
			    <g-upfile ref='gUpfile' :mode="imgList" @chooseFile='chooseFile' @imgDelete='imgDelete' :control='control'
			     :columnNum="columnNum" :maxCount="maxCount" @limitFileSizeList='limitFileSizeList' @limitFileTypeList='limitFileTypeList'  :maxFileSize="20000"></g-upfile>
				</view>
			</view>
			
			<uni-section title="关联合同" type="line">
			 	    <button type="default" @click="openWindow" size="mini">添加关联合同</button>
			</uni-section>
			<view class="uni-form-item uni-column" >
				<uni-list style="background-color: #EFEFEF;">
					<uni-list-item>
						<view slot="header" class="header-slot-box">合同编号</view>
						<view slot="body" class="body-slot-box">合同名称</view>
						<view slot="footer" class="footer-slot-box">暂估金额</view>
					</uni-list-item>
				</uni-list>
			
				<uni-list> 
					<uni-list-item v-for="(item,index) in contractList" :key="index">
							<!-- 自定义 header -->
							<view slot="header" class="header-slot-box">							
								 {{item.contractID}}
							</view>
							<!-- 自定义 body -->
							<view slot="body" class="body-slot-box">
								{{item.contractName}}
							</view>
							<!-- 自定义 footer-->
							<view slot="footer" class="footer-slot-box" style="flex-direction: row;justify-content: center;">		
								<input class="uni-input" type="digit" focus v-model="item.estimateCash"   style="width:50px;"/>
								<button class="mini-btn" type="default" size="mini" @click="delRow(index)" >删除</button>
							</view>
					</uni-list-item>				 
				</uni-list>
			</view>
			
			<view  style="margin-bottom: 120px;">
				 
			</view>
			<view class="uni-btn-v uni-column">
				<button type="primary" form-type="submit" style="border-radius: 15px;" >提交</button>
			</view>
			
		</uni-forms>
	</view>
</template>

<script>
	import permision from "@/common/permission.js";
	import {GetQianzhengDropDown,InsertRequisition,GetzzSupplierEx} from "@/common/api/requisitionApi.js";
	import {GetUserDepartment} from "@/common/api/commonApi.js";
	import {Decimal} from 'decimal.js';     //decimal计算
		 
	
	export default {
		data() {
			return {
				needFormCach:false,    //是否需要表单缓存
				requisitionName:'',
				requisitionDate:this.$util.getDate({
					format: true
				}),
				requisitionType:0,
				qianzhengName:'签证类型',
				changeType:'',
				userCode:this.$store.state.user.userCode,	        //用户编号
				personName:this.$store.state.user.userName,         //申办人
				unitCode:this.$store.state.departmentCode,        //申办部门
				unitCodeName:this.$store.state.departmentName,   //申办部门名
				requisitionReason:'',
				remark:'',
				
				contractList:[],
				
				imageList: [],
				
				countIndex: 5,
				count: [1, 2, 3, 4, 5],
				
				array: [],
				index: 0,
				date: this.$util.getDate({
					format: true
				}),
				startDate:this.$util.getDate('start'),
				endDate:this.$util.getDate('end'),
				
				control: true,
				columnNum: 3,
				imgList: [],
				urlList:[],
				maxCount:5
			
			}
		},
		onLoad(){
			console.info('onLoad');
			console.info(uni.getStorageSync('storage_state'));
			//console.info(this);
			this.$util.persistLogin(this);
			//console.info(this.$store.state.user);
			//const page = getCurrentPages();
			//console.info(page);
			if(this.$util.getQuery("type")=="1"){
				uni.setNavigationBarTitle({
					title:'变更申请单添加'
				});
				this.qianzhengName='设计变更类型';
			}
			else{
				uni.setNavigationBarTitle({
					title:'签证申请单添加'
				});
				this.qianzhengName='签证类型';
			}
		},
		onUnload() {
			this.imageList = [],
			
			this.countIndex = 5;
		},
		created: function() {
			console.info('created');
			this.GetDropDown();
			this.GetzzSupplierEx();
			//表示从子页面获取了数值，返回父页面有可能会造成页面刷新导致表单数据丢失，需要从缓存中读取表单数据
			if(this.needFormCach){     
				this.getTemp(this);
			}
		},
		updated:function(){
			
		},
		
		methods: {
			input(form, name, value) {
				this.$refs[form].setValue(name, value)
			},		

			/**
			 * 手动提交
			 * @param {Object} form
			 */
			submitForm(e) {				
				console.info('submitForm');
				let _this=this;
				if(this.requisitionName==='')
				{
					uni.showToast({
						icon:"none",
						title:"请填写申请单名称",
						duration:3000
					});
					return;
				}
				if(this.requisitionName.length>50)
				{
					uni.showToast({
						icon:"none",
						title:"申请单名称不能多于50字",
						duration:3000
					});
					return;
				}
				if(this.requisitionDate===""){
					uni.showToast({
						icon:"none",
						title:"申请日期不能为空",
						duration:3000
					});
					return;
				}
				if(this.changeType===""){
					uni.showToast({
						icon:"none",
						title:"签证类型不能为空",
						duration:3000
					});
					return;
				}
				if(this.requisitionReason===""){
					uni.showToast({
						icon:"none",
						title:"原因不能为空",
						duration:3000
					});
					return;
				}
				if(this.requisitionReason.length>500){
					uni.showToast({
						icon:"none",
						title:"原因不能超过500字",
						duration:3000
					});
					return;
				}
				if(this.remark!==""){
					if(this.remark.length>500){
						uni.showToast({
							icon:"none",
							title:"签备注不能超过500字",
							duration:3000
						});
						return;
					}	
				}
				if(this.$util.isEmpty(this.userCode)||this.$util.isEmpty(this.unitCode)){
					uni.showToast({
						icon:"none",
						title:"登录人信息丢失，请重新登录再操作",
						duration:4000
					});
					return;
				}
				let requisitionType=this.$util.getQuery("type")-0;
				var requisitionDTO={requisitionName:this.requisitionName,requisitionDate:this.requisitionDate,changeType:this.changeType,requisitionReason:this.requisitionReason,remark:this.remark,person:this.userCode,unitCode:this.unitCode,projectCode:this.$util.getState(this,'projectCode'),requisitionType:requisitionType};
			 
				var list1=this.contractList;
				
				let list=[];
				list1.forEach(function(item,index,array){
					list.push({requisitionCode:'',contractCode:item.contractCode,estimateCash:new Decimal(item.estimateCash).toFixed(2)-0 });
					//list.push({requisitionCode:'',contractCode:item.contractCode,estimateCash: 220});
				});
				console.info("【list】");
				console.info(list);
				if(list.length<=0){
					uni.showToast({
						title:"请添加关联合同",
						icon:"none",
						duration:3000
					});
					return;
				}
				//return;
				var data={Requisition:requisitionDTO,List:list};
				//var strList=JSON.stringify(list);
				//var strData=JSON.stringify(data);
				InsertRequisition(data).then((res)=>{
					console.info("提交应答");
					console.info(res);
					if(res){
						//上传图片
						_this.uploadFileToServe(res) ;
						
						uni.navigateTo({
							url:'/pages/template/requisitionlist/requisitionlist?type='+requisitionType
						})
					}
					else{
						uni.showToast({
							title:'添加失败，重新操作',
							icon:'none',
							duration:3000
						})
					}
					
				});
			},
			//获取供应商明细
			GetzzSupplierEx:function(){
				let that=this;
				let id=this.$util.getQuery("zzSupplierExid");
				if(id!=null&&id!=""){
					GetzzSupplierEx(id).then((res)=>{
						if(typeof res!='string')
						{
							that.requisitionName=res.entity.title;
							that.requisitionReason=res.entity.reason;
							 
						}
					});
				}
				
			},
			bindPickerChange: function(e) {
				//console.log('picker发送选择改变，携带值为：' + e.detail.value);
				//console.info(e.detail);
				this.index = e.detail.value;
				this.changeType=this.array[this.index];
				console.info(this.changeType);
			},
			bindDateChange: function(e) {
				this.date = e.detail.value;
				this.requisitionDate=this.date;
				console.info(this.date);
			},
			
			countChange: function(e) {
				this.countIndex = e.detail.value;
			},
			
			GetDropDown:function(){
				let that=this;
				let type=this.$util.getQuery("type")-0;
				GetQianzhengDropDown(type).then((res)=>{
					console.info(res);
					res.forEach(function(item,index,array){
						that.$set(that.array,index,item);
					});
					that.changeType=that.array[0];					
				});
			},
			GetDepartment:function(){
				let that=this;
				GetUserDepartment('100340').then((res)=>{
					console.info(res);					
					that.unitCodeName=res;
					});
			},
			openWindow:function(){
				let _this=this;
				console.info('监听事件外部this');
				console.info(this);
				this.saveTemp(_this);
				
				//创建名字为fire的监听器，监听子页面传值事件
				uni.$once('fire', function(data) {
					console.info("监听fire子页面的传值",data);
					//修改数据
					_this.contractList=[];
					data.forEach(function(item,index,array){
						//console.info("foreach");				
						_this.$set(_this.contractList,index,item);
					});	
					uni.setStorage({
						key:'contractList',
						data:_this.contractList
					});
					//dom还没更新						
					 _this.getTemp(_this);
					_this.needFormCach=true;
					console.info("监听子页面的传值结束");	
				});	
				//打开子页面
				uni.navigateTo({
					url:"/pages/template/GetRelationContract/GetRelationContract"
				})
			},
			/* 获取this.$data缓存值 */
			getTemp(_this){
				if(uni.getStorageSync('requisitionName')){
					_this.requisitionName=uni.getStorageSync('requisitionName');
					_this.requisitionDate=uni.getStorageSync('requisitionDate');
					_this.requisitionReason=uni.getStorageSync('requisitionReason');
					_this.changeType=uni.getStorageSync('changeType');
					_this.remark=uni.getStorageSync('remark');
					_this.imageList=uni.getStorageSync('imageList');
					_this.contractList=uni.getStorageSync('contractList');
				}
			},
			/* 给$data重新赋值 */
			saveTemp(_this){
				uni.setStorage({
					key:'requisitionName',
					data:_this.requisitionName
				});
				uni.setStorage({
					key:'requisitionDate',
					data:_this.requisitionDate
				});
				uni.setStorage({
					key:'changeType',
					data:_this.changeType
				});
				uni.setStorage({
					key:'requisitionReason',
					data:_this.requisitionReason
				});
				uni.setStorage({
					key:'remark',
					data:_this.remark
				});
				uni.setStorage({
					key:'imageList',
					data:_this.imageList
				});
			},
			delRow:function(index){
				console.info(index);
				console.info(this.contractList[index]);
				this.contractList.splice(index,1);
			},
			/*
			上传后返回的值：
			list：上传后图片数组
			v：返回当前上传图片的临时路径
			*/
			chooseFile(list, v) {
				console.log("上传图片_list：", list)
				console.log("上传图片_v：", v);
				this.urlList=list;
				console.info("urlList",this.urlList);
				
			},
			
			
			/*
			删除图片：
			list：删除返回删除后剩余的图片数组
			eq：返回删除的数组
			*/
			imgDelete(list, eq) {
				console.log("删除图片_list：", list);
				console.log("删除图片_eq：", eq);
				this.urlList=list;
				console.info("urlList",this.urlList);
			},
			/*限制文件大小列表*/
			limitFileSizeList(list){
				console.info('limitFileSizeList:',list);
				if(list){
					if(list.length>0){
						uni.showModal({
							title:'警告',
							content: list.join()+' 文件大小超过2000KB',
							showCancel:false
						});
					}
				}
			},
			/*限制文件类型列表*/
			limitFileTypeList(list,allowFileType){
				console.info('limitFileTypeList:',list);
				console.info('limitFileTypeList:',allowFileType);
				if(list){
					if(list.length>0){
						uni.showModal({
							title:'警告',
							content: list.join()+' 文件类型必须是'+allowFileType.join(),
							showCancel:false
						});
					}
				}
			},
			/*
			执行上传服务：
			urlList：要上传的图片：数组类型
			*/
			uploadFileToServe(masterCode) {
				let _this=this;
				var urlList=_this.urlList;
				if (!urlList || urlList.length <= 0) {
					return;
				};
				//console.info(urlList);
			
			
				//return;
				for (let i = 0; i < urlList.length; i++) {
			
					uni.uploadFile({
						url: '/api/Common/UploadImage', 
						filePath: urlList[i],
						name: 'file',
						formData: {
							createPerson:_this.$store.state.user.userCode,
							masterCode:masterCode,
							attachMentType:'RequisitionAttach'
						},
						headers: {
							'Content-Type': 'multipart/form-data; boundary = ' + new Date().getTime()
							//这里要把content-type设置为multipard/form-data，同时还要设置boundary
						},
						success: (uploadFileRes) => {
							console.log("图片上传:",uploadFileRes.data);
						}
					});
				}
			}
		}
	}
</script>

<style scoped>
	/* 头条小程序组件内不能引入字体 */
	/* #ifdef MP-TOUTIAO */
	@font-face {
		font-family: uniicons;
		font-weight: normal;
		font-style: normal;
		src: url("~@/static/uni.ttf") format("truetype");
	}

	/* #endif */
	 
	page {
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		background-color: #efeff4;
		min-height: 100%;
		height: auto;
	}

	view {
		font-size: 14px;
		line-height: inherit;
	}

	.uni-form-item__title {
	    font-size: 16px;
	    line-height: 24px;
	}
	
	.uni-input-wrapper {
	    /* #ifndef APP-NVUE */
	    display: flex;
	    /* #endif */
	    padding: 8px 13px;
	    flex-direction: row;
	    flex-wrap: nowrap;
	    background-color: #FFFFFF;
	}
	.title{
		background-color: #efefef;
	}
	.uni-input {
	    height: 28px;
	    line-height: 28px;
	    font-size: 15px;
	    padding: 0px;
	    flex: 1;
	    background-color: #FFFFFF;
	}
	
	.uni-icon {
	    font-family: uniicons;
	    font-size: 24px;
	    font-weight: normal;
	    font-style: normal;
	    width: 24px;
	    height: 24px;
	    line-height: 24px;
	    color: #999999;
	}
	
	.uni-eye-active {
	    color: #007AFF;
	}
	.uni-btn-v{
		position: fixed;
		bottom: 0;
		width:100%;
		
	}
	.header-slot-box {
		font-size:15px;
		margin: 5px 5px;
		width:20%;
		justify-content: center;
	}
	.body-slot-box {
		font-size:15px;
		margin: 5px 5px;
		width:40%;
		justify-content: center;
	}
	.footer-slot-box {
		font-size:15px;
		margin: 5px 5px;
		width:40%;
		justify-content: center;
	}
	.uni-textarea textarea{
		font-size:15px;
	}
	.content {
		padding: 40rpx;
		background-color: #fff;
	}
	
	/* 上传控件 */
	.uploadControl {
		border: 1rpx solid #eee;
		border-radius: 10rpx;
		width: 130rpx;
		display: block;
		height: 130rpx;
		text-align: center;
		line-height: 130rpx;
		font-size: 30rpx;
		color: #888;
		background-color: #eeeeee;
	}
</style>
