/**
 * author: dabao
 * date: 2024-03-15
 * description: 商户首页
 */
// pdf.js核心配置（解决Worker跨域问题）
// 修改后
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://unpkg.com/pdfjs-dist@2.16.105/build/pdf.worker.min.js';

let pdfDoc = null;       // PDF文档实例
let currentPageNum = 1;  // 当前页码

let currentScale = 1.2;  // 当前缩放比例（初始120%）
const MIN_SCALE = 0.5;   // 最小缩放比例
const MAX_SCALE = 2.0;   // 最大缩放比例

// 预览PDF主函数


// 渲染指定页码
async function renderPage(pageNum) {
	const pdfViewer = document.getElementById('pdfViewer');
	pdfViewer.innerHTML = ''; // 清空旧内容

	// 获取指定页并渲染到canvas
	const page = await pdfDoc.getPage(pageNum);
	// 使用currentScale控制缩放
	const viewport = page.getViewport({ scale: currentScale });

	// 创建canvas并设置尺寸
	const canvas = document.createElement('canvas');
	canvas.width = viewport.width;
	canvas.height = viewport.height;
	canvas.style.width = '100%'; // 自适应容器宽度

	// 渲染到canvas
	const context = canvas.getContext('2d');
	await page.render({ canvasContext: context, viewport: viewport }).promise;

	// 添加到DOM
	pdfViewer.appendChild(canvas);

	// 更新当前页码显示
	document.getElementById('currentPage').textContent = pageNum;
	// document.getElementById('currentScale').textContent = `${(currentScale * 100).toFixed(0)}%`;
}

// 放大（每次增加0.2倍）
function zoomIn() {
	if (currentScale < MAX_SCALE) {
		currentScale += 0.2;
		renderPage(currentPageNum); // 重新渲染当前页
	}
}

// 缩小（每次减少0.2倍）
function zoomOut() {
	if (currentScale > MIN_SCALE) {
		currentScale -= 0.2;
		renderPage(currentPageNum); // 重新渲染当前页
	}
}


// 上一页
function prevPage() {
	if (pdfDoc && currentPageNum > 1) {
		currentPageNum--;
		renderPage(currentPageNum);
	}
}

// 下一页
function nextPage() {
	if (pdfDoc && currentPageNum < pdfDoc.numPages) {
		currentPageNum++;
		renderPage(currentPageNum);
	}
}

// 关闭预览
function closePreview() {
	document.getElementById('pdfModal').style.display = 'none';
	pdfDoc = null; // 释放资源
	currentPageNum = 1;
}
var VUE = null
window.addEventListener("load", function () {
	VUE = new Vue({
		el: '#app',
		data() {
			return {
				detailInfo:{}
			}
		},
		created() {
			let params = gemhoUtil.getUrlParams()
			console.log(params);
			this.merId = params.merId
		},
		mounted() {
			this.detail()
		},
		methods: {
			detail() { // 隐患详情
				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: 17, // 隐患详情
						safetyId:  gemhoUtil.getParameter('id'),
					}
				}, (res) => {
					if (!res) { // 中台返回为undefined 重新请求
						vant.Toast.clear()
						setTimeout(() => {
							this.detail()
						}, 0);
						return
					}
					if (res) {
						console.log('接口回调数据', JSON.parse(res))
						setTimeout(() => {
							this.$nextTick(() => {
								vant.Toast.clear()
							})
						}, 0);
						this.detailInfo = JSON.parse(res).data
						console.log(this.detailInfo,'sssss')
				
					}
				})

			},
			async previewFile(pdfUrl1) {
				vant.Toast.loading({
					message: '正在加载...',
					forbidClick: true,
					loadingType: 'spinner',
				})
				const pdfUrl = this.detailInfo.file //"http://192.168.2.11:8848/gaoquyingjih5-asd-jpaas/src/test/testPdf.pdf"
				try {
					// 1. 加载PDF文档（异步）
					pdfDoc = await pdfjsLib.getDocument(pdfUrl).promise;
					console.log(pdfDoc, 'pdfjsLib.getDocument')
					const totalPages = pdfDoc.numPages;

					// 2. 更新总页数显示
					document.getElementById('totalPages').textContent = totalPages;

					// 3. 渲染第一页
					currentPageNum = 1;
					await renderPage(currentPageNum);

					// 4. 显示模态框
					document.getElementById('pdfModal').style.display = 'block';
					vant.Toast.clear()
				} catch (error) {
					console.error('PDF加载失败:', error);
					alert('PDF加载失败，请检查文件地址或网络');
					vant.Toast.clear()
				}
			},
			// previewFile(){
			// 	// location.href = "http://192.168.2.11:8848/gaoquyingjih5-asd-jpaas/src/test/testPdf.pdf"
			// 	location.href = '_pdf_viewer.html'
			// },
			onSearch() {
				console.log('xxxx', this.merName)
				this.getList()

			},
			reset() {
				this.page = 0
				this.size = 6
				this.total = 0
				this.hazardList = []
			},
			getList() {
				// 这里添加获取数据的逻辑
				vant.Toast.loading({
					message: '正在加载...',
					forbidClick: true,
					loadingType: 'spinner',
				})
				setTimeout(() => {
					http2.post(
						{
							serviceId: API_KEY_MAP['page']['id'],
							interfacePublicKey: API_KEY_MAP['page']['publicKey'],
							interfacePrivateKey: API_KEY_MAP['page']['privateKey'],
							reqParams: {
								sign: 3,
								// merId: this.merId ? this.merId : '',
								merName: this.shanghuName,
								pageNum: this.page++, // 每次请求增加下一页
								pageSize: this.size,
							},
						},
						(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, 'result')
								this.loading = false; // 加载状态结束
								this.hazardList.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);

						}
					)
				}, 0)
			},
			tabChange(title) {
				console.log('tab 切换', title)
				this.reset()
				this.getList()
			},
			init() {
				this.getList()
			},
			onSearch() {
				this.reset()
				this.getList()
			},
			// 新增选择确认方法

			viewDetail(item, type) {
				let param = {
					id: item.id,
					pageName: '_anquan_changshi',
				}
				let url = gemhoUtil.setParameter('_anquan_changshi-detail.html', param)
				console.log(url)

				gemhoUtil.navigatePage(url, '跳转中...')
			},
		}
	});

})