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

				},
			}
		},
		created() {
			let params = gemhoUtil.getUrlParams()
			console.log(params);
			this.merId = params.merId
		},
		mounted() {
			this.getShopInfo() // 获取商户信息
		},
		// watch: {
		// 	'formData.date': {
		// 		handler(newVal) {
		// 			console.log('date 属性变化:', newVal);
		// 		},
		// 		deep: true // 深度监听对象属性
		// 	}
		// },
		methods: {
			showImage4shusan(liststr, index) {
				const list = liststr.split(',') || []
				const images = list.map((item)=>{
					return this.previewUrl + item
				})
				console.log(images, 'images')
				vant.ImagePreview({
					images,
					startPosition: index,
					closeable: true,
				});
			},
			picDetail(){ // 平面疏散图显示
				if(!this.merInformation.floorEvacuationPlan){
					vant.Dialog.alert({
						message: '该商家还未上传平面疏散图',
					})
					return
				}
			
				this.showImage4shusan(this.merInformation.floorEvacuationPlan, 0)
			},
			showImage(list, index) {
				const images = list.map((item) => {
					return this.previewUrl + item
				})
			
				vant.ImagePreview({
					images,
					startPosition: index,
					closeable: true,
				});
			},
			// 处理平面图删除
			handleDeleteFloorPlan(index, type) {
				this.formData.photos.splice(index, 1);
			},
			paizhao() {
				var data = ["相册", "相机"];
				var maxSelectNum = 4;
				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(value, 'chooseFileUploadTest图片上传回调')
							if(value){
								if(gemhoUtil.isIOSStrict() || gemhoUtil.isHarmonyOS()){ // ios直接返回对象
									VUE.formData.photos.push(...value.fileNames)
								}else{ // 俺安卓机 返回字符串
									VUE.formData.photos.push(...JSON.parse(value).fileNames)
								}
								
								if(VUE.formData.photos.length > maxSelectNum){
									const result = VUE.formData.photos.slice(0, maxSelectNum)
									VUE.formData.photos = result
								}
							}
						},
						fail: function(data1) {
							console.log(data1);
						}
					});
				};
			},
			openDebug() { // 双击开启debugg模式，再次双击则关闭
				console.log('开启关闭debug')
				if (localStorage.getItem('debug') == 'Y') {
					localStorage.setItem('debug', 'N')
				} else {
					localStorage.setItem('debug', 'Y')
				}
			},
			gotoPage(stringifyUrl) {
				let url = gemhoUtil.setParameter(`_${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.date = `${year}-${month}-${day}`;
			// 	this.showDatePicker = false;
			// },
			// dateChange(e) {
			// 	console.log('date 属性变化22222:', e);
			// },
			// 文件上传处理
			handleFileUpload(file) {
				console.log('上传文件:', file);
				// 此处可添加实际文件上传逻辑
			},

			navTo(url) {
				// gemhoUtil.nav2asd(url)
				let params = gemhoUtil.getUrlParams()
				if (url == 'check_info') {
					params = {
						...params,
						flag: 'ADD',
						pageName: '_shanghu_home'
					}
				}
				let strurl = gemhoUtil.setParameter(`_${url}.html`, params)
				gemhoUtil.navigatePage(strurl, '跳转中...')
			},
			submitForm() {
				if (!gemhoUtil.validateRequire(this.formData.content)) {
					vant.Dialog.alert({
						message: '安全建议不可为空',
					})
					return;
				}
				
				if (!this.formData.photos.length) {
					vant.Dialog.alert({
						message: '图片不可为空',
					})
					return;
				}
				
				if (this.formData.contactName && this.formData.contactName.length <2) {
					vant.Dialog.alert({
						message: '联系人格式不正确，请输入2个或更多字符的名称',
					})
					return;
				}
				
				if (this.formData.contactName && !gemhoUtil.validateChineseName(this.formData.contactName)) {
					vant.Dialog.alert({
						message: '联系人格式不正确，请输入中文',
					})
					return;
				}
				
				if (this.formData.contactDetails && !/^1[3-9]\d{9}$/.test(this.formData.contactDetails)) {
					vant.Dialog.alert({
						message: '联系方式格式不正确，请输入11位数字的手机号码',
					})
					return;
				}
				
			
				
			
				
				vant.Toast.loading({
					message: '正在处理...',
					forbidClick: true,
					loadingType: 'spinner',
				});
				var reqParam = {
					merId: this.merId,
					...this.formData,
				}
				// var url = "/gq/checkRecord/safeCheckRecord"

				http3.post('/gq/consumer', reqParam).then((res) => {
					console.log('添加结果', res)
					if(res.code === 200){
						vant.Toast({
							message: '提交成功，感谢您的参与！',
						})
						
						// this.formData.content = ''
						// this.formData.photos = []
						// this.formData.contactName = ''
						// this.formData.contactDetails = ''
						// history.back()
						setTimeout(() => {
							// location.reload()
							lightAppJssdk.navigation.close({
							  success: function (data) {
							    //成功回调
							    console.log('关闭页面')
							  },
							  fail: function (data) {
							    console.log('关闭失败')
							  },
							})
						}, 800);
					}else{
						vant.Toast({
							message: '提交失败',
						})
					}
					
					
					
				})
			},
			//获取商户信息
			getShopInfo() {
				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: 11,
								pageNum: this.page++, // 每次请求增加下一页
								pageSize: this.size,
								merId: this.merId,
								sort: 'lawId,desc',
							},
						},
						(res) => {
							if (!res) {
								// 中台返回为undefined 重新请求
								vant.Toast.clear()
								this.page = this.page - 1 // 重新请求后，分页数恢复上一次请求的值
								setTimeout(() => {
									// this.getList()
								}, 0)
								return
							}
							if (res) {
								var result = JSON.parse(res)
								console.log('消费者', result)
								this.merInformation = { ...this.merInformation, ...result.data }
								// this.merInformation.safeLevel = 1
							}
						}
					)
				}, 0)
			},
		}
	});

})