<template>
  <!-- 微信小程序专用 -->
  <!-- #ifdef MP-WEIXIN -->
  <painter
    :palette="finalPalette"
    @imgOK="onImgOK"
    @imgErr="onImgErr"
    :customStyle="customStyle"
  />
  <!-- #endif -->

  <!-- H5和APP端使用Canvas兼容 -->
  <!-- #ifndef MP-WEIXIN -->
  <view class="painter-container">
    <canvas 
      id="posterCanvas" 
      canvas-id="posterCanvas"
      :style="{ 
        width: customStyle.width, 
        height: customStyle.height,
        position: 'fixed',
        left: '-9999px'
      }"
    ></canvas>
    <image v-if="posterUrl" :src="posterUrl" mode="widthFix" class="poster-image" />
    <view v-if="generating" class="loading">海报生成中...</view>
  </view>
  <!-- #endif -->
</template>

<script>
// 小程序端直接使用原生组件
// #ifdef MP-WEIXIN
import Painter from './painter.js';
export default {
  components: { Painter },
  props: {
    palette: Object,
    customStyle: {
      type: Object,
      default: () => ({ width: '750rpx', height: '1334rpx' })
    }
  },
  computed: {
    finalPalette() {
      return this.palette;
    }
  },
  methods: {
    onImgOK(e) {
      this.$emit('imgOK', e);
    },
    onImgErr(err) {
      this.$emit('imgErr', err);
    }
  }
};
// #endif

// H5和APP端兼容实现
// #ifndef MP-WEIXIN
import QRCode from 'qrcode';

export default {
  props: {
    palette: Object,
    customStyle: Object
  },
  data() {
    return {
      posterUrl: '',
      generating: false
    };
  },
  mounted() {
    this.generateH5Poster();
  },
  methods: {
    async generateH5Poster() {
      this.generating = true;
      try {
        console.log('开始生成海报');
        
        // 1. 生成二维码
        const qrCodeUrl = await this.generateQRCode();
        console.log('二维码生成完成', qrCodeUrl ? '成功' : '失败');
        
        // 2. 获取Canvas上下文
        const ctx = uni.createCanvasContext('posterCanvas', this);
        
        // 3. 绘制背景
        ctx.setFillStyle('#ffffff');
        ctx.fillRect(0, 0, 750, 1334);
        
        // 4. 绘制背景图
        const bg = this.palette.views.find(v => v.type === 'image');
        if (bg) {
          console.log('开始绘制背景图:', bg.url);
          try {
            await this.drawImage(ctx, bg.url, 0, 0, 750, 1334);
          } catch (err) {
            console.warn('背景图绘制失败:', err);
          }
        }
        
        // 5. 绘制文字
        const texts = this.palette.views.filter(v => v.type === 'text');
        texts.forEach(text => {
          ctx.setFontSize(parseInt(text.css.fontSize));
          ctx.setFillStyle(text.css.color || '#000000');
          ctx.setTextAlign(text.css.left === 'center' ? 'center' : 'left');
          const x = text.css.left === 'center' ? 375 : parseInt(text.css.left);
          const y = parseInt(text.css.top);
          ctx.fillText(text.text, x, y);
        });
        
        // 6. 绘制二维码
        const qrView = this.palette.views.find(v => v.type === 'qrcode');
        if (qrView && qrCodeUrl) {
          console.log('开始绘制二维码');
          try {
            await this.drawImage(ctx, qrCodeUrl, 
              parseInt(qrView.css.left), 
              parseInt(qrView.css.top), 
              parseInt(qrView.css.width), 
              parseInt(qrView.css.height)
            );
          } catch (err) {
            console.warn('二维码绘制失败:', err);
          }
        }
        
        // 7. 生成最终图片
        console.log('开始生成最终图片');
        await new Promise(resolve => {
          ctx.draw(false, () => {
            setTimeout(() => {
              uni.canvasToTempFilePath({
                canvasId: 'posterCanvas',
                success: (res) => {
                  console.log('图片生成成功', res);
                  this.posterUrl = res.tempFilePath;
                  this.$emit('imgOK', { detail: { path: res.tempFilePath } });
                  resolve();
                },
                fail: (err) => {
                  console.error('图片生成失败:', err);
                  this.$emit('imgErr', err);
                  resolve();
                }
              }, this);
            }, 300);
          });
        });
        
      } catch (err) {
        console.error('海报生成失败:', err);
        this.$emit('imgErr', err);
      } finally {
        this.generating = false;
      }
    },
    
    drawImage(ctx, url, x, y, width, height) {
      return new Promise((resolve, reject) => {
        // 如果是base64数据，直接绘制
        if (url.startsWith('data:image')) {
          console.log('绘制base64图片');
          const img = new Image();
          img.onload = () => {
            ctx.drawImage(img, x, y, width, height);
            resolve();
          };
          img.onerror = (err) => {
            console.warn('base64图片加载失败', err);
            reject(err);
          };
          img.src = url;
          return;
        }
        
        console.log('加载网络图片:', url);
        uni.getImageInfo({
          src: url,
          success: (res) => {
            console.log('图片加载成功', res);
            const img = new Image();
            img.onload = () => {
              ctx.drawImage(img, x, y, width, height);
              resolve();
            };
            img.onerror = (err) => {
              console.warn('图片绘制失败', err);
              reject(err);
            };
            img.src = res.path;
          },
          fail: (err) => {
            console.warn('图片加载失败:', err);
            reject(err);
          }
        });
      });
    },
    
    generateQRCode() {
      return new Promise((resolve) => {
        const qrView = this.palette.views.find(v => v.type === 'qrcode');
        if (!qrView || !qrView.content) {
          console.warn('未找到有效的二维码配置');
          resolve(null);
          return;
        }
        
        console.log('开始生成二维码，内容:', qrView.content);
        
        // 创建临时Canvas用于生成二维码
        const canvas = document.createElement('canvas');
        canvas.width = 200;
        canvas.height = 200;
        
        // 使用Promise风格的API
        QRCode.toCanvas(canvas, qrView.content, {
          width: 200,
          margin: 2,
          color: {
            dark: '#000000',
            light: '#ffffff'
          }
        }, (error) => {
          if (error) {
            console.error('二维码生成失败:', error);
            resolve(null);
          } else {
            console.log('二维码生成成功');
            resolve(canvas.toDataURL('image/png'));
          }
        });
      });
    }
  }
};
// #endif
</script>

<style scoped>
.painter-container {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

canvas {
  display: none;
}

.poster-image {
  width: 100%;
  max-width: 750rpx;
  display: block;
  margin: 0 auto;
}

.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 20rpx 40rpx;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 10rpx;
  font-size: 28rpx;
}
</style>