<template>
  <wd-popup v-model="show" position="bottom" round>
    <view class="max-h-[calc(100vh-100px)] m-4">
      <view class="p-4 flex justify-center">
        <!-- 添加最大高度限制容器 -->
        <view class="max-h-[70vh] rounded-xl overflow-hidden">
          <canvas canvas-id="posterCanvas" id="posterCanvas" class="rounded-xl shadow"
            :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }" ref="posterCanvas"></canvas>
        </view>
      </view>
      <view class="divider">分享到好友</view>

      <view class="flex items-center justify-around">
        <view class="flex flex-col items-center justify-center" @click="savePoster">
          <image src="/static/image/icon_share_img.svg" class="w-10 h-10 rounded-full" />
          <view class="text-center mt-1 text-gray-600 text-xs">保存图片</view>
        </view>
        <!-- <view class="flex flex-col items-center justify-center" @click="shareToWechatFriend">
          <image src="/static/image/icon_share_wechat.svg" class="w-10 h-10 rounded-full" />
          <view class="text-center mt-1 text-gray-600 text-xs">微信好友</view>
        </view>
        <view class="flex flex-col items-center justify-center" @click="shareToWechatMoments">
          <image src="/static/image/icon_share_friends.svg" class="w-10 h-10 rounded-full" />
          <view class="text-center mt-1 text-gray-600 text-xs">微信朋友圈</view>
        </view> -->
        <view class="flex flex-col items-center justify-center" @click="copyUrl">
          <image src="/static/image/icon_share_url.svg" class="w-10 h-10 rounded-full" />
          <view class="text-center mt-1 text-gray-600 text-xs">复制链接</view>
        </view>

      </view>
    </view>
  </wd-popup>
</template>

<script setup>
import { ref, watch, nextTick, computed, onMounted, toRefs, getCurrentInstance } from 'vue';
import UQRCode from 'uqrcodejs';

const props = defineProps({
  linkIdentifier: {
    type: String,
    required: true,
  },
  mode: {
    type: String,
    default: "promote", // 例如 "promote" | "invitation"
  },
});

const { linkIdentifier, mode } = toRefs(props);
const posterCanvas = ref(null);  // 用于绘制海报的canvas
const posterGenerated = ref(false);  // 标记海报是否已经生成过
const show = defineModel('show');
const instance = getCurrentInstance();

// 添加画布尺寸变量 - 降低默认尺寸
const canvasWidth = ref(300);  // 画布宽度
const canvasHeight = ref(500); // 画布高度

const url = computed(() => {
  // 在uniapp中获取当前站点的基础URL
  const baseUrl = import.meta.env.VITE_APP_SHARE_URL || 'https://www.tianyuandata.com';
  return mode.value === "promote"
    ? `${baseUrl}/agent/promotionInquire/`
    : `${baseUrl}/agent/invitationAgentApply/`;
});

const qrcodeImage = ref(null);

const loadPosterImage = async () => {
  if (mode.value === "promote") {
    return '/static/image/tg_qrcode_1.png';
  } else {
    return '/static/image/yq_qrcode_1.png';
  }
};

onMounted(async () => {
  // 只在挂载时加载图片路径，但不生成海报
  qrcodeImage.value = await loadPosterImage();
});

// 计算适合屏幕的画布尺寸
const calculateCanvasSize = (imgWidth, imgHeight) => {
  // 获取系统信息
  const sysInfo = uni.getSystemInfoSync();

  // 计算可用高度（屏幕高度的70%）
  const maxHeight = sysInfo.windowHeight * 0.6;
  // 控制最大宽度（屏幕宽度的80%）
  const maxWidth = sysInfo.windowWidth * 0.8;

  // 初始尺寸
  let width = 300;
  let height = width * (imgHeight / imgWidth);

  // 如果高度超出限制，按高度缩放
  if (height > maxHeight) {
    height = maxHeight;
    width = height * (imgWidth / imgHeight);
  }

  // 如果宽度超出限制，按宽度缩放
  if (width > maxWidth) {
    width = maxWidth;
    height = width * (imgHeight / imgWidth);
  }

  // 返回最终计算的尺寸
  return {
    width: Math.floor(width),
    height: Math.floor(height)
  };
};

// 生成海报并合成二维码
const generatePoster = async () => {
  console.log('[DEBUG] generatePoster: 开始生成海报');

  // 如果已经生成过海报，就直接返回
  if (posterGenerated.value) {
    console.log('[DEBUG] generatePoster: 海报已生成，跳过');
    return;
  }

  // 确保 DOM 已经渲染完成
  await nextTick();
  console.log('[DEBUG] generatePoster: DOM已渲染完成');

  try {
    // 显示加载提示
    uni.showLoading({ title: '生成海报中...' });

    console.log('[DEBUG] generatePoster: 在APP环境中执行');
    const canvasContext = uni.createCanvasContext('posterCanvas', instance.proxy);
    if (!canvasContext) {
      throw new Error('创建Canvas上下文失败');
    }
    console.log('[DEBUG] generatePoster: 创建Canvas上下文成功', !!canvasContext);

    // 加载海报图片 - 确保绝对路径
    const posterImagePath = mode.value === "promote"
      ? '/static/image/tg_qrcode_1.png'
      : '/static/image/yq_qrcode_1.png';
    console.log('[DEBUG] generatePoster: 开始加载海报图片', posterImagePath);

    try {
      // 加载图片信息
      const posterImgInfo = await new Promise((resolve, reject) => {
        uni.getImageInfo({
          src: posterImagePath,
          success: res => {
            console.log('[DEBUG] generatePoster: 海报图片加载成功', res);

            // 计算适合屏幕的尺寸
            const size = calculateCanvasSize(res.width, res.height);
            canvasWidth.value = size.width;
            canvasHeight.value = size.height;
            console.log('[DEBUG] generatePoster: 计算画布尺寸', size);

            resolve(res);
          },
          fail: err => {
            console.error('[DEBUG] generatePoster: 海报图片加载失败', err);
            reject(err);
          }
        });
      });

      // 完全清除画布
      canvasContext.clearRect(0, 0, canvasWidth.value, canvasHeight.value);

      // 绘制流程 - 多次测试以查找问题
      // 先尝试绘制底色确认canvas工作正常
      canvasContext.setFillStyle('#ffffff');
      canvasContext.fillRect(0, 0, canvasWidth.value, canvasHeight.value);

      // 先绘制一次确保底色显示
      console.log('[DEBUG] generatePoster: 绘制白色背景');
      canvasContext.draw(false, () => {
        console.log('[DEBUG] generatePoster: 白色背景绘制完成');

        // 第一步完成后，绘制背景图
        setTimeout(() => {
          console.log('[DEBUG] generatePoster: 开始绘制背景图片', posterImgInfo.path);
          canvasContext.drawImage(posterImgInfo.path, 0, 0, canvasWidth.value, canvasHeight.value);
          console.log('[DEBUG] generatePoster: 背景图片绘制完成');

          canvasContext.draw(true, () => {
            console.log('[DEBUG] generatePoster: 背景图绘制完成，准备绘制二维码');

            // 背景图绘制完成后，绘制二维码
            setTimeout(async () => {
              try {
                // 计算二维码在海报上的位置和大小 - 使用比例计算
                const scaleFactor = canvasWidth.value / posterImgInfo.width;

                // 根据海报类型和缩放因子调整二维码尺寸和位置
                const qrSize = mode.value === "promote"
                  ? Math.min(Math.floor(300 * scaleFactor), canvasWidth.value * 0.4) // 控制最大尺寸
                  : Math.min(Math.floor(360 * scaleFactor), canvasWidth.value * 0.4);

                // 计算水平位置，确保在画布内
                const qrX = mode.value === "promote"
                  ? Math.min(Math.floor(180 * scaleFactor), canvasWidth.value - qrSize)
                  : Math.min(Math.floor(360 * scaleFactor), canvasWidth.value - qrSize);

                // 计算垂直位置，确保在画布底部合适位置
                const qrY = mode.value === "promote"
                  ? canvasHeight.value - Math.min(Math.floor(480 * scaleFactor), canvasHeight.value * 0.4)
                  : canvasHeight.value - Math.min(Math.floor(1370 * scaleFactor), canvasHeight.value * 0.8);

                console.log('[DEBUG] generatePoster: 二维码参数', { qrX, qrY, qrSize, mode: mode.value, scaleFactor });

                // 3. 使用UQRCode生成二维码并绘制到画布
                // 创建uQRCode实例
                const qr = new UQRCode();
                // 设置二维码内容
                qr.data = generalUrl();
                // 设置二维码大小
                qr.size = qrSize;
                // 调用制作二维码方法
                qr.make();

                // 绘制QR码到指定位置
                // 获取绘制模块信息
                const drawModules = qr.getDrawModules();
                for (const drawModule of drawModules) {
                  if (drawModule.type === 'tile') {
                    canvasContext.setFillStyle(drawModule.color);
                    canvasContext.fillRect(
                      qrX + drawModule.x,
                      qrY + drawModule.y,
                      drawModule.width,
                      drawModule.height
                    );
                  }
                }

                // 4. 最终绘制，这次保留先前绘制的背景图
                canvasContext.draw(true, () => {
                  console.log('[DEBUG] generatePoster: 画布完整绘制完成');
                  posterGenerated.value = true;
                  uni.hideLoading();
                });
              } catch (error) {
                console.error('[DEBUG] generatePoster: 二维码生成异常', error);
                uni.hideLoading();
                uni.showToast({
                  title: '生成二维码失败',
                  icon: 'none'
                });
              }
            }, 300);
          });
        }, 300);
      });
    } catch (error) {
      console.error('[DEBUG] generatePoster: APP环境图片处理失败', error);
      uni.hideLoading();
      uni.showToast({
        title: '生成海报失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('[DEBUG] generatePoster: 生成海报发生未捕获异常', error);
    uni.hideLoading();
    uni.showToast({
      title: '生成海报失败',
      icon: 'none'
    });
  }
};

// 监听 show 变化，show 为 true 时生成海报
watch(show, (newVal) => {
  if (newVal && !posterGenerated.value) {
    generatePoster();  // 当弹窗显示且海报未生成时生成海报
  }
});

// 保存海报图片
const savePoster = () => {
  if (!posterGenerated.value) {
    uni.showToast({
      title: '海报生成中，请稍后再试',
      icon: 'none'
    });
    return;
  }

  uni.canvasToTempFilePath({
    canvasId: 'posterCanvas',
    width: canvasWidth.value,
    height: canvasHeight.value,
    destWidth: canvasWidth.value * 2, // 输出图片宽度为 canvas 宽度的2倍，提高清晰度
    destHeight: canvasHeight.value * 2, // 输出图片高度为 canvas 高度的2倍，提高清晰度
    success: (res) => {
      // 保存图片到相册
      uni.saveImageToPhotosAlbum({
        filePath: res.tempFilePath,
        success: () => {
          uni.showToast({
            title: '保存成功',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('保存失败:', err);
          // 如果是用户拒绝授权导致的
          if (err.errMsg && err.errMsg.includes('auth deny')) {
            uni.showModal({
              title: '提示',
              content: '需要您授权保存图片到相册',
              success: (res) => {
                if (res.confirm) {
                  uni.openSetting();
                }
              }
            });
          } else {
            uni.showToast({
              title: '保存失败',
              icon: 'none'
            });
          }
        }
      });
    },
    fail: (err) => {
      console.error('Canvas转图片失败:', err);
      uni.showToast({
        title: '保存失败',
        icon: 'none'
      });
    }
  }, instance.proxy);
};

// 分享到微信好友
const shareToWechatFriend = () => {
  if (!posterGenerated.value) {
    uni.showToast({
      title: '海报生成中，请稍后再试',
      icon: 'none'
    });
    return;
  }

  uni.canvasToTempFilePath({
    canvasId: 'posterCanvas',
    width: canvasWidth.value,
    height: canvasHeight.value,
    destWidth: canvasWidth.value * 2,
    destHeight: canvasHeight.value * 2,
    success: (res) => {
      // #ifdef APP-PLUS
      shareWithSystem('WXSceneSession', res.tempFilePath);
      // #endif

      // #ifndef APP-PLUS
      uni.showToast({
        title: '分享功能仅支持APP',
        icon: 'none'
      });
      // #endif
    },
    fail: (err) => {
      console.error('Canvas转图片失败:', err);
      uni.showToast({
        title: '分享准备失败',
        icon: 'none'
      });
    }
  }, instance.proxy);
};

// 分享到微信朋友圈
const shareToWechatMoments = () => {
  if (!posterGenerated.value) {
    uni.showToast({
      title: '海报生成中，请稍后再试',
      icon: 'none'
    });
    return;
  }

  uni.canvasToTempFilePath({
    canvasId: 'posterCanvas',
    width: canvasWidth.value,
    height: canvasHeight.value,
    destWidth: canvasWidth.value * 2,
    destHeight: canvasHeight.value * 2,
    success: (res) => {
      // #ifdef APP-PLUS
      shareWithSystem('WXSceneTimeline', res.tempFilePath);
      // #endif

      // #ifndef APP-PLUS
      uni.showToast({
        title: '分享功能仅支持APP',
        icon: 'none'
      });
      // #endif
    },
    fail: (err) => {
      console.error('Canvas转图片失败:', err);
      uni.showToast({
        title: '分享准备失败',
        icon: 'none'
      });
    }
  }, instance.proxy);
};

// 通用的分享处理函数
const shareWithSystem = (scene, tempFilePath) => {
  try {
    // 判断是否安装微信
    plus.share.getServices((services) => {
      const wechatService = services.find((s) => s.id === 'weixin');

      if (!wechatService) {
        uni.showToast({
          title: '未检测到微信应用',
          icon: 'none'
        });
        return;
      }

      // 判断微信是否认证
      wechatService.authorize(() => {
        const shareOptions = {
          provider: 'weixin',
          scene: scene, // WXSceneSession或WXSceneTimeline
          type: 2, // 图片类型
          imageUrl: tempFilePath,
          title: mode.value === "promote" ? '推广海报' : '邀请海报',
          href: generalUrl(),
          success: (res) => {
            uni.showToast({
              title: '分享成功',
              icon: 'success'
            });
          },
          fail: (err) => {
            console.error('分享失败:', err);
            uni.showToast({
              title: '分享失败',
              icon: 'none'
            });
          }
        };

        wechatService.send(shareOptions, () => {
          console.log('分享成功');
        }, (err) => {
          console.error('分享失败:', err);
        });
      }, (err) => {
        console.error('微信认证失败:', err);
        uni.showToast({
          title: '微信认证失败',
          icon: 'none'
        });
      });
    }, (err) => {
      console.error('获取分享服务列表失败:', err);

      // 如果获取服务失败，尝试使用系统分享
      try {
        plus.share.sendWithSystem({
          pictures: [tempFilePath]
        }, () => {
          uni.showToast({
            title: '分享成功',
            icon: 'success'
          });
        }, (err) => {
          uni.showToast({
            title: '分享失败',
            icon: 'none'
          });
        });
      } catch (e) {
        uni.showToast({
          title: '当前设备不支持分享',
          icon: 'none'
        });
      }
    });
  } catch (error) {
    console.error('分享出错:', error);
    uni.showToast({
      title: '分享失败',
      icon: 'none'
    });
  }
};

const generalUrl = () => {
  return url.value + encodeURIComponent(linkIdentifier.value);
};

const copyUrl = () => {
  uni.setClipboardData({
    data: generalUrl(),
    success: () => {
      uni.showToast({
        title: '链接已复制！',
        icon: 'success'
      });
    }
  });
};
</script>

<style lang="scss" scoped>
.divider {
  position: relative;
  display: flex;
  align-items: center;
  margin: 16px 0;
  color: #969799;
  font-size: 14px;

  &::before,
  &::after {
    content: '';
    height: 1px;
    flex: 1;
    background-color: #ebedf0;
  }

  &::before {
    margin-right: 16px;
  }

  &::after {
    margin-left: 16px;
  }
}
</style>
