var VUE = null
window.addEventListener('load', function () {
  const canvas = document.getElementById('mainCanvas')
  const ctx = canvas.getContext('2d')
  // 在原有Vue实例中添加
  VUE = new Vue({
    el: '#app',
    data() {
      return {
        flag: 'XQ',
        canvasReady: false,
        loadedImages: 0, // 记录已加载的图片数量
        formData: {
          id: 1,
          unitName: '威海火炬高技术产业开发区沸腾小火锅店',
          businessAddress: '268-7-D2-4',
          smallPlaceTypeId: 2,
          useNature: '餐饮店',
          unifiedSocialCreditCode: '92371000MA3U6FCR02',
          area: 51.61,
          employeeCount: 2,
          owner: '朱德艳',
          merchantPhone: '13863159973',
          qrCodeUrl: '',
          community: '欧乐坊社区',
          street: '田和街道',
          gridMemberName: '于灏',
          gridMemberPhone: '17865160657',
          createBy: '',
          createTime: null,
          updateBy: '',
          updateTime: '2025-04-02 01:30:33',
          remark: '',
          deptId: 209,
          merchantId: 0,
          smallPlaceType: '',
          smallPlaceTypeName: '小餐饮',
          principal: '',
          phone: '',
          area: '',
          businessHours: '',
          type: '', // 新增类型字段
          sjName1: '威海市宝威酒店有限公司',
          sjName2: 'XXX',
          sjName3: '0631-522221212',
          sjName4: '威海市XXXXXXXXX',
          sjName5: '小餐饮',
        },
        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+0ShjCt9hT7Eb6h8GxrR72POx56u5EWOPBy1/iUFNCt9KbCownESdwCYKmxHm1LRtzs8yPw/J9wEUz7sjcBLLuSuWX+h6sQrJCNvTe2y+j83Wwn4YhGfNHGscms5dLeeXOy9swZ7vm+pf4sKQKkG6kG11Wc+qeSIHtfmN9r0JFv2o9+SUe2sp7ZiN1mT5TbYFDkAh6STqO/I/mhdfjljR20xITiynvQJYNevGXC1hn9ze+nn76JdEjN27c9mbLKYzLYfcPo4l3dH7q+Y3d4BjlnGuN35brt9rLxrZlrOpSwX82Oamx1auZRJ1x+dT/sKRGMsc7K09s8QyrR3D+VYs9jRcv7nyfSpnLfrDcx8SA57CblxkmZEmli10dPlDWOzuHoUmfJCbtfxXwezn+G2nV8udYT/LjhtJ30fYY9v2INwdb2hIFjZvr8TYjFiwNfDcIQ/XEGpITB+5M8gNu/Da9/5zt/wJ5zVLxjs6WyMAAAAASUVORK5CYII='
				  
				this.generateQRCode(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

          // 绘制二维码
          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: '保存失败',
		})
	  },
	})
  }
