<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="viseId" />
				</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">
					<input class="uni-input" focus placeholder="请填写签证名称" v-model="viseName" />
				</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 ">
					<input class="uni-input-small"   v-model="requisitionName" />
					<a href='javascript:;' @click='getRequisition' class="uni-icon"><i class="fa fa-search" aria-hidden="true"></i></a>
				</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 ">
					<input class="uni-input-small" disabled=true v-model="contractName" />
					<a href='javascript:;' @click='getRelationContract' class="uni-icon"><i class="fa fa-search" aria-hidden="true"></i></a>
				</view>
			</view>
			<view class="uni-form-item uni-column"  v-show="contractName">
				<view class="title"><text class="uni-form-item__title">税率</text></view>
				<view class="uni-input-wrapper">
					 {{contract.taxRate+'%'}}
				</view>
			</view>
			<view class="uni-form-item uni-column"  v-show="contractName">
				<view class="title"><text class="uni-form-item__title">是否可抵扣</text></view>
				<view class="uni-input-wrapper"   >
					 {{contract.isDeduct==0?'否':'是'}}
				</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"     @change="bindDateChange" v-model="viseDate"     style="width: 100%;">
					 	<view class="uni-input">{{viseDate}}</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-input-wrapper" style="justify-content: left;">
					<picker mode="date"     @change="bindDealDateChange" v-model="endDate"  style="width: 100%;">
						<view class="uni-input">{{endDate}}</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-input-wrapper" style="justify-content: left;">
					<picker mode="selector" :value="index" :range="array" range-key="name" @change="bindPickerChange" v-model="viseType"  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-input-wrapper">
            		<input class="uni-input" focus value="0" v-model="estimateCash" type="digit" />
            	</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">
					<input class="uni-input" focus value="0" v-model="reportCash" type="digit"/>
				</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="reason" auto-height="true"   />
					</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"  />
			    </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="2000"></g-upfile>
				</view>
			</view>
			
			<uni-section title="费用明细"  type="line"></uni-section>
			<uni-list>
				<uni-list-item v-if="costList"  v-for="(item, index) in costList"  :key="index">
					<view slot="body" class="slot-box">
						<view class="row">
							<view class="column-left">费用项：</view>
							<view class="column-right">{{item.costCodeName}}</view>
						</view>
						<view class="row">
							<view class="column-left">含税金额</view>
							<view class="column-right">
								<input class="uni-input-small" type="digit"  v-model="item.cash" style="width: 240px;text-align: left;" @blur='countTaxtCash(item,index)' />							 
							</view>
						</view>
						<view class="row">
							<view class="column-left">税额</view>
							<view class="column-right" >
								<input class="uni-input-small"  type="digit"   disabled="true"  v-model="item.rateCash" style="width: 240px;text-align: left;"  />	
							</view>
						</view>
						<view class="row">
							<view class="column-left">金额</view>
							<view class="column-right">
								<input class="uni-input-small"  type="digit"  disabled="true"  v-model="item.noRateCash" style="width: 240px;text-align: left;" />	
							</view>
						</view>
						<view class="row">
							<view class="column-left">备注：</view>
							<view class="column-right"> 
							    <textarea  focus  v-model="item.remark"  auto-height="true" style="width: 240px;text-align: left;" />
							</view>
						</view>
						<view class="row">
							<view class="column-left">操作：</view>
							<view class="column-right"> 
							   <i class="fa fa-window-close" aria-hidden="true"   @click="delRow(index)" style="font-size:20px;cursor: pointer;color: #999;margin-left:15px;" title="删除"></i>
							</view>
						</view>
					</view>
				</uni-list-item>
			</uni-list>
			 <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>
		 
			<topicon class="topicon" :iconWidth="50" :iconHeight="50" :startPostion="3" iconPath="../../../static/zhiding.png"
			 :marginBottom="20" :marginTop="60" :marginLeft="5" :marginRight="5" @tapIcon="tapIcon"
			></topicon>
		 
	</view>
</template>

<script>
	
	import {GetQianzhengDropDown} from "@/common/api/requisitionApi.js";
	import {GetContract} from "@/common/api/commonApi.js";
	import {GetContractCostDTOs,InsertVise} from "@/common/api/viseApi.js";
	import {Decimal} from 'decimal.js';     //decimal计算
	import topicon from '@/components/gwh-backTopIcon/gwh-backTopIcon.vue'	
	
	export default {
		components:{
			topicon
		},
		data() {			
			return {
				viseId:'',
				viseName:'',
				requisitionCode:'',     //申请单编号
				requisitionName:'',    //申请单名称
				contractCode:'',
				contractName:'',
				contract:{},          //获取的关联合同信息
				viseDate:this.$util.getDate({
					format: true
				}),
				endDate:this.$util.getDate({
					format: true
				}),
				
				viseType:'',
				 
				
				estimateCash:0.00,
				reportCash:0.00,
				reason:'',
				remark:'',
				costList:[],    //费用明细
			
				  
				imageList: [],
				 
				countIndex: 5,
				count: [1, 2, 3, 4, 5],
				title1: 'picker',
				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(page.path);
			console.info(uni.getStorageSync('storage_state'));
			//console.info(this);
			this.$util.persistLogin(this);
			//console.info(this.$store.state.user);
			
		},
		onUnload() {
			this.imageList = [],
			this.sourceTypeIndex = 2,
			this.sourceType = ['拍照', '相册', '拍照或相册'],
			this.sizeTypeIndex = 2,
			this.sizeType = ['压缩', '原图', '压缩或原图'],
			this.countIndex = 5;
		},
		created: function() {
			this.GetDropDown();
				
			
		},
		updated:function(){
			
		},
		methods: {
			
			/**
			 * 手动提交
			 * @param {Object} form
			 */
			submitForm(e) {				
				console.info('submitForm');
				let _this=this;
				if(this.viseId==='')
				{
					uni.showToast({
						icon:"none",
						title:"请填写签证编号",
						duration:3000
					});
					return;
				}
				if(this.viseName==='')
				{
					uni.showToast({
						icon:"none",
						title:"请填写签证名称",
						duration:3000
					});
					return;
				}
				if(this.viseName.length>50)
				{
					uni.showToast({
						icon:"none",
						title:"签证名称不能多于50字",
						duration:3000
					});
					return;
				}
				if(this.requisitionCode===""){
					uni.showToast({
						icon:"none",
						title:"请选择申请单",
						duration:3000
					});
					return;
				}
				if(this.contractCode===""){
					uni.showToast({
						icon:"none",
						title:"请选择关联合同号",
						duration:3000
					});
					return;
				}
				if(this.viseDate===""){
					uni.showToast({
						icon:"none",
						title:"请选择签证日期",
						duration:3000
					});
					return;
				}
				if(this.endDate===""){
					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.reason!=""){
					if(this.reason.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.costList.length<=0){
					uni.showToast({
						icon:"none",
						title:"费用明细不能为空",
						duration:3000
					});
					return;
				}
				let moneyType=this.contract.moneyType;
				let exchangeRate=this.contract.exchangeRate;
				let taxRate=this.contract.taxRate;
				let list1=this.costList;   //费用明细
				let totalCash=0.00;        //总含税金额
				let rateTotalCash=0.00;   //税收总额
				let noRateTotalCash=0.00;   //不含税总金额
				
				let viseCosts=[];
				list1.forEach(function(item,index,arr){
					totalCash+= item.cash-0.00;
					rateTotalCash+= item.rateCash;
					noRateTotalCash+= item.noRateCash;
					viseCosts.push({costCode:item.costCode,costBudgetSetCode:item.costBudgetSetCode,cash:item.cash-0.00,checkCash:0.00,moneyType:moneyType,exchangeRate:exchangeRate,money:item.cash-0.00,checkMoney:0.00,remark:item.remark,rate:taxRate,rateCash:item.rateCash,rateMoney:item.rateCash,noRateCash:item.noRateCash,noRateMoney:item.noRateCash});
				});
				//vise  viseCosts
				var vise={viseId:this.viseId,viseName:this.viseName,viseType:this.viseType,person:this.$util.getState(this,'userCode'),unitCode:this.$store.state.departmentCode,viseDate:this.viseDate,endDate:this.endDate,remark:this.remark,reason:this.reason,projectCode:this.$store.state.projectCode,contractCode:this.contractCode,totalCash:totalCash,moneyType:moneyType,exchangeRate:exchangeRate,estimateCash:this.estimateCash-0,reportCash:this.reportCash-0,requisitionCode:this.requisitionCode,rate:taxRate,rateTotalCash:rateTotalCash,noRateTotalCash:noRateTotalCash };
			 
				 
				
				var data={vise:vise,viseCosts:viseCosts};
				console.info('data:',data); 
				//return;
				InsertVise(data).then((res)=>{
					console.info("提交应答");
					console.info(res);
					if(res){
						//上传图片
						_this.uploadFileToServe(res) ;
						
						uni.navigateTo({
							url:'/pages/template/GetVises/GetVises'
						})
					}
					else{
						uni.showToast({
							title:'添加失败，重新操作',
							icon:'none',
							duration:3000
						})
					}
					
				});
			},
			/*
			获取申请单
			*/
			getRequisition() {
				let _this = this;				
				_this.saveTemp(_this);
				//创建名字为fire的监听器，监听子页面传值事件
				uni.$on('requisition', function(data) {
					console.info("监听getRequisition子页面的传值", data);
					//console.info('监听',_this);
			         _this.getTemp(_this);
					 _this.requisitionCode=data[0].requisitionCode;
					 _this.requisitionName=data[0].requisitionName;
					/* _this.$nextTick(function(){
					 	//更新dom
					 }); */
				 
					//接收一次监听，一旦监听到回传值，则清除监听事件，若不清除，会占用资源
					uni.$off("requisition");
				});
				uni.navigateTo({
					url: '/pages/template/SelectRelationRequision/SelectRelationRequision'
				});
			},
			/*
			获取关联合同
			*/
			getRelationContract() {
				let _this = this;				
				_this.saveTemp(_this);
				//创建名字为fire的监听器，监听子页面传值事件
				uni.$on('contract', function(data) {
					console.info("监听getRelationContract子页面的传值", data);
					//console.info('监听',_this);
			         _this.getTemp(_this);
					 _this.contractCode=data[0].contractCode;
					 _this.contractName=data[0].contractName;
					 _this.contract=data[0].contract;
					 _this.getCostList();
					/* _this.$nextTick(function(){
					 	//更新dom
					 }); */
				 
					//接收一次监听，一旦监听到回传值，则清除监听事件，若不清除，会占用资源
					uni.$off("contract");
				});
				let requisitionCode=_this.requisitionCode;
				if(requisitionCode==""){
					uni.showToast({
						title:'请先选择申请单',
						icon:'none',
						duration:3000
					});
					return;
				}
				uni.navigateTo({
					url: '/pages/template/SelectRelationContract/SelectRelationContract?requisitionCode='+requisitionCode
				});
			},
			
			/*
			获取费用明细
			*/
			getCostList() {
				let _this = this;				
				_this.saveTemp(_this);
				if(_this.contractCode){
					GetContractCostDTOs(_this.contractCode).then(res=>{
						console.info('GetContractCostDTOs',res);
						if(res.length>0){
							res.forEach(function(item,index,arr){
								item.cash=0.00;
								item.rateCash=0.00;
								item.noRateCash=0.00;
								_this.$set(_this.costList,index,item); 
							});
						}
					});
				}
				 
				 
			},
			delRow: function(index) {
				console.info("删除");
				console.info(this.costList[index]);
				this.costList.splice(index, 1);
			},
			/* 计算该行的税额 */
			countTaxtCash:function(item,index){
				let _this=this;
				 
				//console.info("countTaxtCash",item);
				//console.info("countTaxtCash",index);
				//let value=event.detail.value;
				let taxRate=_this.contract.taxRate;
				item.rateCash=item.cash*taxRate;
				item.noRateCash=item.cash-item.rateCash;
				
			},
			bindPickerChange: function(e) {
				//console.log('picker发送选择改变，携带值为：' + e.detail.value);
				//console.info(e.detail);
				this.index = e.detail.value;
				this.viseType=this.array[this.index];
				console.info(this.viseType);
			},
			bindDateChange: function(e) {
				let date = e.detail.value;
				this.viseDate=date;
				console.info('bindDateChange',this.viseDate);
			},
			bindDealDateChange: function(e) {
				let date = e.detail.value;
				this.endDate=date;
				console.info('bindDealDateChange',this.endDate);
			},
			
			GetDropDown:function(){
				let that=this;
				GetQianzhengDropDown().then((res)=>{
					console.info('GetQianzhengDropDown:',res);
					res.forEach(function(item,index,array){
						that.$set(that.array,index,item);
					});
					//赋默认值
					that.viseType=that.array[0];	
					console.info(that.viseType);
				});
			},
			
			/*
			上传后返回的值：
			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:'Vise'
						},
						headers: {
							'Content-Type': 'multipart/form-data; boundary = ' + new Date().getTime()
							//这里要把content-type设置为multipard/form-data，同时还要设置boundary
						},
						success: (uploadFileRes) => {
							console.log("图片上传:",uploadFileRes.data);
						}
					});
				}
			},
		
		   saveTemp(_this){  //临时存
		   	uni.setStorage({
		   		key:'viseId',
		   		data:_this.viseId
		   	});
		   	uni.setStorage({
		   		key:'viseName',
		   		data:_this.viseName
		   	});
		   	uni.setStorage({
		   		key:'requisitionCode',
		   		data:_this.requisitionCode
		   	});
		   	uni.setStorage({
		   		key:'requisitionName',
		   		data:_this.requisitionName
		   	});
		   	uni.setStorage({
		   		key:'contractName',
		   		data:_this.contractName
		   	});
		   	uni.setStorage({
		   		key:'contractCode',
		   		data:_this.contractCode
		   	});
		   	uni.setStorage({
		   		key:'viseDate',
		   		data:_this.viseDate
		   	});
		   	uni.setStorage({
		   		key:'endDate',
		   		data:_this.endDate
		   	});
		   	uni.setStorage({
		   		key:'viseType',
		   		data:_this.viseType
		   	});
		   	uni.setStorage({
		   		key:'estimateCash',
		   		data:_this.estimateCash
		   	});
		   	uni.setStorage({
		   		key:'reportCash',
		   		data:_this.reportCash
		   	});
		   	uni.setStorage({
		   		key:'reason',
		   		data:_this.reason
		   	});
		   	uni.setStorage({
		   		key:'remark',
		   		data:_this.remark
		   	});
		   
		   },
		   getTemp(_this){   //获取缓存，重新给表单赋值
		   	_this.viseId=uni.getStorageSync('viseId');
		   	_this.viseName=uni.getStorageSync('viseName');
		   	_this.requisitionCode=uni.getStorageSync('requisitionCode');
		   	_this.requisitionName=uni.getStorageSync('requisitionName');
		   	_this.contractName=uni.getStorageSync('contractName');
		   	_this.contractCode=uni.getStorageSync('contractCode');
			
		   	_this.viseDate=uni.getStorageSync('viseDate');
		   	_this.endDate=uni.getStorageSync('endDate');
		   	_this.viseType=uni.getStorageSync('viseType');
		   	_this.estimateCash=uni.getStorageSync('estimateCash');
		   	
		   	_this.reportCash=uni.getStorageSync('reportCash');
		   	_this.reason=uni.getStorageSync('reason');
		   	_this.remark=uni.getStorageSync('remark');
		   
		   },
		   tapIcon(e){
			   console.log('you tap icon');
			    document.documentElement.scrollTop = document.body.scrollTop = 0;
		   }
		}
	}
</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;
		margin-left:15px;
	    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;
	}
	 
	 .topicon >>> .icon{
	        border: #4CD964 2upx solid;
	    }
</style>
