var VUE = null
window.addEventListener('load', function () {
  // const canvas = document.getElementById('mainCanvas')
  // const ctx = canvas.getContext('2d')
  // ctx.imageSmoothingEnabled = true;
  // ctx.imageSmoothingQuality = 'high';
  // ctx.fillStyle = '#1890ff'; // 或其他所需颜色
  // ctx.fillRect(0, 0, canvas.width, canvas.height);
  
  // 配置参数
  const CONFIG = {
    bgSize: { width: 2480, height: 3502 },  // 背景图原始尺寸
    qrSize: 1150,                           // 二维码尺寸
    pageWidth: 375                          // 页面显示宽度
  };
  
  // 初始化双Canvas
  const displayCanvas = document.getElementById('displayCanvas');
  const exportCanvas = document.createElement('canvas');
  const displayCtx = displayCanvas.getContext('2d');
  const exportCtx = exportCanvas.getContext('2d');
  
  // 设置离屏Canvas（固定导出尺寸）
  exportCanvas.width = CONFIG.bgSize.width;
  exportCanvas.height = CONFIG.bgSize.height;
  
  // 适配显示Canvas
  function initDisplayCanvas() {
    const dpr = window.devicePixelRatio || 1;
    const displayHeight = (CONFIG.pageWidth / CONFIG.bgSize.width) * CONFIG.bgSize.height;
    
    // 设置物理像素
    displayCanvas.width = CONFIG.pageWidth * dpr;
    displayCanvas.height = displayHeight * dpr;
    
    // 调整CSS显示尺寸
    displayCanvas.style.width = `${CONFIG.pageWidth}px`;
    displayCanvas.style.height = `${displayHeight}px`;
    
    // 缩放绘图上下文
    displayCtx.scale(dpr, dpr);
    displayCtx.imageSmoothingEnabled = true;  // 抗锯齿 
  }
  
  // 加载并绘制资源
  async function drawPoster(bgUrl, qrUrl) {
    const [bgImage, qrImage] = await Promise.all([
      loadImage(bgUrl),
      loadImage(qrUrl)
    ]);
	
	if(!bgImage || !qrImage){
		console.log('图片加载失败')
		return
	}
	
    // 计算显示比例
    const scale = CONFIG.pageWidth / CONFIG.bgSize.width;
  
    // 绘制显示Canvas（适配页面宽度）
    displayCtx.drawImage(bgImage, 0, 0, CONFIG.bgSize.width, CONFIG.bgSize.height,
      0, 0, CONFIG.pageWidth, CONFIG.pageWidth * (CONFIG.bgSize.height/CONFIG.bgSize.width));
    
    // 绘制二维码（居中显示）
    const qrDisplaySize = CONFIG.qrSize * scale;
    const qrX = (CONFIG.pageWidth - qrDisplaySize) / 2;
    const qrY = displayCanvas.height/displayCtx.getTransform().a - qrDisplaySize - 50*scale -980*scale;
    displayCtx.drawImage(qrImage, qrX, qrY, qrDisplaySize, qrDisplaySize);
  
    // 绘制离屏Canvas（原始尺寸）
    exportCtx.drawImage(bgImage, 0, 0); 
    const qrExportX = (CONFIG.bgSize.width - CONFIG.qrSize) / 2;
    const qrExportY = CONFIG.bgSize.height - CONFIG.qrSize - 100 -980;
    exportCtx.drawImage(qrImage, qrExportX, qrExportY, CONFIG.qrSize, CONFIG.qrSize);
	
	// VUE.canvasReady = true
	
	document.getElementById('saveBtn').classList.remove('hideEle')
  }
  
  // 图片加载器
  function loadImage(url) {
    return new Promise((resolve, reject) => {
      const img = new Image();
      img.crossOrigin = 'anonymous';
      img.onload = () => resolve(img);
      img.onerror = reject;
      img.src = url;
    });
  }
  
  // 导出图片
  window.saveImage = function() {
    // const link = document.createElement('a');
    // link.download = 'poster.jpg';
    // link.href = exportCanvas.toDataURL('image/jpeg', 0.9);
    // link.click();
  	// const canvas = document.getElementById('mainCanvas')
  	const dataURL = exportCanvas.toDataURL('image/png', 0.9)
  	console.log(dataURL, '图片下载')
  	
  	lightAppJssdk.media.savePhoto({
  	  arg: dataURL,
  	  success: function (data) {
  		// vant.Toast.clear()
  		// alert(JSON.stringify(data))
  		vant.Dialog.alert({
  			message: '保存成功',
  		})
  	  },
  	  fail: function (data) {
  		// vant.Toast.clear()
  		// alert('保存失败')
  		vant.Dialog.alert({
  			message: '保存失败',
  		})
  	  },
  	})
  }
  
  
  // 初始化执行
  initDisplayCanvas();
  // const qrcodeUrl = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsAQAAAABRBrPYAAADw0lEQVR42u2av2/TUBDHzxjViA6uOhUhESSQWLsioecMLGwI/oEiVQKJia2VAm6VoWtFF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r5t98eHyxtrndf91qwnz9/cnEPb87+XrYir3dPzpyzzfo0WH7h76apG7jmB4m7V/Isy+527y3u9uKXZ7uP5i4F9vvLi7bv5C97cmT49u32j/06mTvx/mNj2fuafKHPeVzpKpvl52T/+/YTw8nrIRgQMwOAAAAAElFTkSuQmCC'
  // drawPoster('../image/code/erweimabg.png', qrcodeUrl);
  
  
  
  // 在原有Vue实例中添加
  VUE = new Vue({
    el: '#app',
    data() {
      return {
        flag: 'XQ',
        canvasReady: false,
        loadedImages: 0, // 记录已加载的图片数量
        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: '',
          smallPlaceTypeName: '',
          principal: '',
          phone: '',
          area: '',
          businessHours: '',
          type: '', // 新增类型字段
        },
        showTypePicker: false,
        typeOptions: ['小餐饮', '酒店', '商场', '学校', '医疗机构'],
      }
    },
    computed: {},
    mounted() {
        this.detail()
    },
    methods: {
      detail(id) {
		  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: 11,
		  		"merId": gemhoUtil.getParameter('merId'),
		  	}
		  }, (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);
		  		var result = JSON.parse(res)
		  		this.formData = result.data
				
				console.log('查看详情:', id)
				// this.formData = {}  // 表单赋值
				// 这里添加跳转逻辑
				const QR_IMAGE_URL = result.data.qrCodeUrl
				  // 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAASwAAAEsAQAAAABRBrPYAAAD70lEQVR42u2az0sUYRjHn8na6SCtVFRSOIqGHQILoRQ3f3TqYNgf0EHo4NVuLsi8YynWJbYWlgKbOQR16xJ0sjSEfsDmBEUkBI4o7lFlg9ZY5ul9n/edSc2gS9C+7DAsw8xnZ+F5n+f7/HgX8G+OdahiVayKVbEqpgMWgjhYyaJ7ASsBw8DAQNw19cLEdWCD5RA8xgEzsM2AqUc6YeI+t4NRsugax0rAMRv4p4YYNwh/SryFZBZdMe7Y3AgGcmtYkTPoh9FNUwYyjiE69K3dY6GiMRIum0J467mrvlU0Fh8h3eefTGjXH3NW5WL0NCCboANWKE5+8OjmQa0XJhZaRHFkFqFaBlfs35JRpWNSkBlVFBTOSsQo+WqGgaguTCFZIa2+E5lo69JrgEXCJeoKvuJCqEu8rOKeEOymbxWMIRVRSNnWoUqDLuL8qxGGUpZVF8Btwg+D6kbQCwtFAiJlJt+O6g3yBNQKQ3JsCcilR6qmhGVMvTAqFEmjZL8jREzlX72wkBpYamMt6fB2dIJ2mMg7FMg2kIgpKwXbYqHyMSHRVFQYUfYhE8kZhVYYVYmqejTkNEbEskpPOmFqEGGKC3FSqy7dgKFemCRLstMR7Q/NnWSdrBUWgqwV1VRNpt14yKYbhijrYabGTXH7oxdGq2zIbGvKb/2aDGuGidqJzCKNQ5NSiyZsumEO+XnsAHYU16AXFs9e5PjFBjV+CU0M9cJUww6qVZctnnRy0AwjTWaygqKIRgrt0Nw+LNUBk9s31KEDVVDUGsBO4dIGU9usEOUmOYrRECOXlk9D2m91tg9LtcDUBpzMtnLFaad1Z4FR8Vi0UUU7j6p6ZNGkQies+heXKlbF/gX2tIh+0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SRBhC4T+UhEPGmORTdDkqsRNShEqoO5dFJhHqdCT5iyfiKVyQtQ3UnS4GKSUepn4GzQ5L6TU+DfFFSyGyNCOQjMVokX9LRvlsWBSsG1dMq5cOUlclo+TpeQQMMamAaeDHoIHT9VathH1QWNo5IqFLvSWe7HWsDRcTNOVhnk2z4e2d2a9azR3wWI8sro35IW/YWCjV1TGgSHZIveKBEEltxZbbjH8SOPAMN6ovUw3y6G3GEnoqw/GgY1rIVhp8EgCHmgegywpI8Hm1pUy9JQ+kLLeNkImaAw9NZyONVAs7RI0+bKl4WKLiZmuqxCsJ02NQhkyVmg7jdYUbAZN7lWHzBspOljMogVOhxl+pRGks5rGMCFgzAbHqvwkXdnsFbJEon5JkweMwbcqM61usRnlHG13Y0oQLoZCV+8TQt9mNdfWx4BhtFRpXydGqg6xSm4TzCgwrp0OUW9FXPXtsNGfhozZDJ90bonxfYGRB6sm51gwtNjQsshUdWeUaY9UD/IjwNz1b1e/lLheLanB8DH0p4h10tD3tRgpY8JglSpYjXqd1fgVlgaK1b+wD0gFlE3MCvttKI0EI/tjw0znS5VmXAxh6+lTDFj3v5oOu/pUFhO3cWefe22YX1dsq1+ctX7o6Q5l7uXn/n1qw76v79DNtc2t/k4r5t98eHyxtrndf91qwnz9/cnEPb87+XrYir3dPzpyzzfo0WH7h76apG7jmB4m7V/Isy+527y3u9uKXZ7uP5i4F9vvLi7bv5C97cmT49u32j/06mTvx/mNj2fuafKHPeVzpKpvl52T/+/YTw8nrIRgQMwOAAAAAElFTkSuQmCC'
				drawPoster('../image/code/erweimabg.png', QR_IMAGE_URL);
				
		  	}
		  })
      
      },
      // 新增选择确认方法
      onConfirmType(value) {
        this.formData.type = value
        this.showTypePicker = false
      },
   
      // generateQRCode(QR_IMAGE_URL) {
      //   this.canvasReady = false
      //   // 加载二维码图片
      //   const img = new Image()
      //   img.crossOrigin = 'Anonymous' // 处理跨域问题
      //   img.src = '../image/code/erweimabg.png' // QR_IMAGE_URL;

      //   const img4erweima = new Image()
      //   img4erweima.crossOrigin = 'Anonymous' // 处理跨域问题
      //   img4erweima.src = QR_IMAGE_URL // QR_IMAGE_URL;

      //   img.onload = () => {
      //     this.loadedImages++
      //     this.drawImages(img, img4erweima)
      //   }

      //   img4erweima.onload = () => {
      //     this.loadedImages++
      //     this.drawImages(img, img4erweima)
      //   }
      // },
      // drawImages(img, img4erweima) {
      //   if (this.loadedImages === 2) {
      //     // 画布的宽度和高度
      //     const canvasWidth = canvas.width
      //     const canvasHeight = canvas.height

      //     // 图片的原始宽度和高度
      //     const imgWidth = img.width
      //     const imgHeight = img.height

      //     // 计算宽度和高度的缩放比例
      //     const scaleX = canvasWidth / imgWidth
      //     const scaleY = canvasHeight / imgHeight

      //     // 取较小的缩放比例作为最终的缩放比例
      //     const scale = Math.min(scaleX, scaleY)

      //     // 计算缩放后的图片宽度和高度
      //     const scaledWidth = imgWidth * scale
      //     const scaledHeight = imgHeight * scale

      //     // 计算图片在画布上的绘制位置，使其居中显示
      //     const x = (canvasWidth - scaledWidth) / 2
      //     const y = (canvasHeight - scaledHeight) / 2

      //     // 绘制图片到 canvas 上
      //     ctx.drawImage(img, x, y, scaledWidth, scaledHeight)

      //     // 绘制前景图标
      //     const fgIconSize = 180 // 假设前景图标显示的尺寸
      //     const fgX = (canvasWidth - fgIconSize) / 2
      //     const fgY = ((canvasHeight - fgIconSize) / 2 ) + 15

      //     // 绘制二维码
      //     ctx.drawImage(img4erweima, fgX, fgY, fgIconSize, fgIconSize)

      //     this.canvasReady = true
      //   }
      // },
    },
  })
})

 //   function saveCanvas() {
	// if (!VUE.canvasReady) return
	// vant.Toast.loading({
	// 	message: '图片保存中...',
	// 	forbidClick: true,
	// 	loadingType: 'spinner',
	// });

	// const canvas = document.getElementById('mainCanvas')
	// const dataURL = canvas.toDataURL('image/png')
	// console.log(dataURL, '图片下载')

	// lightAppJssdk.media.savePhoto({
	//   arg: dataURL,
	//   success: function (data) {
	// 	// vant.Toast.clear()
	// 	// alert(JSON.stringify(data))
	// 	vant.Dialog.alert({
	// 		message: '保存成功',
	// 	})
	//   },
	//   fail: function (data) {
	// 	// vant.Toast.clear()
	// 	// alert('保存失败')
	// 	vant.Dialog.alert({
	// 		message: '保存失败',
	// 	})
	//   },
	// })
 //  }


