<template>
	<view class="bg-white">
		<!-- 顶部 -->
		<cu-custom bgColor="bg-blue" :isBack="true">
			<block slot="backText"></block>
			<block slot="content"></block>
			<block slot="right">
			</block>
		</cu-custom>
		<view style="padding: 15px;">
			<uni-forms ref="form" label-width="110px" :modelValue="addform">
				<uni-forms-item label="合同段">
					<uni-easyinput v-model="addform.contractName" disabled placeholder="请输入合同段" />
				</uni-forms-item>
				<uni-forms-item label="检查日期" required name="startDate">
					<uni-datetime-picker type="date" return-type="string" :disabled="addInfoType != 1" v-model="addform.startDate"/>
				</uni-forms-item>
				<uni-forms-item label="检查单位" required name="supervisionUnitName">
					<uni-easyinput v-model="addform.supervisionUnitName" :disabled="addInfoType != 1" placeholder="请输入检查单位" />
				</uni-forms-item>
				<uni-forms-item label="被检单位" required>
					<uni-easyinput v-model="addform.contractorUnitName" disabled placeholder="请输入被检单位" />
				</uni-forms-item>
				<uni-forms-item label="是否限期整改" required>
					<uni-data-checkbox v-model="addform.deadline" :disabled="addInfoType != 1" :localdata="[{text: '是',value: 1}, {text: '否',value: 0}]" />
				</uni-forms-item>
				<uni-forms-item label="整改期限日期" name="endDate">
					<uni-datetime-picker type="date" return-type="string" :disabled="addInfoType != 1" v-model="addform.endDate"/>
				</uni-forms-item>
				<uni-forms-item label="检查人员" required name="checkName">
					<uni-easyinput v-model="addform.checkName" :disabled="addInfoType != 1" placeholder="请输入检查人员" />
				</uni-forms-item>
				<uni-forms-item label="整改人" required name="taskflowUser">
					<view class="flex">
						<uni-easyinput :value="taskflowUserStr" disabled />
						<view class="name-btn" @click="userChange(1)" v-if="addInfoType == 1">
							选择+
						</view>
						<view class="name-btn name-btn-dis" v-else>
							选择+
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="通知人" >
					<view class="flex">
						<uni-easyinput :value="noticeUserStr" disabled />
						<view class="name-btn" @click="userChange(2)" v-if="addInfoType == 1">
							选择+
						</view>
						<view class="name-btn name-btn-dis" v-else>
							选择+
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="隐患部位及描述">
					<uni-easyinput v-model="addform.hiddenDanger" :disabled="addInfoType != 1" type="textarea" placeholder="请输入隐患部位及描述" />
				</uni-forms-item>
				<uni-forms-item label="整改要求">
					<uni-easyinput v-model="addform.modifyRequirements" :disabled="addInfoType != 1" type="textarea" placeholder="请输入整改要求" />
				</uni-forms-item>
			</uni-forms>
			<view>
				<view class="margin-bottom-sm">
					<view class="flex justify-between">
						<view>
							<text>下发附件</text>
							<button @click="fileList.push({remark:'',files:[]})" v-if="addInfoType == 1" class="cu-btn sm margin-left-sm">新增附件</button>
						</view>
						<view>
							<uni-icons @click="fileUp(1)" type="upload" size="20" color="#1e91ff" class="margin-left-sm" v-if="addInfoType == 1"></uni-icons>
							<uni-icons  type="upload" size="20"  class="margin-left-sm" v-else></uni-icons>
							<uni-icons @click="fileListDel(1)" type="trash" size="20" color="#bd3124" class="margin-left-sm" v-if="addInfoType == 1"></uni-icons>
							<uni-icons type="trash" size="20"  class="margin-left-sm" v-else></uni-icons>
							<uni-icons @click="seeImg(fileList,fileSelect)" type="eye" size="20" color="#1e91ff" class="margin-left-sm"></uni-icons>
						</view>
					</view>
					<uni-table ref="table" border stripe type="selection" emptyText="暂无数据" @selection-change="selectionChange">
						<uni-tr>
							<uni-th width="30" align="center">序号</uni-th>
							<uni-th align="center">隐患位置</uni-th>
							<uni-th align="center">照片/附件</uni-th>
						</uni-tr>
						<uni-tr v-for="(item, index) in fileList" :key="index">
							<uni-td>{{index+1}}</uni-td>
							<uni-td align="center">
								<uni-easyinput v-model="item.remark" :disabled="addInfoType != 1" placeholder="隐患位置" />
							</uni-td>
							<uni-td align="center">
								<view>
									<template v-for="(file,fileindex) in item.files">
										<template v-if="file.name">
										  <text>{{file.name}}</text>
										  <uni-icons type="closeempty" size="20"  color="#e99d42" @click="fileListFliesDel(index,fileindex,fileList)" v-if="addInfoType == 1"></uni-icons>
										  <text v-if="fileindex < item.files.length-1">、</text>
										</template>
									</template>
								</view>
							</uni-td>
						</uni-tr>
					</uni-table>
				</view>
				<view class="margin-bottom-sm">
					<view class="flex justify-between">
						<view>
							<text>整改附件</text>
							<button @click="fileList2.push({remark:'',files:[]})" v-if="addInfoType != 3" class="cu-btn sm margin-left-sm">新增附件</button>
						</view>
						<view>
							<uni-icons @click="fileUp(2)" type="upload" size="20" color="#1e91ff" class="margin-left-sm" v-if="addInfoType != 3"></uni-icons>
							<uni-icons  type="upload" size="20"  class="margin-left-sm" v-else></uni-icons>
							<uni-icons @click="fileListDel(2)" type="trash" size="20" color="#bd3124" class="margin-left-sm" v-if="addInfoType != 3"></uni-icons>
							<uni-icons type="trash" size="20"  class="margin-left-sm" v-else></uni-icons>
							<uni-icons @click="seeImg(fileList2,fileSelect2)" type="eye" size="20" color="#1e91ff" class="margin-left-sm"></uni-icons>
						</view>
					</view>
					<uni-table ref="table2" border stripe type="selection" emptyText="暂无数据" @selection-change="selectionChange2">
						<uni-tr>
							<uni-th width="30" align="center">序号</uni-th>
							<uni-th align="center">隐患位置</uni-th>
							<uni-th align="center">照片/附件</uni-th>
						</uni-tr>
						<uni-tr v-for="(item, index) in fileList2" :key="index">
							<uni-td>{{index+1}}</uni-td>
							<uni-td align="center">
								<uni-easyinput v-model="item.remark" :disabled="addInfoType == 3" placeholder="隐患位置" />
							</uni-td>
							<uni-td align="center">
								<view>
									<template v-for="(file,fileindex) in item.files">
									  <template v-if="file.name">										  
										<text>{{file.name}}</text>
										<uni-icons type="closeempty" size="20" color="#e99d42" @click="fileListFliesDel(index,fileindex,fileList2)" v-if="addInfoType != 3"></uni-icons>
										<text v-if="fileindex < item.files.length-1">、</text>
									  </template>
									</template>
								</view>
							</uni-td>
						</uni-tr>
					</uni-table>
				</view>
			</view>
		</view>
		
		<view style="height: 120rpx;"></view>
		<view class="fixed-bottom">
			<view v-if="addInfoType == 1 || addInfoType == 2">
				<button class="cu-btn" @click="submitForm">确定</button>
				<button class="cu-btn line-grey margin-left-lg" @click="backPage">取消</button>
			</view>
			<view v-if="addInfoType == 3">
				<template v-if="type2 =='review'">
					<button class="cu-btn bg-green" @click="finish">更新为已办结</button>
					<button class="cu-btn line-grey margin-left-lg" @click="backPage">取消</button>
				</template>
				<template v-else>
					<button class="cu-btn line-grey margin-left-lg" @click="backPage">取消查看</button>
				</template>
			</view>
		</view>
	</view>
</template>
<script>
	import config from "../../core/api.js"
	export default {
		data() {
			return {
				addInfoType:1,//1.正常填写，2.只有整改附件可以修改，3.都不能修改
				type2:'',
				
				addform:{
				  startDate:'',
				  endDate:'',
				  contractName:'',
				  contractorUnitName:'',
				  hiddenDanger:'',
				  modifyRequirements:'',
				  deadline:1
				},
				
				userid:null,
				project:null,
				
				personType:1,
				
				fileList:[],
				fileSelect:[],
				fileList2:[],
				fileSelect2:[],
				
				// 校验规则
				rules: {
					supervisionUnitName: {
						rules: [{
							required: true,
							errorMessage: '请输入检查单位'
						}]
					},
					startDate: {
						rules: [{
							required: true,
							errorMessage: '请输入检查单位'
						}]
					},
					checkName: {
						rules: [{
							required: true,
							errorMessage: '请输入检查人员'
						}]
					},
				}
			}
		},
		computed:{
			taskflowUserStr: function () {
				if(this.addform.taskflowUser && this.addform.taskflowUser.length){
					let str = '';
					for(let i=0;i<this.addform.taskflowUser.length;i++){
					  str += this.addform.taskflowUser[i].user_name;
					  if(i < this.addform.taskflowUser.length-1){
						  str += ','
					  }
					}
					return str;
				}else{
					return '请选择施工单位接收人员';
				}
			},
			noticeUserStr:function () {
				if(this.addform.noticeUser && this.addform.noticeUser.length){
					let str = '';
					for(let i=0;i<this.addform.noticeUser.length;i++){
					  str += this.addform.noticeUser[i].user_name;
					  if(i < this.addform.noticeUser.length-1){
						  str += ','
					  }
					}
					return str;
				}else{
					return '请选择通知人';
				}
			}
		},
		onLoad(e) {
			this.userid = uni.getStorageSync("userInfo").id;
			this.project = uni.getStorageSync("porject"+"_"+uni.getStorageSync("userInfo").id);
			this.addform.contractName = this.project.contractName;
			this.addform.startDate = this.$dayjs().format('YYYY-MM-DD');
			
			if(e.type){
				this.addInfoType = e.type;
			}
			if(e.id){
				this.getDetail(e.id);
			}
			if(e.type2){
				this.type2 = e.type2;
			}
		},
		onShow() {
			this.getEditData();
			
			uni.$on("principal", res => {
				if(this.personType == 1){
				  this.$set(this.addform,'taskflowUser',res);
				}else if(this.personType == 2){
				  this.$set(this.addform,'noticeUser',res);
				}
			})
		},
		onReady() {
			// 设置自定义表单校验规则，必须在节点渲染完毕后执行
			this.$refs.form.setRules(this.rules)
		},
		methods: {
			getEditData(){
				this.http.request("/app/qualityModifyInfo/getEditData",{
					id:this.project.contractId,
				}).then((json)=>{
					if(json.result == 1){
						this.addform.contractorUnitName = json.data.contractorUnitName;
					}
				})
			},
			
			userChange(type){
				var list = [];
				this.personType = type;
				if(type == 1 && this.addform.taskflowUser){
				  list = this.addform.taskflowUser;
				}
				if(type == 2 && this.addform.noticeUser){
				  list = this.addform.noticeUser;
				}
				//把已选值储存到全局变量
				getApp().globalData.principal = list;
				uni.navigateTo({
					url: "/pages/constructionLog/personnel/personnel?name=" + '选择人员'
				})
			},
			
			fileUp(type){
				let list = [];
				let selects = [];
				if(type == 1){
					if(this.fileSelect.length == 0){
						this.$prompt.none("请先勾选数据，再上传文件");
						return;
					}
					selects = this.fileSelect;
					list = this.fileList;
				}else if(type == 2){
					if(this.fileSelect2.length == 0){
						this.$prompt.none("请先勾选数据，再上传文件");
						return;
					}
					selects = this.fileSelect2;
					list = this.fileList2;
				}
				uni.chooseFile({
				  count: 99, //默认100
				  extension:['.jpg','.png','.pdf'],
					success: (res)=>{
						//console.log(res);
						selects.forEach((i)=>{
							res.tempFiles.forEach((file)=>{
								list[i].files.push(file)
							})
						})
					}
				});
			},
			
			// 多选
			selectionChange(e) {
				//console.log(e.detail.index)
				this.fileSelect = e.detail.index;
			},
			selectionChange2(e) {
				//console.log(e.detail.index)
				this.fileSelect2 = e.detail.index;
			},
			
			fileListFliesDel(index1,index2,list){
				list[index1].files.splice(index2,1);
				if(this.addInfoType == 2){
					this.$forceUpdate();
				}
			},
			
			fileListDel(type){
				var list = [];
				var selects = [];
				var table = null;
				if(type == 1){
					list = this.fileList;
					selects = this.fileSelect;
					table = this.$refs.table;
				}else if(type == 2){
					list = this.fileList2;
					selects = this.fileSelect2;
					table = this.$refs.table2;
				}
				selects.sort(function(a,b){
					return  b-a;
				})
				selects.forEach((i)=>{
					list.splice(i,1);
				})
				
				table.clearSelection();
			},
			
			seeImg(filelist,selects){
				if(selects.length != 1){
					this.$prompt.none("只能预览一条数据");
					return;
				}
				if(!this.addform.id){
					this.$prompt.none("保存后才能预览");
					return;
				}
				let row = filelist[selects[0]];
				this.http.request("/app/qualityModifyInfo/seeImgUrl",{
					id:this.addform.id,
					type:row.type,
					groupType:row.groupType
				}).then((json)=>{
					if(json.result == 1){
						var encode=encodeURIComponent(json.data);
						uni.navigateTo({
							url:"/pages/view/preview/preview?preview="+ encode
						})
					  }else{
						this.$prompt.none(json.msg);
					  }
				})
			},
			
			submitForm(){
				this.$refs.form.validate().then(res => {
					if (this.addform.deadline == '1' && !this.addform.endDate) {
						this.$prompt.none("请选择整改期限日期");
						return;
					}
					if (!(this.addform.taskflowUser && this.addform.taskflowUser.length)) {
						this.$prompt.none("请选择整改人员");
						return;
					}
					this.addInfoHandle();
				})
			},
			
			addInfoHandle(){
				//console.log('addInfoHandle')
				let taskflowUserIds = [];
				if(this.addform.taskflowUser){
				  this.addform.taskflowUser.forEach(element => {
					taskflowUserIds.push(element.id)
				  });
				}

				let noticeUserIds = [];
				if(this.addform.noticeUser){
				  this.addform.noticeUser.forEach(element => {
					noticeUserIds.push(element.id)
				  });
				}
				
				//var formData = new FormData();
				
				//console.log(formData)
				// if(this.addInfoType == 2){
				// 	formData.append('id', this.addform.id)
				// 	formData.append('status', 2)//复核中
				// }
				// formData.append('cs', 1)//监理指令1  施工整改0 
				// formData.append('contractName', this.addform.contractName)
				// formData.append('supervisionUnitName', this.addform.supervisionUnitName)
				// formData.append('contractorUnitName', this.addform.contractorUnitName)
				// formData.append('deadline', this.addform.deadline)
				// formData.append('startDate', this.$dayjs(this.addform.startDate).format('YYYY 年 MM 月 DD 日'))
				// formData.append('endDate', this.$dayjs(this.addform.endDate).format('YYYY 年 MM 月 DD 日'))
				// formData.append('checkName', this.addform.checkName)
				// formData.append('taskflowUserIds', taskflowUserIds.join(','))
				// formData.append('noticeUserIds', noticeUserIds.join(','))
				// formData.append('hiddenDanger', this.addform.hiddenDanger)
				// formData.append('modifyRequirements', this.addform.modifyRequirements)
				
				let formData = {};
				if(this.addInfoType == 2){
					formData.id = this.addform.id;
					formData.status = 2;//复核中
				}
				formData.cs = 1;//监理指令1  施工整改0
				formData.contractName = this.addform.contractName;
				formData.supervisionUnitName = this.addform.supervisionUnitName;
				formData.contractorUnitName = this.addform.contractorUnitName;
				formData.deadline = this.addform.deadline;
				formData.startDate = this.$dayjs(this.addform.startDate).format('YYYY 年 MM 月 DD 日');
				formData.endDate = this.$dayjs(this.addform.endDate).format('YYYY 年 MM 月 DD 日');
				formData.checkName = this.addform.checkName;
				formData.taskflowUserIds = taskflowUserIds.join(',');
				formData.noticeUserIds = noticeUserIds.join(',');
				formData.hiddenDanger = this.addform.hiddenDanger;
				formData.modifyRequirements = this.addform.modifyRequirements;

				let fileLists = [];
				for(var i=0;i<this.fileList.length;i++){
				  if(this.fileList[i].files&&this.fileList[i].files.length){
					this.fileList[i].files.forEach((file)=>{
					  fileLists.push({
						id:file.id,
						file:file,
						remark:this.fileList[i].remark,
						type:1,
						groupType:i+1,
					  })
					})
				  }else{
					fileLists.push({
						remark:this.fileList[i].remark,
						type:1,
						groupType:i+1,
					  })
				  }
				}

				for(var i=0;i<this.fileList2.length;i++){
				  if(this.fileList2[i].files&&this.fileList2[i].files.length){
					this.fileList2[i].files.forEach((file)=>{
					  fileLists.push({
						id:file.id,
						file:file,
						remark:this.fileList2[i].remark,
						type:0,
						groupType:i+1,
					  });
					})
				  }else{
					fileLists.push({
						remark:this.fileList2[i].remark,
						type:0,
						groupType:i+1,
					  })
				  }
				}
				
				//console.log(fileLists)
				// fileLists.forEach((file,i)=>{
				//   if(file.file){
				// 	formData.append('images['+i+'].file',file.file);
				//   }
				//   formData.append('images['+i+'].remark',file.remark);
				//   formData.append('images['+i+'].type',file.type);
				//   formData.append('images['+i+'].groupType',file.groupType);
				// })
				
				// let jsonData = {};
				// //console.log(formData)
				// formData.forEach((value, key) => jsonData[key] = value);
				// jsonData.userId = this.userid;
				// jsonData.projectId = this.project.id;
				// jsonData.contractId = this.project.contractId;
				// console.log(jsonData)
				////return;
				
				fileLists.forEach((file,i)=>{
					//console.log(file)
				  if(file.file && file.file.size){
					formData['images['+i+'].file'] = file.file;
				  }
				  if(file.id){
					  formData['images['+i+'].id'] = file.id;
					}
				  formData['images['+i+'].remark'] = file.remark;
				  formData['images['+i+'].type'] = file.type;
				  formData['images['+i+'].groupType'] = file.groupType;
				})
				formData.userId = this.userid;
				formData.projectId = this.project.id;
				formData.contractId = this.project.contractId;
				console.log(formData)
				//return;
				
				const url = config.api;
				const token = uni.getStorageSync("token");
				uni.showLoading({
					title: '加载中'
				});
				uni.uploadFile({  
				    url: url+"/app/qualityModifyInfo/save",  
				    filePath: '123', // 随便填，不为空即可  
				    name: '123', // 随便填，不为空即可  
				    header: {
				    	"Authorization": token,
				    }, // 可以加access_token等  
				    formData: formData, // 接口参数，json格式，底层自动转为FormData的格式数据  
				    success: (res) => {
						//console.log(res);
						this.$prompt.none("保存成功");
						setTimeout(function(){
							uni.navigateBack({
								delta:1
							})
						},500)
					},complete() {
						uni.hideLoading();
					}
				})

			  },
			  
			  getDetail(id){
				  this.http.request("/app/qualityModifyInfo/edit",{
				  	id:id,
				  }).then((json)=>{
				  	if(json.result == 1){
						//this.$set(this,'addform',json.data)
						this.addform = json.data;
						this.addform.startDate = this.$dayjs(this.addform.startDate,'YYYY 年 MM 月 DD 日','zh-cn').format('YYYY-MM-DD')
						this.addform.endDate = this.$dayjs(this.addform.endDate,'YYYY 年 MM 月 DD 日','zh-cn').format('YYYY-MM-DD')
						//回显用户
						var users = [];
						var idList = this.addform.taskflowUserIds.split(',');
						var nameList = this.addform.userName.split(',');
						//console.log(idList)
						idList.forEach((userid,index)=>{
						  users.push({
							user_name:nameList[index],
							id:userid
						  })
						})
						this.$set(this.addform,'taskflowUser',users)
						
						var notices = [];
						var nidList = [];
						
						if(this.addform.noticeUserName && this.addform.noticeUserIds){
							var nnameList = this.addform.noticeUserName.split(',');
							nidList = this.addform.noticeUserIds.split(',')
							nidList.forEach((userid,index)=>{
							  notices.push({
								user_name:nnameList[index],
								id:userid
							  })
							})
							this.$set(this.addform,'noticeUser',notices)
						}
			
						//回显附件
						this.fileList = [];
						this.fileList2 = [];
						var imgs = [];
						if(json.otherParam){
						  imgs = json.otherParam;
						  imgs.forEach((img)=>{
							var tmp;
							if(img.type == 1){
							  tmp = this.fileList;
							}else{
							  tmp = this.fileList2;
							}
							if(tmp[img.groupType-1]){
							  tmp[img.groupType-1].files.push(img)
							}else{
							  tmp[img.groupType-1] = img;
							  tmp[img.groupType-1].files = [Object.assign({},img)]
							}
							
						  })
						}
					}
				  })
			  },
			  
			  finish(){
				  this.changeStatus(3);
			  },
			  changeStatus(code){
			  	this.http.request("/app/qualityModifyInfo/updateStatus",{
					userId:this.userid,
			  		id:this.addform.id,
			  		opCode:code
			  	}).then((json)=>{
			  		if(json.result == 1){
			  			this.$prompt.none("操作成功");
			  			setTimeout(function(){
			  				uni.navigateBack({
			  					delta:1
			  				})
			  			},500)
			  		}
			  	})
			  },
			
			backPage(){
				uni.navigateBack({
					delta: 1
				});
			}
		}
	}
</script>

<style lang="scss">
	.name-btn{
		background-color: #e99d42;
		border-radius: 4px;
		font-size: 14px;
		color: #FFFFFF;
		border: 1px solid #bbbbbb;
		padding: 15rpx 20rpx;
		margin-left: 20px;
	}
	.name-btn-dis{
		background-color: #bbbbbb;
	}
	
	.fixed-bottom{
		position: fixed;
		bottom: 0;
		width: 100%;
		height: 120rpx;
		background-color: #fff;
		text-align: center;
		padding-top: 30rpx;
	}
</style>
