<template>
  <view class="share">
    <!-- 海报内容区域 -->
    <view class="bg_color_fff border_radius_20 save-area" id="saveArea">
      <view class="merchant-info">
        <image class="merchant-logo" :src="merchantInfo.merchantLogo" mode="aspectFill"></image>
        <view class="merchant-detail">
          <view class="merchant-name">{{merchantInfo.merchantNameNew}}</view>
        </view>
      </view>
      <view class="big-merchant-logo">
        <image class="merchant-logo" :src="merchantInfo.merchantLogo" mode="aspectFill"></image>
      </view>
      <view class="qrCodeInfo">
        <view class="left">
          <view class="title">{{ merchantInfo.merchantDescribeNew }}</view>
          <view class="subTitle">扫码加入<text class="dot"></text>{{merchantInfo.merchantNameNew}}</view>
        </view>
        <view class="right">
          <image class="qrCode" :src="qrCode" mode="widthFix"></image>
        </view>
      </view>
    </view>

    <!-- 操作按钮 -->
    <view class="flex-center-between padding30">
      <view class="order_btn flex-center save-btn" @click="saveToAlbum">
        <view class="flex-center-between">
          <image
              src="/static/img/xiazai.png"
              mode="widthFix"
              class="share_img mr20"
          ></image>
          <text>保存海报</text>
        </view>
      </view>
      <button class="order_btn flex-center share-btn" open-type="share">
        <view class="flex-center-between">
          <image
              src="/static/img/fenxiang_w.png"
              mode="widthFix"
              class="share_img mr20"
          ></image>
          <text>分享海报</text>
        </view>
      </button>
    </view>

    <!-- 用于绘制海报的Canvas -->
    <canvas
        canvas-id="posterCanvas"
        id="posterCanvas"
        style="position: fixed; top: -9999px; left: -9999px;"
        :style="{ width: canvasWidth + 'px', height: canvasHeight + 'px' }"
    ></canvas>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { onLoad } from "@dcloudio/uni-app";
import { getQrcode } from "@/api/user.js"

// 响应式数据
const merchantInfo = ref({})
const qrCode = ref("")
const canvasWidth = ref(600) // 根据参考图片调整宽度
const canvasHeight = ref(800) // 根据参考图片调整高度

// 获取二维码方法
const QRCodeGenerationFn = async () => {
  uni.showLoading({ title: "正在获取二维码..." })
  try {
    let data = {
      id: merchantInfo.value.id
    }
    const response = await getQrcode(data)
    console.log("getQrcode", response)
    qrCode.value = response.message
  } catch (err) {
    console.error("获取二维码失败", err)
    uni.showToast({ title: "获取二维码失败", icon: "none" })
  } finally {
    uni.hideLoading()
  }
}

// 绘制圆角矩形
const drawRoundRect = (ctx, x, y, width, height, radius) => {
  ctx.beginPath()
  ctx.moveTo(x + radius, y)
  ctx.arcTo(x + width, y, x + width, y + height, radius)
  ctx.arcTo(x + width, y + height, x, y + height, radius)
  ctx.arcTo(x, y + height, x, y, radius)
  ctx.arcTo(x, y, x + width, y, radius)
  ctx.closePath()
}

// 绘制圆角图片
const drawRoundImage = (ctx, imgPath, x, y, width, height, radius) => {
  // 保存当前状态
  ctx.save()

  // 创建圆角路径
  drawRoundRect(ctx, x, y, width, height, radius)
  ctx.clip()

  // 绘制图片
  ctx.drawImage(imgPath, x, y, width, height)

  // 恢复状态
  ctx.restore()
}

// 保存海报到相册
const saveToAlbum = async () => {
  uni.showLoading({ title: "正在生成海报..." })

  try {
    // 检查必要的图片资源
    if (!merchantInfo.value.merchantLogo) {
      throw new Error("商家Logo不能为空")
    }

    if (!qrCode.value) {
      throw new Error("二维码不能为空")
    }

    // 创建 Canvas 上下文
    const ctx = uni.createCanvasContext('posterCanvas', getCurrentInstance())

    // 1. 绘制白色背景
    ctx.setFillStyle("#ffffff")
    ctx.fillRect(0, 0, canvasWidth.value, canvasHeight.value)

    // 3. 加载并绘制商家Logo（小头像）
    await new Promise((resolve, reject) => {
      uni.getImageInfo({
        src: merchantInfo.value.merchantLogo,
        success: (logoRes) => {
          // 绘制圆形商家头像
          const avatarSize = 80
          const avatarX = 60
          const avatarY = 60
          const radius = 10 // 设置圆角半径为10

          // ctx.drawImage(logoRes.path, avatarX, avatarY, avatarSize, avatarSize)
          // ctx.restore()
          drawRoundImage(ctx, logoRes.path, avatarX, avatarY, avatarSize, avatarSize, radius)

          resolve()
        },
        fail: (err) => {
          reject(new Error('获取商家Logo失败: ' + err.errMsg))
        }
      })
    })

    // 4. 绘制商家名称
    const merchantName = merchantInfo.value.merchantNameNew || "商家名称"
    ctx.setFontSize(28)
    ctx.setFillStyle("#333333")
    ctx.setTextAlign("left")
    ctx.fillText(merchantName, 160, 110)

    // 5. 绘制主体内容区域
    const contentStartY = 200

    // 6. 加载并绘制商家Logo（大头像）
    await new Promise((resolve, reject) => {
      uni.getImageInfo({
        src: merchantInfo.value.merchantLogo,
        success: (logoRes) => {
          // 绘制圆形商家头像
          const avatarSize = 400
          const avatarX = 100
          const avatarY = contentStartY
          const radius = 10
          // ctx.drawImage(logoRes.path, avatarX, contentStartY, avatarSize, avatarSize)
          // ctx.restore()
          drawRoundImage(ctx, logoRes.path, avatarX, avatarY, avatarSize, avatarSize, radius)

          resolve()
        },
        fail: (err) => {
          reject(new Error('获取商家Logo失败: ' + err.errMsg))
        }
      })
    })

    // 9. 绘制"好久不见"标题
    const bottomStartY = contentStartY + 80+400
    ctx.setFontSize(32)
    ctx.setFillStyle("#333333")
    ctx.setTextAlign("left")
    ctx.fillText(merchantInfo.value.merchantDescribeNew, 40, bottomStartY)

    // 10. 绘制副标题
    ctx.setFontSize(20)
    ctx.setFillStyle("#787878")
    const subTitle = `扫码加入 · ${merchantInfo.value.merchantNameNew}`
    ctx.fillText(subTitle, 40, bottomStartY + 50)

    // 11. 加载并绘制二维码
    await new Promise((resolve, reject) => {
      uni.getImageInfo({
        src: qrCode.value,
        success: (qrRes) => {
          const qrSize = 150
          const qrX = canvasWidth.value-210;
          const qrY = contentStartY+400+20
          ctx.drawImage(qrRes.path, qrX, qrY, qrSize, qrSize)
          ctx.restore()

          resolve()
        },
        fail: (err) => {
          reject(new Error('获取二维码失败: ' + err.errMsg))
        }
      })
    })


    // 等待绘制完成
    await new Promise((resolve) => {
      ctx.draw(false, () => {
        setTimeout(() => {
          resolve()
        }, 800) // 增加等待时间确保绘制完成
      })
    })

    // 13. 导出Canvas为临时文件
    const tempFilePath = await new Promise((resolve, reject) => {
      uni.canvasToTempFilePath({
        canvasId: 'posterCanvas',
        fileType: 'png',
        quality: 1,
        width: canvasWidth.value,
        height: canvasHeight.value,
        success: (res) => {
          resolve(res.tempFilePath)
        },
        fail: (err) => {
          reject(new Error('生成图片失败: ' + err.errMsg))
        }
      }, getCurrentInstance())
    })

    // 14. 保存到相册
    await new Promise((resolve, reject) => {
      uni.saveImageToPhotosAlbum({
        filePath: tempFilePath,
        success: () => {
          resolve()
        },
        fail: (err) => {
          if (err.errMsg.includes('auth deny') || err.errMsg.includes('auth denied')) {
            uni.showModal({
              title: '提示',
              content: '需要授权保存图片到相册',
              showCancel: false,
              confirmText: '去设置',
              success: () => {
                uni.openSetting()
              }
            })
          }
          reject(new Error('保存失败: ' + err.errMsg))
        }
      })
    })

    uni.hideLoading()
    uni.showToast({ title: '保存成功', icon: 'success' })

  } catch (error) {
    uni.hideLoading()
    console.error('保存海报失败:', error)
    uni.showToast({
      title: error.message || '保存失败',
      icon: 'none',
      duration: 3000
    })
  }
}

// 页面加载时获取二维码
onLoad((options) => {
  if (options.merchantInfo) {
    merchantInfo.value = JSON.parse(decodeURIComponent(options.merchantInfo))
    merchantInfo.value.merchantName="一号商家一号商家一号商家一号商家一号商家一号商家一号商家一号商家一号商家一号商家一号商家一号商家"
    merchantInfo.value.merchantDescribe="一号商家一号商家一号商家一号商家一号商家一号商家一号商家一号商家一号商家一号商家一号商家一号商家"
    // 修正语法错误
    merchantInfo.value.merchantNameNew = truncateText(merchantInfo.value.merchantName, 10) || ''
    merchantInfo.value.merchantDescribeNew = truncateText(merchantInfo.value.merchantDescribe, 10) || ''
        qrCode.value = merchantInfo.value.merchantCodeUrl || ''

    if (!qrCode.value) {
      QRCodeGenerationFn()
    }
  }
})

// 分享功能
const onShareAppMessage = () => {
  let keyInfo = `merchantCode=${merchantInfo.value?.merchantCode}`
  keyInfo = encodeURIComponent(keyInfo)
  return {
    title: `快来加入${merchantInfo.value?.merchantName || '我们'}~`,
    desc: merchantInfo.value.merchantDescribeNew,
    path: `/pages/index/index?scene=${keyInfo}`
  }
}
// 添加文本截取函数
const truncateText = (text, maxLength) => {
  if (!text) return ''
  if (text.length <= maxLength) return text
  return text.substring(0, maxLength) + '...'
}
// 暴露给模板
defineExpose({
  onShareAppMessage
})
</script>

<style lang="scss" scoped>
.share {
  padding: 30rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
  box-sizing: border-box;

  .save-area {
    padding: 40rpx;
    box-sizing: border-box;
    position: relative;
    margin-bottom: 30rpx;
  }

  .logo_img {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
  }

  .share_img {
    width: 40rpx;
    height: 40rpx;
  }

  .order_btn {
    padding: 20rpx;
    width: 45%;
    text-align: center;
    font-size: 32rpx;
    color: white;
    border-radius: 12rpx;
    border: none;
    background: #f0ad4e;
  }
}

.merchant-info {
  display: flex;
  align-items: center;
  margin-bottom: 30rpx;

  .merchant-logo {
    width: 120rpx;
    height: 120rpx;
    border-radius: 12rpx;
    margin-right: 30rpx;
  }

  .merchant-detail {
    flex: 1;

    .merchant-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
  }
}

.big-merchant-logo {
  display: flex;
  width: 100%;
  justify-content: center;
  align-items: center;
  margin: 60rpx 0;

  .merchant-logo {
    width: 400rpx;
    height: 400rpx;
    border-radius: 20rpx;
    box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.1);
  }
}

.border_radius_20 {
  border-radius: 20rpx;
}

.bg_color_fff {
  background-color: #ffffff;
}

.qrCodeInfo {
  display: flex;
  align-items: center;
  margin-top: 60rpx;

  .left {
    flex: 1;

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      line-height: 60rpx;
      margin-bottom: 16rpx;
    }

    .subTitle {
      font-size: 28rpx;
      color: #666;
      line-height: 40rpx;

      .dot {
        display: inline-block;
        vertical-align: middle;
        height: 8rpx;
        width: 8rpx;
        border-radius: 50%;
        background-color: #666;
        margin: 0 16rpx;
      }
    }
  }

  .right {
    width: 160rpx;
    text-align: center;

    .qrCode {
      width: 100%;
      border-radius: 12rpx;
    }
  }
}

.flex-center-between {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.padding30 {
  padding: 30rpx 0;
}

.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}

.mr20 {
  margin-right: 20rpx;
}
</style>