<template>
	<view>
		<!-- 顶部 -->
		<cu-custom bgColor="bg-blue" :isBack="true">
			<block slot="backText">编辑监理巡视记录</block>
			<block slot="content"></block>
			<block slot="right">
				<view class=" flex justify-center">
					<template v-if="dateList[0].taskStatus == '0' || dateList[0].taskStatus == '1'">
						<button @click="repeal()" class="margin-top-ssm cu-btn line-blue round text-white" style="width: 130rpx;height: 66rpx;padding: 0;">废除</button>
					</template>
					<template v-else>
						<button @click="save(2)" class="margin-top-ssm cu-btn line-blue round text-white" style="width: 130rpx;height: 66rpx;padding: 0;">上报</button>
					</template>
					<!-- <button  @click="save()" class="margin-top-ssm cu-btn line-blue round text-white" style="width: 160rpx;height: 66rpx;padding: 0;">保存</button> -->
					<button class="margin-top-ssm  cu-btn round line-blue text-white">
						<button class="cu-btn  line-blue" style="padding:0 20rpx 0 10rpx" @click="save(1)">
							<text class="text-white">预览</text>
						</button>
						<template v-if="!(dateList[0].taskStatus == '0' || dateList[0].taskStatus == '1')">
							<text class="bg-white" style="width: 1rpx;height: 30rpx;"></text>
							<button class=" cu-btn  line-blue" style="padding:0 10rpx 0 20rpx" @click="save()">
								<text class="text-white">保存</text>
							</button>
						</template>
					</button>
				</view>
			</block>
		</cu-custom>
		<!-- 项目合同段信息 -->
		<!-- <view style="background-color: #fff;padding: 22rpx;margin-bottom: 20rpx;"> 
			<view style="font-size: 30rpx;color: #101010;font-weight: bold;">{{project.project_name}}</view>
			<view style="font-size: 28rpx;color: #101010;margin-top: 10rpx;">{{project.contractName}}</view>
		</view> -->
		<view v-for="(data,index) in dateList" :key="index">
			<form>
				<view class="cu-form-group_1 flex justify-between">
					<view>
						<text  class="title">日志{{index+1}}</text>
						<button class="cu-btn round sm margin-left-sm" @click="addNow(index)" v-if="!(data.taskStatus==0 || data.taskStatus==1)">复制当前</button>
					</view>
					<button class="cu-btn round sm" @click="delOne(index)" v-if="!(data.taskStatus==0 || data.taskStatus==1)&&(index != 0)">删除</button>
				</view>
				<template v-if="project && project.contract_type == 1">
					<checkbox-group @change="checkboxChange($event,index,1)" class="block" style="padding: 0 10px;background-color: #FFFFFF;">
						<view>单位</view>
						<template v-for="(item,index2) in data.constructi2onList">
							<view style="padding-top: 10px;">
								<checkbox v-if="item.contractorUnitName" :value='item.id' class='round' :class="item.checked?'checked':''" :checked="item.checked" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" style="transform:scale(0.82)"></checkbox>
								<text style="margin-left: 20rpx;">{{item.contractorUnitName}}</text>
							</view>
						</template>
					</checkbox-group>
					<checkbox-group @change="checkboxChange($event,index,2)" class="block" style="padding: 0 10px;background-color: #FFFFFF;">
						<view>合同段</view>
						<template v-for="(item,index2) in data.contractIdDataList">
							<span style="padding-top: 10px;margin-right: 30rpx;">
								<checkbox v-if="item.contractNumber" :value='item.id' class='round' :class="item.checked?'checked':''" :checked="item.checked" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" style="transform:scale(0.82)"></checkbox>
								<text style="margin-left: 10rpx;">{{item.contractNumber}}</text>
							</span>
						</template>
					</checkbox-group>
				</template>
				<view class="cu-form-group_1">
					<view class="title">巡视时间</view>
					<input placeholder-style="color:#AEAEAE" placeholder="请输入" disabled="" v-model="data.date" name="input"></input>
				</view>
				<view class="cu-form-group_1">
					<view class="title">编号</view>
					<input placeholder-style="color:#AEAEAE" placeholder="请输入" v-model="data.serialNumber" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" name="input"></input>
				</view>
			</form>
			<form>
				<view class="cu-form-group_2">
					<view class="title">巡视的范围</view>
					<view>
						<textarea placeholder-style="color:#AEAEAE" maxlength="-1" v-model="data.jobContent" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" placeholder="请输入"></textarea>
					</view>
				</view>
				<!-- <view class="cu-form-group_2">
					<view class="title flex justify-between">
						<text>关联工序</text>
						<button class="cu-btn round line-blue sm" @click="toSelectProcess(index)" style="font-size: 26rpx;">
							<text class="cuIcon-add"></text>新增
						</button>
					</view>
					<view>
						<view class="text-gray" v-if="data.processList && data.processList.length < 1">可多选，添加关联工序后可在资料填报页面查看关联的旁站记录</view>
						<template v-else>
							<view v-for="(process,index2) in data.processList" :key="process.id" style="margin-bottom: 10rpx;">
								<text class="text-gray process-line" style="position: relative;">{{process.pathName || process.name}}
									<image src="/static/index/delete-blue.png" style="width: 32rpx;height: 32rpx;position: absolute;bottom: 0;" @click="deleProcess(index2,index)"></image>
								</text>
							</view>
						</template>
					</view>
				</view> -->
				<view class="cu-form-group_2">
					<view class="title">主要施工情况</view>
					<view>
						<textarea placeholder-style="color:#AEAEAE" maxlength="-1" v-model="data.patrolContent" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" placeholder="请输入"></textarea>
					</view>
				</view>
				<view class="cu-form-group_2">
					<view class="title">质量、安全、环保等情况</view>
					<view>
						<textarea placeholder-style="color:#AEAEAE" maxlength="-1" v-model="data.acceptance" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" placeholder="请输入"></textarea>
					</view>
				</view>
				<view class="cu-form-group_2">
					<view class="title">发现的问题及处理意见</view>
					<view>
						<textarea placeholder-style="color:#AEAEAE" maxlength="-1" v-model="data.problem" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" placeholder="请输入"></textarea>
					</view>
				</view>
			</form>
		</view>
		<view class="cu-bar bg-white tabbar" style="border: none;"></view>
		<view class="cu-bar bg-white tabbar border shop" style="position: fixed;bottom: 0;left: 0;width: 100%;border-top: 1rpx solid #EAEAEA;">
			<view class="flex solid-bottom padding justify-between" style="width: 100%;">
				<text></text>
				<button class="cu-btn round" @click="addOne" v-if="!(dateList[0].taskStatus == '0' || dateList[0].taskStatus == '1')">新增</button>
			</view>
		</view>
		<!-- <form>
			<view class="cu-form-group_1"  @click="navTo(2)" style="justify-content: space-between;">
				<view class="title">监理员</view>
				<input placeholder-style="color:#AEAEAE" placeholder="请选择" v-model="data.supervisionWorker"  disabled=""  style="width: 520rpx;"></input>
				<text class='cuIcon-right'></text>
			</view>
			<view class="cu-form-group_1" @click="navTo(1)" style="justify-content: space-between;">
				<view class="title">施工员</view>
				<input placeholder-style="color:#AEAEAE" placeholder="请选择" v-model="data.constructionWorker" disabled=""  style="width: 520rpx;"></input>
				<text class='cuIcon-right'></text>
			</view>
		</form> -->
		<!-- 时间弹窗 -->
		<view class="cu-modal bottom-modal" :class="modalShow?'show':''">
			<view class="cu-dialog" style="background-color: white;border-radius: 20rpx 20rpx 0 0;">
				<view class="cu-bar bg-white">
					<view class="action text-gray"></view>
					<view class="action text-black text-bold" style="color: #101010;">选择时间</view>
					<view class="action text-gray" @tap="showdialog()">取消</view>
				</view>
				<view style="padding-bottom: 10rpx;">
					<calendar @selected-change="datechange" :showBack="false" :dotStyle="dotStyle"></calendar>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				dotStyle: {
					color: 'black'
				},
				project: "",
				time: "",
				constructionList: [],
				supervisionList: [],
				modalShow: false,
				// data: {

				// },
				dateList:[{
					pageNumber:1,
					recorderId:uni.getStorageSync("userInfo").id,
					contractId:uni.getStorageSync("porject"+"_"+uni.getStorageSync("userInfo").id).contractId,
					processList:[],
					constructi2onList:[],
					contractIdDataList:[],
				}],
				curIndex:0,
				
				updateOrInsert: 0, //0为新增 ， 1为编辑
				upId: null,
				
				
				constructi2onList:[],
				contractIdDataList:[],
				
				contractId : uni.getStorageSync("porject"+"_"+uni.getStorageSync("userInfo").id).contractId,
				project:uni.getStorageSync("porject"+"_"+uni.getStorageSync("userInfo").id),
				recorderId:uni.getStorageSync("userInfo").id,
			}
		},
		async onLoad(e) {
			this.dateList[0].date = e.time;
			this.project = uni.getStorageSync("porject" + "_" + uni.getStorageSync("userInfo").id);
			this.updateOrInsert = e.type;
			this.upId = e.id;
			
			if(this.project.contract_type == 1){
				await this.getcontractInfoListByContract();
			}
			//console.log(this.constructi2onList)
			//debugger
			
			if (this.updateOrInsert == 1) { //获取日志信息进行绑定
				//this.findData(this.upId);
				this.getDataByDate(e.time);
			} else {
				//获取合同段的地址，根据地址获取温度和天气
				var that = this;
				var cityName = uni.getStorageSync("porject" + "_" + uni.getStorageSync("userInfo").id).project_place;
				that.http.request("/app/diary/getWeather", {
					projectId:that.project.id,
					contractId:that.contractId,
					date:e.time
				}).then((res) => {
					//that.$set(that.data,'averageTemperature',res.tempSection);
					that.$set(that.dateList[0], 'weather', res.weather);
					//that.data.averageTemperature =res.tempSection;
					//that.data.weather = res.weather
				})
				this.dateList[0].constructi2onList = this.getNewOption(this.constructi2onList)
				this.dateList[0].contractIdDataList = this.getNewOption(this.contractIdDataList);
			}
			
			//监听选择工序
			uni.$on('selectProcess',this.selectProcess)
			
			uni.$on('report',this.reportSuccess)
		},
		onUnload(){
			uni.$off('selectProcess',this.selectProcess)
			
			uni.$off('report',this.reportSuccess)
		},
		methods: {
			showdialog() {
				this.modalShow = !this.modalShow;
			},
			datechange(e) {
				this.data.startTime = e.fullDate
				this.showdialog();
			},
			navTo(value) {
				uni.navigateTo({
					url: "/pages/constructionLog/personnel/personnel?type=" + value
				})
			},
			//获取该日志的数据，编辑
			findData(id) {
				var that = this;
				that.http.request('/app/patrol/getDataById', {
					id: id
				}).then((result) => {
					that.data = result.data;
					that.$delete(that.data, 'prefix');
				})
			},
			// save(){
			// 	var that =this;
			// /* 	let result= that.$formValidate.validate(this.data,this.rules)//表单验证
			// 	if(result.isOk){ */
			// 		let param =that.data;
			// 		param.contractId= this.project.contractId;
			// 		param.creator= uni.getStorageSync("userInfo").id;
			// 		param.state= that.data.state==null ? 0 : that.data.state;
			// 		param.deleted= that.data.deleted==null ? 0 : that.data.deleted;
			// 		param.createTime=new Date();
			// 	    that.http.request('/app/diary/addOrUpdate', param).then((result)=>{
			// 	    	if(result.result=="1"){
			// 	    		that.$prompt.none(result.msg);
			// 	    		setTimeout(function(){
			// 	    			uni.navigateBack({
			// 	    				delta:1
			// 	    			})
			// 	    		},500)						   
			// 	    	}else{
			// 	    		 that.$prompt.Error("保存失败");						  
			// 	    	}
			// 	    })
			// 	/* }else{
			// 		that.$prompt.none(result.errmsg)
			// 	} */

			// }
			save(type) {
				if(!this.verification()){
					uni.showToast({
					    title: '每份日志至少要填写一项内容',
						icon:'none',
					    duration: 2000
					});
					return;
				}
				// this.data.contractId = this.project.contractId;
				// this.data.recorderId = uni.getStorageSync("userInfo").id;
				for (let j=0; j < this.dateList.length; j++){
					let arr = [];
					if(this.dateList[j].processList){
						for (let i = 0; i < this.dateList[j].processList.length; i++) {
							arr.push(this.dateList[j].processList[i].id);
						}
					}
					this.dateList[j].processId = arr.join(',');
										
					if (this.constructi2onList && this.constructi2onList.length > 0) {
						var arr2 = [];
						for (var i = 0; i < this.dateList[j].constructi2onList.length; i++) {
							if(this.dateList[j].constructi2onList[i].checked){
								arr2.push(this.dateList[j].constructi2onList[i].id)
							}
						}
						this.dateList[j].constructionUnits = arr2.join(',');
					} else {
						this.dateList[j].constructionUnits = null;
					}
					if (this.contractIdDataList && this.contractIdDataList.length > 0) {
						var arr2 = [];
						for (var i = 0; i < this.dateList[j].contractIdDataList.length; i++) {
							if(this.dateList[j].contractIdDataList[i].checked){
								arr2.push(this.dateList[j].contractIdDataList[i].id)
							}
						}
						this.dateList[j].contractIds = arr2.join(',');
					} else {
						this.dateList[j].contractIds = null;
					}
				}
				//this.http.request('/app/patrol/addEntity.json', JSON.stringify(this.dateList), 1).then((res) => {
				this.http.request('/app/patrol/addEntity.json', {voStr:JSON.stringify(this.dateList),storeName:uni.getStorageSync("storeName")}).then((res) => {
					if (res.result == "1") {
						let urlArr = [];
						for (let i = 0; i < res.datas.length; i++) {
							this.dateList[i].id = res.datas[i].id;
							this.dateList[i].outUrl = res.datas[i].outUrl;
							urlArr.push(res.datas[i].outUrl);
						}
						this.$prompt.none(res.msg);
						setTimeout(()=> {
							if (type == 1) {
								//跳去预览
								uni.navigateTo({
									url: "/pages/view/preview/preview?previews=" + urlArr.join(',')
								})
							}else if(type == 2){
								getApp().globalData.diary = res.datas[0];
								uni.navigateTo({
									url:"/pages/dataReport/dailyReport?urlName="+"patrol"+"&isZJ="+"0"
								})
							} else {
								uni.navigateBack({
									delta: 1
								})
							}
						}, 500)
					} else {
						this.$prompt.Error("保存失败,"+res.msg);
					}
				})
			},
			
			radioChange(event,type){
				//console.log(event.target.value,type);
				this.data[type] = event.target.value;
			},
			
			//跳转选择工序
			toSelectProcess(index){
				this.curIndex = index;
				uni.navigateTo({
					url:"/pages/constructionLog2/selectProcess/selectProcess"
				})
			},
			//选择工序
			selectProcess(process){
				//console.log(process);
				//console.log(this.dateList[this.curIndex]);
				this.dateList[this.curIndex].processList.push(process);
			},
			//移除工序
			deleProcess(index,curIndex){
				this.dateList[curIndex].processList.splice(index,1);
			},
			
			verification(){
				let verify = true;
				for (let i = 0; i < this.dateList.length; i++) {
					if(!this.dateList[i].serialNumber && !this.dateList[i].jobContent &&
						!(this.dateList[i].processList && this.dateList[i].processList.length > 0) &&
						!this.dateList[i].patrolContent && !this.dateList[i].acceptance &&
						!this.dateList[i].problem
					){
						verify = false;
					}else{
						verify = true;
					}
				}
				return verify;
			},
			addOne(){
				this.dateList.push({
					date:this.dateList[0].date,//日期
					weather:this.dateList[0].weather,//天气
					pageNumber:this.dateList[this.dateList.length-1].pageNumber+1,
					processList:[],
					recorderId:this.dateList[0].recorderId,
					contractId:this.dateList[0].contractId,
					constructi2onList : this.getNewOption(this.constructi2onList),
					contractIdDataList : this.getNewOption(this.contractIdDataList)
				})
			},
			addNow(index){
				let addObj = Object.assign({},this.dateList[index]);
				addObj.pageNumber = addObj.pageNumber+1;
				addObj.processList = [].concat(addObj.processList);
				addObj.constructi2onList = this.getNewOption(addObj.constructi2onList);
				addObj.contractIdDataList = this.getNewOption(addObj.contractIdDataList);
				addObj.id = '';
				for (let i = index+1; i < this.dateList.length; i++) {
					this.dateList[i].pageNumber += 1;
				}
				this.dateList.splice(index+1,0,addObj);
				//console.log(this.dateList)
			},
			delOne(index){
				uni.showModal({
				    title: '删除',
				    content: '是否删除 日志'+(index+1)+' ?'+'删除后无法还原',
				    success:(res) => {
				        if (res.confirm) {
				            //console.log('用户点击确定');
							
							//没保存过直接删
							if(!this.dateList[index].id){
								this.dateList.splice(index,1);
								return;
							}
							//保存过的需要请求
							this.http.request('/app/patrol/del', {
								id: this.dateList[index].id,
							}).then((result) => {
								if(result.result ==1){
									this.dateList.splice(index,1);
								}else{
									this.$prompt.Error("删除失败");
								}
							})
				        } else if (res.cancel) {
				            //console.log('用户点击取消');
				        }
				    }
				});		
			},
			getDataByDate(date){
				this.http.request('/app/patrol/getDataByDate', {
					date: date,
					recorderId:this.recorderId,
					contractId:this.contractId,
				}).then((result) => {
					if(result.result ==1){
						if(result.datas){
							for (let i = 0; i < result.datas.length; i++) {
								result.datas[i].contractId = this.contractId;
								result.datas[i].processList = result.datas[i].proList;
								result.datas[i].constructi2onList = this.getNewOption(this.constructi2onList);
								result.datas[i].contractIdDataList = this.getNewOption(this.contractIdDataList);
								var items,values;
								if(result.datas[i].constructionUnits){
									items= result.datas[i].constructi2onList;
									values = result.datas[i].constructionUnits.split(",");
									this.setChecked(items,values)
								}
								if(result.datas[i].contractIds){
									values = result.datas[i].contractIds.split(",");
									items= result.datas[i].contractIdDataList;
									this.setChecked(items,values)
								}
							}
							this.dateList =result.datas;
							
							// var items,values;
							// if(this.dateList[0].constructionUnits){
							// 	items= this.constructi2onList;
							// 	values = this.dateList[0].constructionUnits.split(",");
							// 	this.setChecked(items,values)
							// }
							// if(this.dateList[0].contractIds){
							// 	values = this.dateList[0].contractIds.split(",");
							// 	items= this.contractIdDataList;
							// 	this.setChecked(items,values)
							// }
						}else{
							this.$prompt.Error(result.msg);
						}
						
					}else{
						this.$prompt.Error(result.msg);
					}
				})
			},
			getPageNumber(){
				let max = 1;
				for (let i = 0; i < this.dateList.length; i++) {
					if(this.dateList[i].pageNumber > max){
						max = this.dateList[i].pageNumber;
					}
				}
				return max+1;
			},
			
			async getcontractInfoListByContract(){
				let result = await this.http.request('/app/parameterLog/getcontractInfoListByContract',{
						contractId:this.contractId,
					})
				if(result.result == '1'){
					this.constructi2onList = [];
					this.contractIdDataList = [];
					for (var i = 0; i < result.datas.length; i++) {
						this.constructi2onList.push({
							id:result.datas[i].id,
							contractorUnitName:result.datas[i].contractorUnitName,
							checked:false,
						})
						this.contractIdDataList.push({
							id:result.datas[i].id,
							contractNumber:result.datas[i].contractNumber,
							checked:false,
						})
					}
				}else{
					
				}
			},
			
			checkboxChange(e,index,type){
				//console.log(e.detail.value)
				let items = []
				if(type == 1){
					items = this.dateList[index].constructi2onList
				}else if(type == 2){
					items = this.dateList[index].contractIdDataList
				}
				
				let values = e.detail.value
				
				this.setChecked(items,values)
			},
			
			setChecked(items,values){
				for (let i = 0, lenI = items.length; i < lenI; ++i) {
				  items[i].checked = false
							
				  for (let j = 0, lenJ = values.length; j < lenJ; ++j) {
					if (items[i].id === values[j]) {
						//console.log(values[j])
					  items[i].checked = true
					  break
					}
				  }
				}
			},
			getNewOption(list){
				var newList = [];
				for (var i = 0; i < list.length; i++) {
					newList.push(Object.assign({},list[i]));
				}
				return newList;
			},
			
			repeal(){
				let { account } = uni.getStorageSync('userInfo')
				uni.showModal({
					title: '废除',
					content: '是否废除任务?',
					success:(res) => {
						if (res.confirm) {
							this.http.request('/app/task/repeal', {
								taskId: this.dateList[0].taskId,
								opUserName: account ? account : '',
							}).then((result) => {
								if(result.result ==1){
									this.$prompt.none("废除成功");
									this.getDataByDate(this.dateList[0].date);
								}else{
									this.$prompt.Error("废除失败");
								}
							})
						} else if (res.cancel) {
							//console.log('用户点击取消');
						}
					}
				});	
			},
			reportSuccess(){
				//上报成功，刷新
				this.getDataByDate(this.dateList[0].date);
			}
		},
		onShow() {
			/* 监听选择施工人员页面的handleFun方法 */
			// uni.$on("handleFun", res => {
			// this.data.constructionWorker="";
			// this.constructionList=res;
			// res.forEach((item)=>{
			//  this.data.constructionWorker+=item.user_name
			// })
			// })
			/* 监听选择监理人员页面的handleFun方法 */
			// uni.$on("handleFunBy", res => {
			//    this.data.supervisionWorker="";
			//    this.supervisionList=res;
			//    res.forEach((item)=>{
			// 	   this.data.supervisionWorker+=item.user_name
			//    })
			// })
		},
	}
</script>

<style>
	.solid-top-type {
		border-top: 0px solid #eee;
	}

	.cu-form-group_1 {
		display: flex;
		align-items: center;
		padding: 0 22rpx;
		background-color: #fff;
		border-bottom: 2rpx solid #EAEAEA;
		height: 88rpx;
	}

	.cu-form-group_1 .title {
		font-size: 30rpx;
		color: #101010;
		width: 154rpx;
	}

	.cu-form-group_1 input {
		font-size: 30rpx;
		color: #8a8a8a;
	}

	.cu-form-group_2 {
		padding: 22rpx;
		background-color: #fff;
		border-bottom: 2rpx solid #EAEAEA;
	}

	.cu-form-group_2 .title {
		font-size: 30rpx;
		color: #101010;
		padding-bottom: 18rpx;
	}

	.cu-form-group_2 textarea {
		font-size: 30rpx;
		color: #8a8a8a;
		width: 100%;
	}

	.cu-modal.show {
		overflow-y: auto;
		pointer-events: auto;
	}
</style>
