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

	// 在原有Vue实例中添加
	VUE = new Vue({
		el: '#app',
		data() {
			return {
				previewUrl: BASE_URL,
				loading: false,
				finished: false,
				page: 0,
				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: [], // 新增图片数组字段
				},
				dict4changhsuoType: [],
				dict4fangwuType: [],
				dict4fangwuyongtuType: [],
				dict4businessType: [],
				dict4community: [],
				dict4industryType: [],
				consumerSuggestList: [],
			}
		},
		computed: {
		},
		mounted() {
			// 详情编辑权限控制
			const userType = gemhoUtil.getCookie('userType')
			if (userType == 'wgy' || userType == 'safety') {
				this.flag = 'XG'
			} else {
				this.flag = 'XQ'
			}

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

			// this.getDict4changhsuoType()
		},
		watch: {
			'formData.industryType': {
				handler(newVal) {
					// 选择后晴空下级下拉框值
					this.dict4changhsuoType = []
					
					this.getDict4changhsuoType({
						industryId: newVal
					})
				},
				deep: true // 深度监听对象属性
			}
		},
		methods: {
			reset(){
				this.page = 0
				this.size = 9999
				this.total = 0
				this.consumerSuggestList = []
				
			},
			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);
				}
			},
			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) { // 调用爱山东中台系统，将数据流传递过去
				alert(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)
						}
						// 可根据后端返回的数据做进一步处理，如显示上传成功信息等
						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; // 下滑不在刷新数据
						}
					}
					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.area) {
					vant.Toast({
						message: '建筑面积不能为空',
					})
					return
				}
				if (!reqParam.merchantName) {
					vant.Toast({
						message: '负责人不能为空',
					})
					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(',')

				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(',')
						}
						if(tempData['floorPlanPhotos']){
							tempData['floorPlanPhotos'] = tempData['floorPlanPhotos'].split(',')
						}
						if(tempData['storefrontPhotos']){
							tempData['storefrontPhotos'] = tempData['storefrontPhotos'].split(',')
						}
						this.formData = tempData
						
						console.log('******详情********', tempData)
					
						// 这里添加跳转逻辑
						const QR_IMAGE_URL = result.data.qrCodeUrl
						this.qrCodeUrl = result.data.qrCodeUrl
					
					}
				})
			},
			
		},
	})
})




