/**
 * author: dabao
 * date: 2024-03-15
 * description: 商户首页
 */
var VUE = null
window.addEventListener("load", function() {
	VUE = new Vue({
		el: '#app',
		data() {
			return {
				previewUrl: BASE_URL,
				userType: gemhoUtil.getCookie('userType'),
				flag: 'XQ',
				flag: 'ADD',
				showDatePicker: false, // 控制日期选择器显示
				minDate: new Date(gemhoUtil.getTargetDateYMD()), // 最小可选日期
				maxDate: new Date(2099, 11, 31), // 最大可选日期
				tabList4lv2: [],
				// 日期选择的最小范围，这里设置为当前日期的前 10 年
				// maxDate: new Date(new Date().getFullYear() + 10, 11),
				// 新增以下数据
				formData: {
					images: [],
					exerciseDate: gemhoUtil.getTargetDateYMD(),
				},
				id: ''
			}
		},
		created() {

		},
		mounted() {
			this.id = gemhoUtil.getParameter('id')
			if (this.id) { // 详情
				this.flag = 'XQ'
				this.detail() // 获取商户信息
			} else {
				this.flag = 'ADD'
			}
		},
		methods: {
			// 处理平面图删除
			handleDeleteFloorPlan(index, type) {
				this.formData.images.splice(index, 1);
			},
			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, type) { // 调用爱山东中台系统，将数据流传递过去
				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 + '/common/upload', {
						method: 'POST',
						body: formData,
						headers: {
							'Authorization': gemhoUtil.getCookie('token'),
						}
					})
					.then(response => {
						if (response.ok) {
							return response.json();
						}
						throw new Error('Network response was not ok.');
					})
					.then(value => {
						console.log(value, 'value图片上********'); // 处理后端返回的数据
						if (value) { // 返回信息不为空，则进行解密操作
							this.formData.images.push(value.fileName)
							// 可根据后端返回的数据做进一步处理，如显示上传成功信息等
							setTimeout(() => {
								vant.Toast.clear()
							}, 0);
						} else {
							this.afterRead(file)
						}
					})
					.catch(error => {
						// console.error('There has been a problem with your fetch operation:', error);
					});
			},
			paizhao() {
				var data = ["相册", "相机"];
				var maxSelectNum = 6;
				// var maxSelectNum = 1;
				lightAppJssdk.notification.showMediaAlert({
					arg0: data,
					success: function(data) {
						console.log('选择菜单的数据', data)
						// formData.append('file', file.file); // 通过FormData构建要上传的文件数据
						// alert(data);
						var pam1 = {
							"url": BASE_URL + '/common/uploads',
							// url:'sdfsdfsd',
							"fileKey": "files",
							// "fileKey": "files",
							"params": {
							},
							"header": {
								'Authorization': gemhoUtil.getCookie('token'),
							},
							"chooseType": "chooseFileUpload",
							"transmissionType": 0, //1-base64 0-图片地址"maxSize": 10, "maxSelectNum": 9,
							"maxSize": 10,
							"maxSelectNum": maxSelectNum,
						}
						if (data.index == 0) {
							pam1.chooseType = "chooseImageUpload" // pam1.fileKey = "file"
						} else if (data.index == 1) {
							pam1.chooseType ="takingPicturesUpload" // pam1.fileKey = "picfile"
						}
						
						
						console.log('请求接口i偶路径', pam1)
						
						chooseFileUploadTest(pam1)
						// setTimeout('onHidePreloaders()', 2000);
					},
					fail: function(data) {
						console.log(data);
					}
				});
			
				function chooseFileUploadTest(pam) {
					lightAppJssdk.uploadFile.chooseFileUpload({
						arg0: pam,
						success: function(value) {
							console.log('chooseFileUpload方法', value)
							if(value){
								// VUE.formData.images.push(...JSON.parse(value).fileNames)
								if(gemhoUtil.isIOSStrict() || gemhoUtil.isHarmonyOS()){ // ios直接返回对象
									VUE.formData.images.push(...value.fileNames)
								}else{ // 俺安卓机 返回字符串
									VUE.formData.images.push(...JSON.parse(value).fileNames)
								}
								if(VUE.formData.images.length > maxSelectNum){
									const result = VUE.formData.images.slice(0, maxSelectNum)
									VUE.formData.images = result
								}
							}
						},
						fail: function(data1) {
							console.log(data1);
						}
					});
				};
			},
			showDatePickerModal() {
				if (this.flag == 'XQ') {
					return
				}
				this.showDatePicker = true
			},
			showImage(list, index) {
				const images = list.map((item) => {
					return this.previewUrl + item
				})
				console.log(images, 'images')
				vant.ImagePreview({
					images,
					startPosition: index,
					closeable: true,
				});
			},
			gotoPage(stringifyUrl) {
				let url = gemhoUtil.setParameter(`src/_${stringifyUrl}.html`)
				gemhoUtil.navigatePage(url, '跳转中...')
			},
			// 确认日期选择
			onDateConfirm(date) {
				// 将 Date 对象格式化为 YYYY-MM-DD 字符串
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				this.formData.exerciseDate = `${year}-${month}-${day}`;
				this.showDatePicker = false;
			},

			// 文件上传处理
			handleFileUpload(file) {
				console.log('上传文件:', file);
				// 此处可添加实际文件上传逻辑
			},

			submitForm() {
				if (!gemhoUtil.validateRequire(this.formData.title)) {
					vant.Dialog.alert({
						message: '演练标题不可为空',
					})
					return;
				}
				
				if (!gemhoUtil.validateRequire(this.formData.participantsNum)) {
					vant.Dialog.alert({
						message: '演练人数不可为空',
					})
					return;
				}
				
				if (!gemhoUtil.validateNumber999(this.formData.participantsNum)) {
					vant.Dialog.alert({
						message: '演练人数格式不正确，请输入大于0且小于999的数字',
					})
					return;
				}
				
				if (!gemhoUtil.validateRequire(this.formData.responsiblePerson)) {
					vant.Dialog.alert({
						message: '负责人不可为空',
					})
					return;
				}
				
				if (!gemhoUtil.validateChineseName(this.formData.responsiblePerson)) {
					vant.Dialog.alert({
						message: '负责人格式不正确，请输入中文',
					})
					return;
				}
				
				if (this.formData.responsiblePerson.length < 2) {
					vant.Dialog.alert({
						message: '负责人格式不正确，请输入2个或更多字符的名称',
					})
					return;
				}
				
				
				if (!this.formData.images.length) {
					vant.Dialog.alert({
						message: '图片不可为空',
					})
					return;
				}
				vant.Toast.loading({
					message: '正在处理...',
					forbidClick: true,
					loadingType: 'spinner',
				});
				var reqParam = {
					merId: gemhoUtil.getParameter('merId'),
					exerciseType: '2', // 应急演练
					...this.formData,
				}
				reqParam.images = this.formData.images.join(',')

				http3.post('/gaoqu/exercise', reqParam).then((res) => {
					console.log('添加结果', res)
					if(res.code === 200){
						vant.Toast({
							message: '操作成功',
						})
						setTimeout(function(){
							history.back()
						}, 300)
						
					}else{
						vant.Toast({
							message: '操作失败',
						})
					}
					
					// location.reload()
				})
			},
			//获取商户信息
			detail() {
				vant.Toast.loading({
					message: '正在加载...',
					forbidClick: true,
					loadingType: 'spinner',
				})
				setTimeout(() => {
					http2.post({
							serviceId: API_KEY_MAP['no-page']['id'],
							interfacePublicKey: API_KEY_MAP['no-page']['publicKey'],
							interfacePrivateKey: API_KEY_MAP['no-page']['privateKey'],
							reqParams: {
								sign: 31,
								exerciseId: this.id,
								sort: 'lawId,desc',
							},
						},
						(res) => {
							console.log('res', JSON.parse(res))
							if (!res) {
								// 中台返回为undefined 重新请求
								vant.Toast.clear()
								setTimeout(() => {
									// this.getList()
								}, 0)
								return
							}
							if (res) {
								var result = JSON.parse(res)
								// 图片数据结构处理
								let tempData = result.data
								if (tempData['images']) {
									tempData['images'] = tempData['images'] ? tempData[
										'images'].split(',') : []
								}

								this.formData = tempData
							}
						}
					)
				}, 0)
			},
		}
	});

})