var VUE = null
window.addEventListener('load', function () {

	// 在原有Vue实例中添加
	VUE = new Vue({
		el: '#app',
		data() {
			return {
				previewUrl: BASE_URL,
				loading: false,
				finished: false,
				page: 1,
				size: 9999,
				total: 0,
				
				activeTab: 0,
				flag: 'XQ',
				canvasReady: false,
				loadedImages: 0, // 记录已加载的图片数量
				userType: gemhoUtil.getCookie('userType'),
				formData: {
					id: '',
					unitName: '',
					businessAddress: '',
					smallPlaceTypeId: 0,
					useNature: '',
					unifiedSocialCreditCode: '',
					area: '',
					employeeCount: 0,
					owner: '',
					merchantPhone: '',
					qrCodeUrl: '',
					community: '',
					street: '',
					gridMemberName: '',
					gridMemberPhone: '',
					createBy: '',
					createTime: null,
					updateBy: '',
					updateTime: '',
					remark: '',
					deptId: '',
					merchantId: 0,
					smallPlaceType: '1',
					smallPlaceTypeName: '',
					principal: '',
					phone: '',
					area: '',
					businessHours: '',
					type: '', // 新增类型字段
					photos: [], // 新增图片数组字段
					floorPlanPhotos:[],
					businessLicensePhotos:[],
					storefrontPhotos:[],
					floorEvacuationPlan:[],
					
				},
				dict4changhsuoType: [],
				dict4fangwuType: [],
				dict4fangwuyongtuType: [],
				dict4businessType: [],
				dict4community: [],
				dict4industryType: [],
				consumerSuggestList: [],

				// 添加显示状态管理对象
				showOriginal: {
				merchantName: false,
				merchantPhone: false,
				businessAddress: false,
				owner: false,
				ownerPhone: false,
				operator: false,
				operatorPhone: false,
				landlordName: false,
				landlordContact: false
				}
			}
		},
		computed: {
		},
		mounted() {
			// 详情编辑权限控制
			const userType = gemhoUtil.getCookie('userType')
			if (userType == 'wgy' || userType == 'safety') {
				this.flag = 'XG'
			} else {
				// this.flag = 'XQ'
				this.flag = 'XG'
			}

			this.getDict4fangwuType()
			this.getDict4fangwuyongtuType()
			this.getDict4businessType()
			this.getDict4community()
			this.getDict4industryType()
			
			this.detail()

			// this.getDict4changhsuoType()
		},
		watch: {
			'formData.industryType': {
				handler(newVal) {
					// 选择后晴空下级下拉框值
					this.dict4changhsuoType = []
					
					this.getDict4changhsuoType({
						industryId: newVal
					})
				},
				deep: true // 深度监听对象属性
			}
		},
		methods: {
			paizhao(photosType, maxSelectNum) {
				VUE.photosType = photosType
				var data = ["相册", "相机"];
				lightAppJssdk.notification.showMediaAlert({
					arg0: data,
					success: function (data) {
						console.log('选择菜单的数据', data, photosType, maxSelectNum)
						// 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)
							var photosVar = []
							// 根据选择的图片不同进行区分设置
							if(VUE.photosType === 'floorPlan'){
								photosVar = VUE.formData.floorPlanPhotos
							}else if(VUE.photosType === 'businessLicensePhotos'){
								photosVar = VUE.formData.businessLicensePhotos
							}else if(VUE.photosType === 'storeFront'){
								photosVar = VUE.formData.storefrontPhotos
							}else if(VUE.photosType === 'floorEvacuationPlan'){
								photosVar = VUE.formData.floorEvacuationPlan
							}
							if(!photosVar){ // 如果为空字符串则手动重置为[]
								photosVar = []
							}
							console.log('photsVar方法', JSON.stringify(photosVar))
							if (value) {
								// VUE.formData.attachmentFile.push(...JSON.parse(value).fileNames)
								if(gemhoUtil.isIOSStrict() || gemhoUtil.isHarmonyOS()){ // ios、鸿蒙系统直接返回对象
									
									photosVar.push(...value.fileNames)
								}else{ // 俺安卓机 返回字符串
									photosVar.push(...JSON.parse(value).fileNames)
								}
								console.log('大小', photosVar.length, maxSelectNum,photosVar.length > maxSelectNum)
								if (photosVar.length > maxSelectNum) {
									const result = photosVar.slice(0, maxSelectNum)
									console.log('大小比较', photosVar.length > maxSelectNum, result)
									photosVar = result
								}
							}
						},
						fail: function (data1) {
							console.log(data1);
						}
					});
				};
			},
			
			
			// 添加脱敏处理函数
			desensitize(value, type) {
				if (!value) return '';
				switch(type) {
				case 'name': // 姓名脱敏：保留姓氏
					return value.length > 1 ? value.charAt(0) + '*'.repeat(value.length - 1) : value;
				case 'phone': // 手机号脱敏：保留前3后4
					return value.replace(/^(\d{3})\d{4}(\d{4})$/, '$1****$2');
				case 'address': // 地址脱敏：保留前5后5
					if (value.length <= 10) return value;
					return value.substring(0, 5) + '*****' + value.substring(value.length - 5);
				default: // 默认脱敏：保留前3后3
					if (value.length <= 6) return value;
					return value.substring(0, 3) + '*****' + value.substring(value.length - 3);
				}
			},
			// 切换显示状态方法
			toggleShow(field) {
				this.$set(this.showOriginal, field, !this.showOriginal[field]);
			},
			reset(){
				this.page = 1
				this.size = 9999
				this.total = 0
				this.consumerSuggestList = []
				this.loading = false
				this.finished = false
				
			},
			showImage(list, index) {
				const images = list.map((item)=>{
					return this.previewUrl + item
				})
				console.log(images, 'images')
				vant.ImagePreview({
					images,
					startPosition: index,
					closeable: true,
				});
			},
			// 处理平面图删除
			handleDeleteFloorPlan(index, type) {
				if(type === 'floorPlan'){
					this.formData.floorPlanPhotos.splice(index, 1);
				}else if(type === 'license'){
					this.formData.businessLicensePhotos.splice(index, 1);
				}else if(type === 'storeFront'){
					this.formData.storefrontPhotos.splice(index, 1);
				}else if(type === 'floorEvacuationPlan'){
					this.formData.floorEvacuationPlan.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){ // 返回信息不为空，则进行解密操作
						if(type === 'floorPlan'){
							this.formData.floorPlanPhotos.push(value.fileName)
						}else if(type === 'license'){
							this.formData.businessLicensePhotos.push(value.fileName)
						}else if(type === 'storeFront'){
							this.formData.storefrontPhotos.push(value.fileName)
						}else if(type === 'floorEvacuationPlan'){
							this.formData.floorEvacuationPlan.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);
				});
			},
			viewDetail(item) {
				let params = {
					id: item.id,
				}
				// 这里添加跳转逻辑

				let url = gemhoUtil.setParameter('_consumer_jydetail.html', params)
				gemhoUtil.navigatePage(url, '跳转中...')
			},
			clickTab() {
				if (this.activeTab > 1) {
					this.reset()
					this.getConsumerSuggestList() // 获取检查列表
				}
			},
			

			getConsumerSuggestList() {
				vant.Toast.loading({
					message: '正在加载...',
					forbidClick: true,
					loadingType: 'spinner',
				});
				http2.post({
					serviceId: API_KEY_MAP["page"]['id'],
					interfacePublicKey: API_KEY_MAP["page"]["publicKey"],
					interfacePrivateKey: API_KEY_MAP["page"]["privateKey"],
					reqParams: {
						page: this.page, // 每次请求增加下一页
						size: this.size,
						sign: 18, // 消费者建议列表
						"merId": gemhoUtil.getParameter('merId'),
					}
				}, (res) => {
					if (!res) { // 中台返回为undefined 重新请求
						vant.Toast.clear()
						this.page = this.page - 1 // 重新请求后，分页数恢复上一次请求的值
						setTimeout(() => {
							this.consumerSuggestList()
						}, 0);
						return
					}
					if (res) {
						console.log('接口回调数据-消费者建议', JSON.parse(res))
						setTimeout(() => {
							this.$nextTick(() => {
								vant.Toast.clear()
							})
						}, 0);
						var result = JSON.parse(res)
						this.consumerSuggestList.push(...result.rows);
						this.total = result.total
						
						if (this.page * this.size >= this.total) {
							this.finished = true; // 下滑不在刷新数据
						}else{this.page++}
					}
					this.loading = false
					setTimeout(() => {
						this.$nextTick(()=>{
							vant.Toast.clear()
						})
					}, 0);
				})
			},
			getDict4changhsuoType(param) {
				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: 21, // 场所类型=>行业类别
						...param
					}
				}, (res) => {
					if (!res) { // 中台返回为undefined 重新请求
						vant.Toast.clear()
						setTimeout(() => {
							this.getDict4changhsuoType()
						}, 0);
						return
					}
					if (res) {
						console.log('接口回调数据', JSON.parse(res))
						setTimeout(() => {
							this.$nextTick(() => {
								vant.Toast.clear()
							})
						}, 0);
						var result = JSON.parse(res)
						this.dict4changhsuoType = result.data.body.data
						if(!this.dict4businessType || !this.dict4businessType.length){ // 如果下拉列表为空，则置空场所类型的值。
							this.formData.smallPlaceTypeId = null
						}

					}
				})
			},
			// handleIndustryChange(val) {
			// 	// 选择后晴空下级下拉框值
			// 	this.dict4changhsuoType = []
			// 	this.getDict4changhsuoType({
			// 		industryId: this.formData.industryType
			// 	})
			// },
			getDict4industryType() {
				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: 20, // 行业类型列表
					}
				}, (res) => {
					if (!res) { // 中台返回为undefined 重新请求
						vant.Toast.clear()
						setTimeout(() => {
							this.getDict4industryType()
						}, 0);
						return
					}
					if (res) {
						console.log('接口回调数据-行业类型', JSON.parse(res))
						setTimeout(() => {
							this.$nextTick(() => {
								vant.Toast.clear()
							})
						}, 0);
						var result = JSON.parse(res)
						this.dict4industryType = result.data.body.data

					}
				})
			},
			getDict4community() {
				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: 22,
					}
				}, (res) => {
					if (!res) { // 中台返回为undefined 重新请求
						vant.Toast.clear()
						setTimeout(() => {
							// this.getDict4community()
						}, 0);
						return
					}
					if (res) {
						console.log('接口回调数据=所属社区', JSON.parse(res))
						setTimeout(() => {
							this.$nextTick(() => {
								vant.Toast.clear()
							})
						}, 0);
						var result = JSON.parse(res)
						this.dict4community = result.data

					}
				})
			},
			getDict4businessType() {
				http2.post({
					serviceId: API_KEY_MAP["page"]['id'],
					interfacePublicKey: API_KEY_MAP["page"]["publicKey"],
					interfacePrivateKey: API_KEY_MAP["page"]["privateKey"],
					reqParams: {
						page: 1,
						size: 9999,
						sign: 15,
						dictType: 'business_type'
					}
				}, (res) => {
					if (!res) { // 中台返回为undefined 重新请求
						vant.Toast.clear()
						setTimeout(() => {
							this.getDict4businessType()
						}, 0);
						return
					}
					if (res) {
						console.log('接口回调数据=生产经营类型', JSON.parse(res))
						setTimeout(() => {
							this.$nextTick(() => {
								vant.Toast.clear()
							})
						}, 0);
						var result = JSON.parse(res)
						this.dict4businessType = result.rows

					}
				})
			},

			getDict4fangwuType() {
				http2.post({
					serviceId: API_KEY_MAP["page"]['id'],
					interfacePublicKey: API_KEY_MAP["page"]["publicKey"],
					interfacePrivateKey: API_KEY_MAP["page"]["privateKey"],
					reqParams: {
						page: 1,
						size: 9999,
						sign: 15,
						dictType: 'house_type'
					}
				}, (res) => {
					if (!res) { // 中台返回为undefined 重新请求
						vant.Toast.clear()
						setTimeout(() => {
							this.getDict4fangwuType()
						}, 0);
						return
					}
					if (res) {
						console.log('接口回调数据', JSON.parse(res))
						setTimeout(() => {
							this.$nextTick(() => {
								vant.Toast.clear()
							})
						}, 0);
						var result = JSON.parse(res)
						this.dict4fangwuType = result.rows

					}
				})
			},
			getDict4fangwuyongtuType() {
				http2.post({
					serviceId: API_KEY_MAP["page"]['id'],
					interfacePublicKey: API_KEY_MAP["page"]["publicKey"],
					interfacePrivateKey: API_KEY_MAP["page"]["privateKey"],
					reqParams: {
						page: 1,
						size: 9999,
						sign: 15,
						dictType: 'house_usage'
					}
				}, (res) => {
					if (!res) { // 中台返回为undefined 重新请求
						vant.Toast.clear()
						setTimeout(() => {
							this.getDict4fangwuyongtuType()
						}, 0);
						return
					}
					if (res) {
						console.log('接口回调数=房屋用途', JSON.parse(res))
						setTimeout(() => {
							this.$nextTick(() => {
								vant.Toast.clear()
							})
						}, 0);
						var result = JSON.parse(res)
						this.dict4fangwuyongtuType = result.rows

					}
				})
			},
			save() {
				vant.Toast.loading({
					message: '正在处理...',
					forbidClick: true,
					loadingType: 'spinner',
				});
				var reqParam = { ...this.formData }			// var url = "/gq/checkRecord/safeCheckRecord"

				if (!reqParam.unitName) {
					vant.Toast({
						message: '商家名称不能为空',
					})
					return
				}

				if (!reqParam.merchantName) {
					vant.Toast({
						message: '负责人不能为空',
					})
					return
				}
				if (!gemhoUtil.validateChineseName(reqParam.merchantName)) {
					vant.Dialog.alert({
						message: '负责人格式不正确，请输入中文',
					})
					return;
				}
				
				// 具体格式有待确认 是否支持座机！
				if (reqParam.merchantPhone && !/^1[3-9]\d{9}$/.test(reqParam.merchantPhone)) {
					vant.Dialog.alert({
						message: '电话格式不正确，请输入11位数字的手机号码',
					})
					return;
				}
				
				if (!reqParam.area) {
					vant.Toast({
						message: '建筑面积不能为空',
					})
					return
				}
				
				if (reqParam.area*1 <= 0 || reqParam.area*1 > 9999) {
					vant.Dialog.alert({
						message: '建筑面积格式不正确，请输入大于0且小于9999的数字',
					})
					return;
				}
				
				if (reqParam.owner && !gemhoUtil.validateChineseName(reqParam.owner)) {
					vant.Dialog.alert({
						message: '产权人格式不正确，请输入中文',
					})
					return;
				}
				
				// 具体格式有待确认 是否支持座机！
				if (reqParam.ownerPhone && !/^1[3-9]\d{9}$/.test(reqParam.ownerPhone)) {
					vant.Dialog.alert({
						message: '产权人联系方式格式不正确，请输入11位数字的手机号码',
					})
					return;
				}
				
				if (reqParam.operator && !gemhoUtil.validateChineseName(reqParam.operator)) {
					vant.Dialog.alert({
						message: '经营人格式不正确，请输入中文',
					})
					return;
				}
				
				// 具体格式有待确认 是否支持座机！
				if (reqParam.operatorPhone && !/^1[3-9]\d{9}$/.test(reqParam.operatorPhone)) {
					vant.Dialog.alert({
						message: '经营人联系方式格式不正确，请输入11位数字的手机号码',
					})
					return;
				}
				
				
				if (reqParam.landlordName && !gemhoUtil.validateChineseName(reqParam.landlordName)) {
					vant.Dialog.alert({
						message: '房东姓名格式不正确，请输入中文',
					})
					return;
				}
				
				// 具体格式有待确认 是否支持座机！
				if (reqParam.landlordContact && !/^1[3-9]\d{9}$/.test(reqParam.landlordContact)) {
					vant.Dialog.alert({
						message: '房东联系方式格式不正确，请输入11位数字的手机号码',
					})
					return;
				}
				
				if (!reqParam.community) {
					vant.Toast({
						message: '所属社区不能为空',
					})
					return
				}

				if (!reqParam.industryType) {
					vant.Toast({
						message: '行业类型不能为空',
					})
					return
				}

				reqParam.floorPlanPhotos = this.formData.floorPlanPhotos.join(',')
				reqParam.businessLicensePhotos = this.formData.businessLicensePhotos.join(',')
				reqParam.storefrontPhotos = this.formData.storefrontPhotos.join(',')
				reqParam.floorEvacuationPlan = this.formData.floorEvacuationPlan.join(',')
				http3.put('/gq/merchant', reqParam).then((res) => {
					console.log('保存结果', res)
					vant.Toast({
						message: res.code === 200 ? '操作成功': '操作失败',
					})
					// gemhoUtil.navigatePage(`${this.pageName}.html${window.location.search}`, '操作完成,跳转中...')
				})
			},
			// 文件上传处理
			handleFileUpload(file) {
				console.log('上传文件:', file);
				// 此处可添加实际文件上传逻辑
			},
			// 场所类型
			handlesmallPlaceTypeNameConfirm(event, item) {
				console.log('select选择', event.target.value)
				const value = event.target.value;
				if (value) {
					const days = parseInt(value);
					item.deadlineDays = days;
					const deadlineDate = new Date();
					deadlineDate.setDate(deadlineDate.getDate() + days);
					item.deadlineDate = this.formatDate(deadlineDate);
				}
				// this.showDeadlinePicker = false;
			},
			saveCanvas() {
				vant.Toast.loading({
					message: '图片保存中...',
					forbidClick: true,
					loadingType: 'spinner',
				});

				lightAppJssdk.media.savePhoto({
					arg: VUE.formData.qrCodeUrl,
					success: function (data) {
						vant.Toast('保存成功');
					},
					fail: function (data) {
						vant.Toast('保存失败');
					},
				})
			},
			detail(id) {
				vant.Toast.loading({
					message: '正在加载...',
					forbidClick: true,
					loadingType: 'spinner',
				});
				http3.get(`/gq/merchant/${gemhoUtil.getParameter('merId')}`, {
					
				}).then((res) => {
					if (!res) { // 中台返回为undefined 重新请求
						vant.Toast.clear()
						setTimeout(() => {
							this.detail()
						}, 0);
						return
					}
					if (res) {
						console.log('接口回调数据', res)
						setTimeout(() => {
							this.$nextTick(() => {
								vant.Toast.clear()
							})
						}, 0);
						var result = res
						
						// 图片数据结构处理
						let tempData = result.data
						if(tempData['businessLicensePhotos']){
							tempData['businessLicensePhotos'] = tempData['businessLicensePhotos'].split(',')
						}else{
							tempData['businessLicensePhotos'] = []
						}
						if(tempData['floorPlanPhotos']){
							tempData['floorPlanPhotos'] = tempData['floorPlanPhotos'].split(',')
						}else{
							tempData['floorPlanPhotos'] = []
						}
						if(tempData['storefrontPhotos']){
							tempData['storefrontPhotos'] = tempData['storefrontPhotos'].split(',')
						}else{
							tempData['storefrontPhotos'] = []
						}
						if(tempData['floorEvacuationPlan']){
							tempData['floorEvacuationPlan'] = tempData['floorEvacuationPlan'].split(',')
						}else{
							tempData['floorEvacuationPlan'] = []
						}
						this.formData = tempData
						
						console.log('******详情********', tempData)
					
						// 这里添加跳转逻辑
						const QR_IMAGE_URL = result.data.qrCodeUrl
						this.qrCodeUrl = result.data.qrCodeUrl
					
					}
				})
			},
			
		},
	})
})




