<template>
  <view class="container">
    <canvas canvas-id="myCanvas" style="width: 300px; height: 300px;"></canvas>
    <button @tap="uploadImage">上传印章图片</button>
    <button @tap="processImage" v-if="imagePath">处理图片</button>
    <image :src="processedImage" v-if="processedImage" mode="widthFix"></image>
  </view>
</template>

<script>
	import { BASE_URL,IMAGE_BASE_URL } from '@/utils/config';
export default {
  data() {
    return {
      imagePath: '',
      processedImage: ''
    }
  },
  methods: {
    // 上传图片
    uploadImage() {
      const that = this;
      uni.chooseImage({
        count: 1,
        sourceType: ['album', 'camera'],
        success: function (res) {
          that.imagePath = res.tempFilePaths[0];
          that.drawImageToCanvas();
        }
      });
    },
    
    // 将图片绘制到Canvas
    drawImageToCanvas() {
      const that = this;
      const ctx = uni.createCanvasContext('myCanvas', this);
      
      // 清空Canvas
      ctx.clearRect(0, 0, 300, 300);
      
      // 绘制图片
      uni.getImageInfo({
        src: that.imagePath,
        success: function (res) {
          ctx.drawImage(res.path, 0, 0, 300, 300);
          ctx.draw(false, () => {
            console.log('图片绘制完成');
          });
        }
      });
    },
    
    // 处理图片（移除白色背景）
    processImage() {
      const that = this;
      const ctx = uni.createCanvasContext('myCanvas', this);
      
      // 获取Canvas像素数据
      uni.canvasGetImageData({
        canvasId: 'myCanvas',
        x: 0,
        y: 0,
        width: 300,
        height: 300,
        success: function(res) {
          const data = res.data;
          
          // 遍历像素数据，将白色（或接近白色）变为透明
          for (let i = 0; i < data.length; i += 4) {
            const r = data[i];
            const g = data[i + 1];
            const b = data[i + 2];
            
            // 判断是否为白色或接近白色（可根据需要调整阈值）
            if (r > 200 && g > 200 && b > 200) {
              data[i + 3] = 0; // 设置Alpha通道为0（完全透明）
            }
          }
          
          // 将处理后的像素数据放回Canvas
          uni.canvasPutImageData({
            canvasId: 'myCanvas',
            x: 0,
            y: 0,
            width: 300,
            height: 300,
            data: data,
            success: function() {
              // 将Canvas内容转换为图片
              that.canvasToImage();
            }
          });
        }
      });
    },
    
    // 将Canvas转换为图片
    canvasToImage() {
      const that = this;
      uni.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function(res) {
          that.processedImage = res.tempFilePath;
		  const fileList = [{
		    url: res.tempFilePath,
		    status: 'uploading'
		  }];
		  console.log("==fileList",fileList)
		  
		  // 4. 上传文件
		 that.uploadFile(fileList[0]);
          // 这里可以调用上传接口，将处理后的图片上传到服务器
          console.log('处理后的图片路径:', res.tempFilePath);
        },
        fail: function(err) {
          console.error('Canvas转换失败', err);
        }
      });
    },
	async uploadFile(file) {
	  try {
	    await new Promise((resolve, reject) => {
	      uni.uploadFile({
	        url: `${IMAGE_BASE_URL}/api/v1/upload`,
	        filePath: file.url,
	        name: 'file',
	        header: { 
	          'Authorization': `Bearer ${uni.getStorageSync('token')}`,
	          'Content-Type': 'multipart/form-data'
	        },
	        success: (uploadRes) => {
	          try {
	            const data = JSON.parse(uploadRes.data);
	            if (data.success) {
	              resolve(data.data);
	            } else {
	              reject(data.message || '上传失败');
	            }
	          } catch (e) {
	            reject('解析响应失败');
	          }
	        },
	        fail: (err) => reject(err)
	      });
	    });
	  } catch (err) {
	    console.error('上传失败:', err);
	    const index = this.fileList.findIndex(f => f.url === file.url);
	    if (index !== -1) {
	      this.$set(this.fileList, index, { 
	        ...file, 
	        status: 'failed',
	        error: err.message || err 
	      });
	    }
	    uni.showToast({ 
	      title: `上传失败: ${err.message || err}`, 
	      icon: 'none' 
	    });
	    throw err;
	  }
	},
  }
}
</script>