/**
 * author: dabao
 */
var VUE = null
window.addEventListener("load", function() {
	VUE = new Vue({
		el: '#app',
		data() {
			return {
				minDate: new Date(2024, 6, 29),
				previewUrl: BASE_URL,
				form: {
					id: "",
					planName: "",
					// 验收人
					publishDate: "",
					// 隐患描述
					publishDeptName: "",
					publishDesc: "",
					completionDate: "",
					issueDescription: "",
					processDescription: "",
				},
				filePathList: [],
				// 整改日期模态框
				completionDate: '',
				showPopup4completionDate: false,
				// companyId: localStorage.getItem('companyId'),
				// disabled: false,
				fileList: [],
				
			}
		},
		mounted() {
			this.detail()
		},
		computed:{
			showImage(){
				return this.filePathList[0]
			},
			showWrapper(){
				return this.filePathList[0]
			},
			disabled(){
				return this.form.completionStatus === 1
			}
			
		},
		methods: {
			submit() {
				if (!this.form.completionDate) {
					vant.Dialog.alert({
						message: '请输入演练完成日期',
					})
					return;
				}
				if (!this.form.issueDescription) {
					vant.Dialog.alert({
						message: '请输入发现问题',
					})
					return;
				}
				if (!this.form.processDescription) {
					vant.Dialog.alert({
						message: '请输入过程描述',
					})
					return;
				}
				
				vant.Toast.loading({
					message: '正在处理...',
					forbidClick: true,
					loadingType: 'spinner',
				});
				http2.post({
					serviceId: API_KEY_MAP["emergency-add"]['id'],
					interfacePublicKey: API_KEY_MAP["emergency-add"]["publicKey"],
					interfacePrivateKey: API_KEY_MAP["emergency-add"]["privateKey"],
					reqParams: {
						drillPhotoList: this.filePathList,
						id: gemhoUtil.getParameter('planId'),
						processDescription: this.form.processDescription,
						issueDescription: this.form.issueDescription,
						completionDate: this.form.completionDate
					},
				}, (res) => {
						
					if(res){
						console.log('添加结果', res)
						vant.Toast({
							message: '操作成功',
						})
						// if (!this.form.id) { // 添加时则
						// 	location.reload()
						// }
						// history.back()
						gemhoUtil.navigatePage('./emergency.html', '操作完成,跳转中...')
					}else{
						this.submit()
					}
				})
			},
			// beforeUpload(file) {
			// 	console.log('beforeUpload',file)
			// 	// 在文件上传之前的处理逻辑，例如校验文件大小、文件类型等
			// 	return true; // 返回 true 继续上传，返回 false 中止上传
			// },
			beforeRead(file) {
			  if(!['image/png','image/jpeg','image/jpg'].includes(file.type)){
				  vant.Dialog.alert({
				  	title: '信息提示',
				  	message: '文件格式不正确'
				  })
				return;
			  }
			  if (file.size > (10*1024*1024)) {
				vant.Dialog.alert({
					title: '信息提示',
					message: '文件大小不可超过10M'
				})
				return false;
			  }
			  return true;
			},
			// afterRead(file) {
			// 	// 获取文件流，调用网关中台接口，获取文件全路径url
			// 	console.log('afterRead',file)
			
			// 	vant.Toast.loading({
			// 		message: '正在处理...',
			// 		forbidClick: true,
			// 		loadingType: 'spinner',
			// 	});
			// 	http2.post({
			// 		serviceId: API_KEY_MAP["upload"]['id'],
			// 		interfacePublicKey: API_KEY_MAP["upload"]["publicKey"],
			// 		interfacePrivateKey: API_KEY_MAP["upload"]["privateKey"],
			// 		reqParams: {
			// 			modelName: 'emergencydrill',
			// 		},
			// 		fileList: [{
			// 			fileName: 'file',
			// 			file: file.file
			// 		}]
			// 	}, (res) => {
			// 		// gemhoUtil.setCookie('uploading', 'N')
			// 		if(res){
			// 			console.log('接口回调数据', JSON.parse(res))
			// 			var result = JSON.parse(res)
			// 			if(result.body && result.body.indexOf('emergencydrill') > -1){
			// 				this.filePathList = [result.body]
			// 			}else{
			// 				this.filePathList = []
			// 			}
			// 			vant.Toast.clear()
			// 		}
			// 	})
			// },
		afterRead(file) { // 调用爱山东中台系统，将数据流传递过去
			vant.Toast.loading({
				message: '正在处理...',
				forbidClick: true,
				loadingType: 'spinner',
			});
			// 文件读取完成后的处理逻辑
			const formData = new FormData();
			formData.append('file', file.file); // 通过FormData构建要上传的文件数据
			formData.append('biz_content',SM.encrypt('emergencydrill', API_KEY_MAP["upload"]["publicKey"]));
		
			// 发送HTTP POST请求
			fetch(BASE_URL + '/api/common/upload', {
				method: 'POST',
				body: formData
			})
			.then(response => {
				if (response.ok) {
					return response.json();
				}
				throw new Error('Network response was not ok.');
			})
			.then(value => {
				console.log(value); // 处理后端返回的数据
				if(value){ // 返回信息不为空，则进行解密操作
					let sm2_encrypt_result = value // 后台返回待解密内容
					let sm2_decrypt_result = sm2_Decrypt(sm2_encrypt_result, API_KEY_MAP["upload"]["privateKey"],)
					if(!sm2_decrypt_result){ // 如果解密后的值为空字符串则重新上传图片
						vant.Toast.clear()
						setTimeout(() => {
							this.afterRead(file)
						}, 0);
						return
					}
					console.log('upload响应解密', sm2_decrypt_result)
					const decryptRes = JSON.parse(sm2_decrypt_result)
					if(decryptRes.code === 400 || decryptRes.code === 401 || decryptRes.status === 401){
						vant.Dialog.alert({
							title: '信息提示',
							message: decryptRes.msg,
						})
						return
					}
					this.filePathList = decryptRes.body ? [decryptRes.body] : []
					setTimeout(() => {
						vant.Toast.clear()
					}, 0);
				}
			})
			.catch(error => {
				// console.error('There has been a problem with your fetch operation:', error);
			});
		},
			showPopup(popupType) {
				if (!this.disabled) {
					this[popupType] = true
				}
			},
			confirm4completionDate(value) {
				console.log('value', value)
				this.form.completionDate = gemhoUtil.formatDate(new Date(value))
				this.showPopup4completionDate = false
			
			},
			detail(){
				vant.Toast.loading({
					message: '加载中...',
					forbidClick: true,
					loadingType: 'spinner',
				});
				
				http2.post({
					serviceId: API_KEY_MAP["emergency-detail"]['id'],
					interfacePublicKey: API_KEY_MAP["emergency-detail"]["publicKey"],
					interfacePrivateKey: API_KEY_MAP["emergency-detail"]["privateKey"],
					reqParams: {
						planId: gemhoUtil.getParameter('planId'),
					}
				}, (res) => {
					if(!res){ // 中台返回为undefined 重新请求
						vant.Toast.clear()
						setTimeout(() => {
							this.detail()
						}, 0);
						return
					}	
					if(res){
						console.log('接口回调数据', JSON.parse(res))
						
						var result = JSON.parse(res)
						this.loading = false; // 加载状态结束
						
						// console.log('响应结果', result.content)
						this.form = result.body.content[0]
						
						if(this.form.completionStatus===1){
							this.disabled = true
						}else{
							this.disabled = false
						}
						this.filePathList = this.form.drillPhotoList || [];
						setTimeout(() => {
							this.$nextTick(()=>{
								vant.Toast.clear()
							})
						}, 0);
					}
				})
			},
		},
	});
});