<template>
	<view class="page">
		<view class="item item_line" @click="onShowDatePicker(1)" style="margin-top: 22upx;">
			<view class="itemname redMi">申请日期</view>
			<view class="itemtext">
				<view>
					<input class="iteminput InputRightMargin" disabled placeholder="请选择支付日期"
						:value='formData.payApply.applicationDate' />
					<img src="../../static/img/dateIcon.png" class="dateIcon" />
				</view>
			</view>
		</view>
		<view class="item item_line">
			<view class="itemname redMi">申请人</view>
			<view class="itemtext">
				<input class="iteminput" placeholder="请输入申请人名称" v-model="formData.payApply.applicantName" />
			</view>
		</view>
		<view class="item item_line">
			<view class="itemname pl15">申请部门</view>
			<view class="itemtext">
				<input class="iteminput" disabled placeholder="请输入申请部门" v-model="formData.payApply.applicantDeptName" />
			</view>
		</view>
		<view class="item item_line" style="margin-top: 22upx;">
					<view class="itemname redMi">付款单位</view>
					<view class="itemtext">
						<input class="iteminput InputRightMargin" disabled placeholder="请选择付款单位"  @click="showSinglePicker" :value="formData.payApply.supplierName"/>
						<uni-icons type="arrowright" class="myarrowright" style="right: 0px;"></uni-icons>
					</view>
		</view>
		<view class="item item_line" @click="onShowDatePicker(2)">
			<view class="itemname redMi">支付日期</view>
			<view class="itemtext">
				<view>
					<input class="iteminput InputRightMargin" disabled placeholder="请选择支付日期"
						:value='formData.payApply.paymentDate' />
					<img src="../../static/img/dateIcon.png" class="dateIcon" />
				</view>
			</view>
		</view>
		<view class="item item_line item_textarea">
			<view class="itemname redMi">付款事由</view>
			<textarea class="textarea" placeholder="请详细描述付款事由" v-model="formData.payApply.paymentReason"></textarea>
		</view>
		<view class="item item_line item_textarea">
			<view class="itemname pl15">备注</view>
			<textarea class="textarea" placeholder="请输入备注信息" v-model="formData.payApply.remark"></textarea>
		</view>
		<view class="photo_container item_line">
			<view class="pzqd">图片</view>
			<view class="photo_out">
				<view class="imgwrap" v-for="(items,index) in imgsrc_list_local" :key="index">
					<view class="myimgBox" @click="reUpload(index)">
						<view class="img">
							<img class="uploadimg" :src="items" />
							<view class="cxsc">重新上传</view>
						</view>
					</view>
					<img src="../../static/img/delete.png" class="deleteimg" @click="deleteImg(index)" />
				</view>
				<view class="imgwrap" @click="chooseImg()">
					<view class="myimgBox">
						<view class="img upload_btn">
							<img src="../../static/img/uploadimg.png" />
							<view class="sctp">上传图片</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view class="fixMargin"></view>
		<view class="goHome" @click='goMain("formInfo")'>
			<img src="../../static/img/gohome.png">
		</view>
		<view class="fixBottom">
			<view class="uni-flex uni-row">
				<button type="primary" plain="true"  style="width: 90%; background: #fff;" @click="toNext()">导入关联单据</button>
			</view>
		</view>
		<mx-datepicker type="date" :value="value_time" :show="showPicker" @confirm="onSelected" @cancel="onSelected"></mx-datepicker>
		<mpvue-picker themeColor="#007AFF" ref="mpvuePicker" mode="selector" :deepLength="deepLength"
		 @onConfirm="pickerConfirm" :pickerValueArray="apply_type"></mpvue-picker>
	</view>
</template>

<script>
	import {
		config
	} from '../../request/js/config.js'
	import mpvuePicker from '@/components/mpvue-picker/mpvuePicker.vue';
	import mxDatepicker from '@/components/mx-datepicker/mx-datepicker.vue'
	import uniIcons from "@/components/uni-icons/uni-icons.vue"
	import chooseUserMulti from '@/components/xinsoft-search-list/chooseUserMulti.vue'
	import {getTimer} from '@/common/tools'
	export default {
		components: {
			mxDatepicker,
			mpvuePicker,
			uniIcons,
			chooseUserMulti
		},
		data() {
			return {
				config: config,
				imgsrc_list: [],
				imgsrc_list_local: [],
				showPicker: false,
				apply_type:[],
				deepLength:1,
				whoShowPicker:0,//判断是申请日期还是支付日期
				formData: {
					payApply: { //头部相关数据
						applicationDate: "", //申请日期
						applicantDeptId: '', //申请部门id
						applicantDeptName: '', //申请部门名称
						applicantId: '', //申请人id
						applicantName: '', //申请人名称
						supplierName: '', //付款单位
						createBy: '', //制单人id
						createName: '', //制单人名称
						createTime: '' //制单时间
					},
					payApplyItemList: [], //关联单据数组
					uploadAttachment: []
				},
				value_time: '',
				id: '',
				targetList: [],
				// search_value_user:[],
			}
		},
		onLoad(option) {
			var _this = this;
			this.id = option.id || '';

			//如果是编辑，就根据接口获取数据，
			if(option.id){
				this.getDetail()
			}else{
				// 两个默认时间(申请时间，支付时间)
				this.formData.payApply.applicationDate=getTimer().split(' ')[0]
				this.formData.payApply.paymentDate=getTimer().split(' ')[0]
				// 默认申请人与申请部门
				let userInfo=uni.getStorageSync('userInfo')
				this.formData.payApply.applicantName = userInfo.name
				this.formData.payApply.createName = userInfo.name
				this.formData.payApply.createBy = userInfo.userId
				this.formData.payApply.applicantId = userInfo.userId //申请人id
				this.formData.payApply.applicantDeptName = userInfo.deptName
				this.formData.payApply.applicantDeptId = userInfo.deptId
				
				//初始化获取付款单位
				this.$http.request({
				  url: '/apis/supplier/listServiceGroup',
				  methods:'POST',
				  params: {
				    pageno: 1,
				    pagesize: 5,
				    status: 179,
				    useStatus: 1
				  },
				}).then(res=>{
					if(res.data.code == 0){
						var useType = res.data.data.datas;
						for (let i = 0; i < useType.length; i++) {
						    var myVal=
						    	{
						    		'label': useType[i].unit_name,
						    		'value': useType[i].id
						    	}
						    this.apply_type.push(myVal);
						}
						
					}
				}).catch(err=>{
					console.log(err);
				});
			}
			// if (option.id) {
			// 	this.$http.request({
			// 		url: '/apis/payApply/detail',
			// 		method: 'GET',
			// 		params: {
			// 			id: option.id,
			// 		},
			// 	}).then(res => {
			// 		if (res.data.code == 0) {
			// 			var payInfos = res.data.payApplyDO;
			// 			res.data.approveList.forEach((vals, index) => {
			// 				var json = {
			// 					user_id: vals.user_id,
			// 					name: vals.name
			// 				}
			// 				this.targetList.push(json);
			// 			});
			// 			for (var i = 0; i < res.data.initFileList.length; i++) {
			// 				this.imgsrc_list.push(res.data.initFileList[i].filePath);
			// 				this.imgsrc_list_local.push(config.imgURL + res.data.initFileList[i].filePath);
			// 			}
			// 			this.payInfo = {
			// 				totalNumber: payInfos.total_number,
			// 				payReason: payInfos.pay_reason,
			// 				payUser: payInfos.pay_user,
			// 				blankAccount: payInfos.blank_account,
			// 				approveState: payInfos.approveState,
			// 				payDate: payInfos.pay_date,
			// 				id: this.id,
			// 				process_instance_id: payInfos.process_instance_id
			// 			}
			// 			uni.setStorage({
			// 				key: 'payInfo',
			// 				data: {
			// 					info: this.formData,
			// 					imgsrc_list: this.imgsrc_list,
			// 					imgsrc_list_local: this.imgsrc_list_local,
			// 					targetList: this.targetList,
			// 				},
			// 				success: function() {}
			// 			});
			// 		}
			// 	}).catch(err => {
			// 		uni.showToast({
			// 			title: '获取信息失败',
			// 			icon: 'none',
			// 			duration: 2000
			// 		});
			// 	});
			// } else {
			// 	//如果不是，是新增，获取session中的数据。
			// 	uni.getStorage({
			// 		key: 'payInfo',
			// 		success: function(res) {
			// 			_this.formData = res.data.info || {},
			// 				_this.targetList = res.data.targetList || [];
			// 			_this.imgsrc_list = res.data.imgsrc_list || [];
			// 			_this.imgsrc_list_local = res.data.imgsrc_list_local || [];
			// 		}
			// 	});
			// }
		},
		// watch:{
		// 	search_value_user(newv){
		// 		var detail = [];
		// 		newv.forEach(item=>{
		// 			let obj = {user_id: item.userId, name: item.NAME};
		// 			detail.push(obj);
		// 		})
		// 		if(newv.length>0){
		// 			var formData =  uni.getStorageSync('formData');
		// 			if(!formData){
		// 				formData = {}
		// 			}
		// 			this.targetList=detail
		// 			formData.targetList = this.targetList
		// 			uni.setStorage({
		// 			    key: 'formData',
		// 			    data: formData,
		// 			    success: function () {
		// 			    }
		// 			});
		// 			}
		// 		}
		// 	},
		methods: {
			// 弹出选择付款单位
			showSinglePicker() {
				this.pickerValueDefault = [0]
				this.$refs.mpvuePicker.show()
			},
			// 弹框付款单位选择
			pickerConfirm(e){
				this.formData.payApply.supplierName = e.label;
				this.formData.payApply.supplierId = e.value[0];  //我也不知道为什么这边是数组，可能改picker框架支持多选。
			},
			getDetail() {
				this.$http.request({
					url: '/apis/payApply/detail/'+this.id,
					method: 'GET'
				}).then(res => {
					if (res.data.code == 0) {
						this.formData=res.data.data
						res.data.data.uploadAttachment.forEach(item=>{
							this.imgsrc_list_local.push(item.filePath)
						})
						console.log(this.imgsrc_list_local)
						// var payInfos = res.data.payApplyDO;
						// res.data.approveList.forEach((vals, index) => {
						// 	var json = {
						// 		user_id: vals.user_id,
						// 		name: vals.name
						// 	}
						// 	this.targetList.push(json);
						// });
						// for (var i = 0; i < res.data.initFileList.length; i++) {
						// 	this.imgsrc_list.push(res.data.initFileList[i].filePath);
						// 	this.imgsrc_list_local.push(config.imgURL + res.data.initFileList[i].filePath);
						// }
						// this.formData = {
						// 	totalNumber: payInfos.total_number,
						// 	payReason: payInfos.pay_reason,
						// 	payUser: payInfos.pay_user,
						// 	blankAccount: payInfos.blank_account,
						// 	approveState: payInfos.approveState,
						// 	payDate: payInfos.pay_date,
						// 	id: this.id,
						// 	process_instance_id: payInfos.process_instance_id
						// }
						// uni.setStorage({
						// 	key: 'payInfo',
						// 	data: {
						// 		info: this.formData,
						// 		imgsrc_list: this.imgsrc_list,
						// 		imgsrc_list_local: this.imgsrc_list_local,
						// 		targetList: this.targetList,
						// 	},
						// 	success: function() {}
						// });
					}
				}).catch(err => {
					uni.showToast({
						title: '获取信息失败',
						icon: 'none',
						duration: 2000
					});
				});
			},

			onShowDatePicker(n) { //显示
				this.showPicker = true;
				this.whoShowPicker=n
				if(n==1){
					this.value_time=this.formData.payApply.applicationDate
				}else if(n==2){
					this.value_time=this.formData.payApply.paymentDate
				}
			},
			onSelected(e) { //选择
				this.showPicker = false;
				var _this = this;
				if (e) {
					if(this.whoShowPicker==1){
						this.formData.payApply.applicationDate=e.value
					}else if(this.whoShowPicker==2){
						this.formData.payApply.paymentDate=e.value
					}
				}
			},
			onShowDatePickerOne(n) { //显示
				this.showPickerOne = true;
			},
			onSelectedOne(e) { //选择
				this.showPickerOne = false;
				var _this = this;
				if (e) {
					this.value_time_one = e.value;
					this.formData.payApply.paymentDate=e.value
				}
			},
			// dataChange(){
			// 	//保存当前修改信息
			// 	var payInfo =  uni.getStorageSync('payInfo');
			// 	if(!payInfo){
			// 		payInfo = {}
			// 	}
			// 	payInfo.info = this.payInfo;
			// 	uni.setStorage({
			// 	    key: 'payInfo',
			// 	    data: payInfo,
			// 	    success: function () {

			// 	    }
			// 	});
			// },
			//上传
			chooseImg() {
				this.uploadImg();
			},
			//重新上传
			reUpload(index) {
				this.uploadImg(index);
			},
			uploadImg(indexnum) {
				var _this = this;
				//#ifdef APP-PLUS
				var count_ = 9;
				//#endif
				//#ifndef APP-PLUS
				var count_ = 1;
				//#endif
				if (indexnum != undefined) {
					count_ = 1;
				}
				uni.chooseImage({
					count: count_,
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						//#ifdef APP-PLUS
						let imgs = chooseImageRes.tempFilePaths.map((value, index) => {
							return {
								name: "file" + (index +
									1
									), //注意这一行，uni的hello的示例中，这里为key名+index，这样是无法和使用一个固定key名接多个文件的php接口对接上的改为数组下标形式的字符串就解决这个问题了。其效果等同于在html页面上多个同name文件域同时提交表单。  
								uri: value
							}
						});
						uni.uploadFile({
							url: config.baseURL + '/apis/file/uploadMulti', //接口地址
							files: imgs,
							fileType: "image",
							name: 'files',
							success: (uploadFileRes) => {
								var arr = [];
								for (var i = 0; i < JSON.parse(uploadFileRes.data).result
									.length; i++) {
									arr.push(JSON.parse(uploadFileRes.data).result[i].filePath);
								}
								if (indexnum != undefined) { //是重新上传
									_this.imgsrc_list[indexnum] = arr[0]
									_this.imgsrc_list_local[indexnum] = chooseImageRes
										.tempFilePaths[0]
								} else {
									_this.imgsrc_list = _this.imgsrc_list.concat(arr);
									_this.imgsrc_list_local = _this.imgsrc_list_local.concat(
										chooseImageRes.tempFilePaths);

								}
								_this.$forceUpdate();
								var payInfo = uni.getStorageSync('payInfo');
								if (!payInfo) {
									payInfo = {}
								}
								payInfo.imgsrc_list = _this.imgsrc_list;;
								payInfo.imgsrc_list_local = _this.imgsrc_list_local;
								uni.setStorage({
									key: 'payInfo',
									data: payInfo,
									success: function() {

									}
								});
							},
							fail: function() {
								uni.showToast({
									title: '上传图片失败',
									duration: 2000,
									icon: "none"
								});
							}
						});
						//#endif
						//#ifndef APP-PLUS
						uni.uploadFile({
							url: config.baseURL + '/apis/file/upload', //接口地址
							filePath: tempFilePaths[0],
							fileType: "image",
							name: 'file',
							success: (uploadFileRes) => {
								var arr = [];
								if (indexnum != undefined) { //是重新上传
									_this.imgsrc_list[indexnum] = JSON.parse(uploadFileRes.data)
										.filePath;
									_this.imgsrc_list_local[indexnum] = chooseImageRes
										.tempFilePaths[0];
								} else {
									_this.imgsrc_list.push(JSON.parse(uploadFileRes.data).filePath)
									_this.imgsrc_list_local.push(chooseImageRes.tempFilePaths)
								}
								_this.$forceUpdate();
								var payInfo = uni.getStorageSync('payInfo');
								if (!payInfo) {
									payInfo = {}
								}
								payInfo.imgsrc_list = _this.imgsrc_list;
								var arr={
									filePath:JSON.parse(uploadFileRes.data).filePath,
									fileName:JSON.parse(uploadFileRes.data).fileName
								}
								_this.formData.uploadAttachment.push(arr)
								payInfo.imgsrc_list_local = _this.imgsrc_list_local;
								console.log(_this.imgsrc_list_local)
								uni.setStorage({
									key: 'payInfo',
									data: payInfo,
									success: function() {

									}
								});
							},
							fail: function() {
								uni.showToast({
									title: '上传图片失败',
									duration: 2000,
									icon: "none"
								});
							}

						});
						//#endif
					}
				});
			},
			//删除图片
			deleteImg(index) {
				this.imgsrc_list.splice(index, 1);
				this.imgsrc_list_local.splice(index, 1);
				this.$forceUpdate();
				this.formData.uploadAttachment.splice(index,1)
			},
			// 跳转导入关联单据页
			toNext(){
				uni.setStorage({
					key:'formInfo',
					data:this.formData
				})
				uni.navigateTo({
					// url: "repairStep2?id=" + this.id+"&recordId="+this.recordId+"&sparePartsCost="+this.sparePartsCost
					url: "repairStep?id="+this.id
				});
			}
			//点击暂存和确认提交 需要进行的操作。
			// goAddRepair(flag){

			// 	var _this = this;
			// 	//在这里是抄送人数据。
			// 	var carbonCopyRecipients = []
			// 	if(this.targetList.length>0){
			// 		this.targetList.forEach((vals,index)=>{
			// 			carbonCopyRecipients.push(vals.user_id);
			// 		});
			// 	}
			// 	if(!(this.payInfo && this.payInfo.totalNumber)){
			// 		uni.showToast({
			// 			    title: '请输入付款金额',
			// 			    duration: 2000,
			// 				icon:"none"
			// 			});
			// 		return false;
			// 	}
			// 	var payInfom  = uni.getStorageSync('payInfo');
			// 	if(flag == 'tj'){
			// 		//提交进行的操作
			// 		var url = '/apis/approveFlow/submitApprove'
			// 		//调取接口进行保存。
			// 		this.$http.request({
			// 		  url: url,
			// 		  data:{
			// 			  dataType: 10,
			// 			  mainId: payInfom.info.id
			// 		  }
			// 		}).then(res=>{
			// 			if(res.data.code == 0){
			// 				uni.removeStorageSync('payInfo');
			// 				uni.showToast({
			// 					title: '操作成功',
			// 					duration: 	1000,
			// 					icon:"none"
			// 				});
			// 				setTimeout( function(){
			// 					uni.redirectTo({
			// 					    url: 'payApply'
			// 					});
			// 				},1000)
			// 			}else{
			// 				uni.showToast({
			// 					title: res.data.msg,
			// 					duration: 	2000,
			// 					icon:"none"
			// 				});
			// 			}
			// 		}).catch(err=>{
			// 			uni.showToast({
			// 				title: '操作失败',
			// 				duration: 	2000,
			// 				icon:"none"
			// 			});
			// 		});
			// 	}else if(flag == 'zc'){
			// 		//暂存进行的操作。
			// 		var url = '/apis/payApply/addAndSaveChange'
			// 		//调取接口进行保存。
			// 		this.$http.request({
			// 		  url: url,
			// 		  params:{
			// 			  totalNumber:this.payInfo.totalNumber,
			// 			  payUser:this.payInfo.payUser,
			// 			  blankAccount:this.payInfo.blankAccount,
			// 			  payDate:this.payInfo.payDate,
			// 			  payReason:this.payInfo.payReason,
			// 			  processInstanceId:payInfom.info.process_instance_id||'',
			// 			  newApproveList:carbonCopyRecipients, 
			// 			  taglocationappearanceImage:this.imgsrc_list,
			// 			  id:this.id||''
			// 		  }
			// 		}).then(res=>{
			// 			if(res.data.code == 0){
			// 				if(this.payInfo.approveState==-1){
			// 					this.id = res.data.dataId
			// 				}
			// 				this.getDetail()
			// 			}else{
			// 				uni.showToast({
			// 					title: res.data.msg,
			// 					duration: 	2000,
			// 					icon:"none"
			// 				});
			// 			}
			// 		}).catch(err=>{
			// 			uni.showToast({
			// 				title: '操作失败',
			// 				duration: 	2000,
			// 				icon:"none"
			// 			});
			// 		});
			// 	}
			// }
		},
	}
</script>
<style scoped>
	.itemunit {
		position: absolute;
		right: 0;
		top: 0;
		height: 92upx;
		line-height: 92upx;
		color: #999;
		font-size: 26upx;
	}
</style>
