/**
 * author: dabao
 * date: 2024-03-15
 * description: 商户首页
 */
var VUE = null
var quill = null
window.addEventListener("load", function () {
	VUE = new Vue({
		el: '#app',
		data() {
			return {
				detailInfo: {},
				showTipPopup: false,
				previewUrl: BASE_URL,
				flag: 'XQ',
				flag: 'ADD',
				showStartDatePicker: false, // 开始时间选择器显示控制
				showEndDatePicker: false, // 结束时间选择器显示控制
				showDatePicker: false, // 控制日期选择器显示
				minDate: new Date(gemhoUtil.getTargetDateYMDHM()), // 最小可选日期
				maxDate: new Date(2099, 11, 31), // 最大可选日期
				tabList4lv2: [],
				// 日期选择的最小范围，这里设置为当前日期的前 10 年
				// maxDate: new Date(new Date().getFullYear() + 10, 11),
				// 新增以下数据
				formData: {
					merchantName: '',
					merchantPhone: '',
					merName: '',
					attachmentFile: [],
					workType: '',
					companyName: '',
					workerName: '',
					startTime: '', // 开始时间字段
					endTime: '' ,// 结束时间字段
					check: false
				},
				id: '',
				errorReqCount: 0,
				iosFlag: gemhoUtil.isIOSStrict(),
				// 添加显示状态管理对象
				showOriginal: {
					merchantName: false,
					merchantPhone: false,
				}
			}
		},
		created() {

		},
		mounted() {
			this.id = gemhoUtil.getParameter('id')
			if (this.id) { // 详情
				this.flag = 'XQ'
				this.detail() // 获取商户信息
			} else {
				this.flag = 'ADD'
				this.getShopInfo()
			}
			this.getDict4tab1()
		},
		methods: {
			// 添加脱敏处理函数
			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]);
			},
			goback4ios() { // 全部标记为已读
				let params = {
					merId: gemhoUtil.getCookie('merId') || '',
				}
				// 这里添加跳转逻辑
				var pageUrl = '_tezhongzuoye.html' // 安全培训详情页面
				let url = gemhoUtil.setParameter(pageUrl, params)
				gemhoUtil.navigatePage(url, '跳转中...')
			},
			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: 35,
							merId: gemhoUtil.getParameter('merId') || '',
						},
					},
						(res) => {
							if (res) {
								var result = JSON.parse(res)
								console.log('商户信息', result)
								if (result.data) {
									this.formData.merName = result.data.merName
									this.formData.merchantPhone = result.data.merchantPhone
									this.formData.merchantName = result.data.merchantName
								}
							}
						}
					)
				}, 0)
			},
			showTipPage() {

				this.showTipPopup = true
				this.formData.check = true
				this.detail4Tip()
				return

				// let param = {
				// 	type: this.formData.workType,
				// 	pageName: '_tezhongzuoye_detail',
				//   }
				//   let url = gemhoUtil.setParameter('_tezhongzuoye_detail-text.html', param)
				//   console.log(url)

				//   gemhoUtil.navigatePage(url, '跳转中...')
			},
			detail4Tip(param) { // 隐患详情
				// vant.Toast.loading({
				if(!param){ // 初次请求则显示加载框
					vant.Toast.loading({
						message: '正在加载...',
						forbidClick: true,
						loadingType: 'spinner',
					});
				}
				
				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: 34, // 隐患详情
						workType: this.formData.workType,
					}
				}, (res) => {
					if (!res) {
						// 中台返回为undefined 重新请求
						console.log('getRemindStatistic方法返回null！！')
						if(this.errorReqCount <= 5){
							this.errorReqCount++
							this.detail4Tip('repeatReq') // 请求错误后，重新发起请求
						}
						
						return
					}
					if (res) {
						console.log('接口回调数据', JSON.parse(res))
						setTimeout(() => {
							this.$nextTick(() => {
								vant.Toast.clear()
							})
						}, 0);
						this.detailInfo = JSON.parse(res).data
						// 初始化编辑器
						quill = new Quill('#editor-container', {
							theme: 'snow',
							readOnly: true,
							modules: {
								toolbar: false // 关键配置：禁用工具栏
							},
						});
						quill.root.innerHTML = this.detailInfo || '该特种作业类型下暂无提醒事项内容，请联系管理员'
						this.$nextTick(()=>{
							// 新增：触发滚动条更新逻辑
							this.updateScrollWrapper()
						})
						
					}
				})

			},
			// 新增：更新滚动容器的布局
			updateScrollWrapper() {
				const wrapper = document.getElementById('fuwenben-wrapper')
				if (wrapper) {
					// 强制触发浏览器重排（通过访问布局属性）
					const temp = wrapper.offsetHeight
					// 可选：动态调整最大高度（如果需要）
					// wrapper.style.maxHeight = window.innerHeight * 0.6 + 'px'
				}
			},
			getDict4tab1() {
				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: 'special_work_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.tabList4lv2 = result.rows
						if (this.flag == 'ADD') {
							this.formData.workType = this.tabList4lv2[0].dictValue
						}
					}
				})
			},
			// 处理平面图删除
			handleDeleteFloorPlan(index, type) {
				this.formData.attachmentFile.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.attachmentFile.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.attachmentFile.push(...JSON.parse(value).fileNames)
								if(gemhoUtil.isIOSStrict() || gemhoUtil.isHarmonyOS()){ // ios直接返回对象
									VUE.formData.attachmentFile.push(...value.fileNames)
								}else{ // 俺安卓机 返回字符串
									VUE.formData.attachmentFile.push(...JSON.parse(value).fileNames)
								}
								if (VUE.formData.attachmentFile.length > maxSelectNum) {
									const result = VUE.formData.attachmentFile.slice(0, maxSelectNum)
									VUE.formData.attachmentFile = result
								}
							}
						},
						fail: function (data1) {
							console.log(data1);
						}
					});
				};
			},
			showDatePickerModal() {
				if (this.flag == 'XQ') {
					return
				}
				this.showDatePicker = true
			},
			onConfirmType(value) {
				this.formData.type = value;
				this.showTypePicker = false;
			},
			// 确认日期选择
			showStartDatePickerHandler() {
				if (this.flag === 'XQ') return;
				this.showStartDatePicker = true;
			},
			showEndDatePickerHandler() {
				if (this.flag === 'XQ') return;
				this.showEndDatePicker = true;
			},
			onStartDateConfirm(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				this.formData.startTime = `${year}-${month}-${day} ${hours}:00`;
				this.showStartDatePicker = false;
			},
			onEndDateConfirm(date) {
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				this.formData.endTime = `${year}-${month}-${day} ${hours}:00`;
				this.showEndDatePicker = false;
			},

			showImage(list, index) {
				const images = list.map((item) => {
					return this.previewUrl + item
				})

				vant.ImagePreview({
					images,
					startPosition: index,
					closeable: true,
				});
			},
			gotoPage(stringifyUrl) {
				let url = gemhoUtil.setParameter(`src/_${stringifyUrl}.html`)
				gemhoUtil.navigatePage(url, '跳转中...')
			},
			// 文件上传处理
			handleFileUpload(file) {
				console.log('上传文件:', file);
				// 此处可添加实际文件上传逻辑
			},

			submitForm() {
				if (!this.formData.workType) {
					vant.Dialog.alert({
						message: '特种作业类型不可为空',
					})
					return;
				}
				if (!gemhoUtil.validateRequire(this.formData.workerName)) {
					vant.Dialog.alert({
						message: '作业人员姓名不可为空',
					})
					return;
				}
				
				if (!gemhoUtil.validateChineseName(this.formData.workerName)) {
					vant.Dialog.alert({
						message: '作业人员姓名格式不正确，请输入中文',
					})
					return;
				}
				
				if (this.formData.workerName.length <2) {
					vant.Dialog.alert({
						message: '作业人员姓名格式不正确，请输入2个或更多字符的名称',
					})
					return;
				}
				if (!this.formData.startTime || !this.formData.endTime) {
					vant.Dialog.alert({
						message: '作业时间不可为空',
					})
					return;
				}
				if (!this.formData.attachmentFile.length) {

					vant.Dialog.alert({
						message: '作业证件不可为空',
					})
					return;
				}
				if (!this.formData.check) {
					vant.Dialog.alert({
						message: '还未阅读提醒事项',
					})
					return;
				}

				vant.Toast.loading({
					message: '正在处理...',
					forbidClick: true,
					loadingType: 'spinner',
				});
				var reqParam = {
					merId: gemhoUtil.getParameter('merId'),
					exerciseType: '2', // 应急演练
					...this.formData,
				}
				reqParam.attachmentFile = this.formData.attachmentFile.join(',')

				http3.post('/gq/special', reqParam).then((res) => {
					console.log('添加结果', res)
					if (res.code === 200) {
						vant.Toast({
							message: '操作成功',
						})
						setTimeout(function () {
							history.back()
						}, 300)

					} else {
						vant.Toast({
							message: '操作失败',
						})
					}
				})
			},
			//获取商户信息
			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: 33,
							specialWorkId: 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['attachmentFile']) {
									tempData['attachmentFile'] = tempData[
										'attachmentFile'] ? tempData[
											'attachmentFile'].split(',') : []
								}

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

})