/**
 * author: dabao
 */
var VUE = null
window.addEventListener("load", function() {
	VUE = new Vue({
		el: '#app',
		data() {
			return {
				uploading: false,
				previewUrl: BASE_URL,
				form: {
					id: '',
					companyId: '',
					name: "",
					startTime: "",
					endTime: "",
					workTime: '',
					workNumber: '',
					mainPlace: '',
					reportPer: '',
					perTel: '',
					remark: '',
					uploadDate: "",
				},
				filePathList: [], // 'dangerjob/e40eda16-7a86-4a2a-976b-892e17eeed49.pdf'
				// 企业id
				companyId: localStorage.getItem('companyId'),
				disabled: false,
				pageType: '',
				// 检查日期的模态框
				hdInspectDateModel1: '', // 时间的临时model值
				showPopup4hdInspectDate1: false,
				// 检查日期的模态框
				hdInspectDateModel2: '', // 时间的临时model值
				showPopup4hdInspectDate2: false,

				// 整改日期模态框
				hdRectificationDateModel: '',
				showPopup4hdRectificationDate: false,

				fileList: [],
			}
		},
		mounted() {
			// if(gemhoUtil.getCookie('uploading')=== 'Y'){
			// 	vant.Dialog.alert({
			// 		title: '信息提示',
			// 		message: '网络错误，请重新上传图片'
			// 	})
			// 	return
			// }
			if (gemhoUtil.getParameter('type') === 'detail') {
				this.disabled = true
				this.pageType = 'detail'
				this.detail()
			} else if (gemhoUtil.getParameter('type') === 'edit') {
				this.disabled = false
				this.pageType = 'edit'
				this.detail()
			} else if (gemhoUtil.getParameter('type') === 'add') { // 新增
				this.disabled = true
				this.pageType = 'add'
				this.resetData()
			}
		},
		computed: {
			showImage() {
				return this.filePathList[0] && (this.filePathList[0].indexOf('.png') > -1 || 
				this.filePathList[0].indexOf('.jpg') > -1 ||
				 this.filePathList[0].indexOf('.jpeg') >-1)
			},
			showPdf() {
				return this.filePathList[0] && (this.filePathList[0].indexOf('.pdf') > -1)
			},
			showWrapper() {
				return this.filePathList[0]
			}
		},
		methods: {
			previewFile() {
				// var src = 'dangerjob/e40eda16-7a86-4a2a-976b-892e17eeed49.pdf'
				// location.href = './pdfViewer.html?pdfSrc='+ src
				console.log(this.previewUrl + '/' + this.filePathList[0])
				location.href = this.previewUrl + '/' + this.filePathList[0]
			},
			beforeRead(file) {
				if(!['image/png','image/jpeg','image/jpg', 'application/pdf'].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) { // 调用爱山东中台系统，将数据流传递过去
				vant.Toast.loading({
					message: '正在处理...',
					forbidClick: true,
					loadingType: 'spinner',
				});
				// 文件读取完成后的处理逻辑
				const formData = new FormData();
				formData.append('file', file.file); // 通过FormData构建要上传的文件数据
				formData.append('biz_content',SM.encrypt('dangerjob', 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()
							this.afterRead(file)
							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);
					}else{
						this.afterRead(file)
					}
				})
				.catch(error => {
					// console.error('There has been a problem with your fetch operation:', error);
				});
			},
			// 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: 'dangerjob',
			// 		},
			// 		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('dangerjob') > -1) {
			// 				this.filePathList = [result.body]
			// 			} else {
			// 				this.filePathList = []
			// 			}
			// 			vant.Toast.clear()
			// 		}
			// 	})
			// },
			resetData() {
				// 使用 Object.assign 来重写 this.$data，以达到重置 data 的目的
				Object.assign(this.$data, this.$options.data.call(this));
			},
			showPopup(popupType) {
				if (!this.disabled) {
					this[popupType] = true
				}
			},
			detail() {
				vant.Toast.loading({
					message: '正在加载...',
					forbidClick: true,
					loadingType: 'spinner',
				});
				http2.post({
					serviceId: API_KEY_MAP["dw-list"]['id'],
					interfacePublicKey: API_KEY_MAP["dw-list"]["publicKey"],
					interfacePrivateKey: API_KEY_MAP["dw-list"]["privateKey"],
					reqParams: {
						id: gemhoUtil.getParameter('dwId'),
					}
				}, (res) => {
					if(!res){ // 中台返回为undefined 重新请求
						vant.Toast.clear()
						setTimeout(() => {
							this.detail()
						}, 0);
						return
					}	
					if (res) {
						console.log('接口回调数据', JSON.parse(res))
						setTimeout(() => {
							this.$nextTick(()=>{
								vant.Toast.clear()
							})
						}, 0);
						var result = JSON.parse(res)
						// this.noticeContent = result.noticeContent
						this.form = result.content[0]
						this.filePathList = result.content[0].filePathList || []
						if (this.form.workTime && this.form.workTime.length) {
							this.form.startTime = this.form.workTime[0]
							this.form.endTime = this.form.workTime[1]
						}
					}
				})
			},
			submit() {
				if (!this.form.name) {
					vant.Dialog.alert({
						message: '请输入危险作业备案名称',
					})
					return;
				}
				if (!this.form.startTime || !this.form.endTime) {
					vant.Dialog.alert({
						message: '请选择作业时间',
					})
					return;
				}
				if (+new Date(this.form.startTime) > +new Date(this.form.endTime)) {
					vant.Dialog.alert({
						message: '起始时间不能大于结束时间',
					})
					return;
				}
				// this.form.companyId = this.companyId
				this.form.workTime = [this.form.startTime, this.form.endTime]
				this.form.filePathList = this.filePathList
				vant.Toast.loading({
					message: '正在处理...',
					forbidClick: true,
					loadingType: 'spinner',
				});
				http2.post({
					serviceId: API_KEY_MAP["dw-list-detail"]['id'],
					interfacePublicKey: API_KEY_MAP["dw-list-detail"]["publicKey"],
					interfacePrivateKey: API_KEY_MAP["dw-list-detail"]["privateKey"],
					reqParams: this.form
				}, (res, type) => {
					if(!res && !type){ // 如果是中台接口返回为undefined，则重新发起请求
						vant.Toast.clear()
						setTimeout(() => {
							this.submit()
						}, 0);
						
						return
					}
					if (res) {
						console.log('添加结果', res)
						vant.Toast({
							message: '操作成功',
						})
						history.back()
					}
				})
			},
			confirm4hdInspectDate1(value) {
				console.log('value', value)
				this.form.startTime = gemhoUtil.formatDate(new Date(value))
				this.showPopup4hdInspectDate1 = false

			},
			confirm4hdInspectDate2(value) {
				console.log('value', value)
				this.form.endTime = gemhoUtil.formatDate(new Date(value))
				this.showPopup4hdInspectDate2 = false

			},
			confirm4hdRectificationDate(value) {
				console.log('value', value)
				this.form.uploadDate = gemhoUtil.formatDate(new Date(value))
				this.showPopup4hdRectificationDate = false

			},
		},
	});
});