<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" v-if="!(data.taskStatus==0 || data.taskStatus==1)" @click="addNow(index)">复制当前</button>
					</view>
					<button class="cu-btn round sm" @click="delOne(index)" v-if="!(data.taskStatus==0 || data.taskStatus==1)&&(index != 0)">删除</button>
				</view>
				<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="请输入" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" v-model="data.weather" name="input"></input>
				</view>
				<view class="cu-form-group_1">
					<view class="title">编号</view>
					<input placeholder-style="color:#AEAEAE" placeholder="请输入" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" v-model="data.serialNumber" name="input"></input>
				</view>
				<view class="cu-form-group_1">
					<view class="title">审核人</view>
					<input placeholder-style="color:#AEAEAE" placeholder="请输入" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" v-model="data.reviewer" name="input"></input>
				</view>
			</form>
			<form>
				<view class="cu-form-group_2">
					<view class="title">主要施工情况</view>
					<view>
						<textarea placeholder-style="color:#AEAEAE" maxlength="-1" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" v-model="data.jobContent" placeholder="请输入"></textarea>
					</view>
				</view>
				<view class="cu-form-group_2">
					<view class="title">监理主要作业</view>
					<view>
						<textarea placeholder-style="color:#AEAEAE" maxlength="-1" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" v-model="data.buildContent" placeholder="请输入"></textarea>
					</view>
				</view>
				<view class="cu-form-group_2">
					<view class="title">问题及处理情况</view>
					<view>
						<textarea placeholder-style="color:#AEAEAE" maxlength="-1" :disabled="(data.taskStatus==0)||(data.taskStatus==1)" v-model="data.problem" 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,
				}],
				
				updateOrInsert: 0, //0为新增 ， 1为编辑
				upId: null,
				
				contractId : uni.getStorageSync("porject"+"_"+uni.getStorageSync("userInfo").id).contractId,
				project:uni.getStorageSync("porject"+"_"+uni.getStorageSync("userInfo").id),
				recorderId:uni.getStorageSync("userInfo").id,
			}
		},
		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.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.getReviewer(e.time);
				
				uni.$on('report',this.reportSuccess)
			}
		
		},
		onUnload(){
			
			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/superEntity/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;
				//this.http.request('/app/superEntity/addEntity.json', JSON.stringify(this.dateList), 1).then((res) => {
				this.http.request('/app/superEntity/addEntity.json', {voStr:JSON.stringify(this.dateList),storeName:uni.getStorageSync("storeName")}).then((res) => {
					if (res.result == "1") {
						//this.data.id = res.data.id;
						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="+"superEntity"+"&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;
			},
			
			verification(){
				let verify = true;
				for (let i = 0; i < this.dateList.length; i++) {
					if(!this.dateList[i].serialNumber && !this.dateList[i].reviewer &&
						!this.dateList[i].jobContent && !this.dateList[i].buildContent &&
						!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,
					recorderId:this.dateList[0].recorderId,
					contractId:this.dateList[0].contractId
				})
			},
			addNow(index){
				let addObj = Object.assign({},this.dateList[index]);
				addObj.pageNumber = addObj.pageNumber+1;
				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/superEntity/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/superEntity/getDataByDate', {
					date: date,
					recorderId:this.recorderId,
					contractId:this.contractId,
				}).then((result) => {
					if(result.result ==1){
						for (let i = 0; i < result.datas.length; i++) {
							result.datas[i].contractId = this.contractId;
						}
						this.dateList =result.datas;
					}else{
						
					}
				})
			},
			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;
			},
			
			getReviewer(date){
				//获取上一个审核人
				this.http.request("/app/superEntity/getReviewer", {
					projectId:this.project.id,
					contractId:this.contractId,
					date:date
				}).then((res) => {
					if(res.data && this.dateList[0]){
						this.$set(this.dateList[0], 'reviewer', res.data);
					}
				})
			},
			
			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>
