// pages/guicangDetails/index.js

import drawQrcode from 'weapp-qrcode';
import { getwxml, style } from './shareJson.js';
const { request, cosBaseUrl, fileBaseURL } = require('../../utils/newServices');

Page({
  data: {
    id: null,
    itemDetail: null,
    h5Url: 'https://test.4dmuseum.cn/swkzModel/index.html',
    boxTop: 0,
    windowHeight: 0,
    isFullScreen: false,
    startY: 0,
    moveY: 0,
    showSharePopup: false,
    shareUrl: 'https://test.4dmuseum.cn/swkzModel/index.html',
    qrCodeUrl: '',
    shareImagePath: '',
    width: 0,
    height: 0,
    container: null,
    showAppBanner: true, // 控制下载APP提示栏显示
  },

  onLoad: function(options) {
    if (options.id) {
      this.setData({
        id: options.id
      });
      this.loadItemDetail(options.id);
    }
    
    // 获取屏幕高度
    const systemInfo = wx.getSystemInfoSync();
    const windowHeight = systemInfo.windowHeight;
    
    this.setData({
      windowHeight: windowHeight,
      boxTop: windowHeight * 0.8 // 初始位置在屏幕60%的位置
    });
  },
  // 初始化 wxml-to-canvas
  initCanvas: function() {
    const that = this;
    that.widget = this.selectComponent('.widget');
    this.generateShareImage();
  },
  // 加载详情数据
  loadItemDetail: function(id) {
    if (!id) return;
    
    // 显示加载状态
    wx.showLoading({
      title: '加载中...'
    });
    
    // 调用详情接口
    request.getAntiqueDetail(
      {},
      'GET',
      (res) => {
        wx.hideLoading();
        console.log('详情数据加载成功:', res);
        if (res.data && res.data.data) {
          const detail = res.data.data;
          const itemDetail = {
            id: detail.id,
            title: detail.name,
            date: detail.createTime ? detail.createTime.split(' ')[0] : '',
            source: detail.source || '归藏',
            description: detail.description || '',
            dimensions: detail.dimensions || detail.size,
            material: detail.material,
            imageUrl: cosBaseUrl + detail.coverImgUrl,
            file: cosBaseUrl + detail.fileList.find(file => file.name.includes('usdz')).url,
            h5Url: `${fileBaseURL}?m=${cosBaseUrl + detail.fileList.find(file => file.name.includes('usdz')).url}`,
            shareUrl: `${fileBaseURL}?m=${cosBaseUrl + detail.fileList.find(file => file.name.includes('usdz')).url}`,
          };
          console.log(itemDetail);
          this.setData({
            itemDetail: itemDetail
          });
        }
      },
      (err) => {
        wx.hideLoading();
        console.error('详情数据加载失败:', err);
      }
    );
  },

  // 打开H5页面
  openH5Page: function() {
    // 使用web-view内嵌打开H5页面
    wx.navigateTo({
      url: `/pages/webview/index?url=${encodeURIComponent(this.data.itemDetail.h5Url)}`
    });
  },

  // 触摸开始事件
  touchStart: function(e) {
    this.setData({
      startY: e.touches[0].clientY
    });
  },

  // 触摸移动事件
  touchMove: function(e) {
    const moveY = e.touches[0].clientY;
    const diff = moveY - this.data.startY;
    
    // 计算新的boxTop位置
    let newBoxTop = this.data.boxTop + diff;
    
    // 限制上下边界
    if (newBoxTop < this.data.windowHeight * 0.1) {
      newBoxTop = this.data.windowHeight * 0.1;
    } else if (newBoxTop > this.data.windowHeight * 0.7) {
      newBoxTop = this.data.windowHeight * 0.7;
    }
    
    this.setData({
      boxTop: newBoxTop,
      startY: moveY
    });
  },

  // 触摸结束事件
  touchEnd: function(e) {
    // 判断是否切换到全屏模式
    if (this.data.boxTop < this.data.windowHeight * 0.4) {
      this.setData({
        boxTop: this.data.windowHeight * 0.1,
        isFullScreen: true
      });
    } else {
      this.setData({
        boxTop: this.data.windowHeight * 0.8,
        isFullScreen: false
      });
    }
  },

  // 分享功能
  onShareAppMessage: function() {
    return {
      title: this.data.itemDetail ? this.data.itemDetail.title : '文物详情',
      path: '/pages/guicangDetails/index?id=' + this.data.id
    };
  },
  
  // 分享按钮点击事件
  shareItem: function() {
    this.setData({
      showSharePopup: true
    });
    this.showQRCode();
    setTimeout(() => {
      this.initCanvas();
    }, 1000)
    },
    // 关闭分享弹窗
    closeSharePopup: function() {
      this.setData({
        showSharePopup: false,
        shareImagePath: '',
      });
    },
  // 生成分享图片
  generateShareImage: function() {
    const that = this;
    if (!that.widget) {
      wx.showToast({
        title: 'wxml-to-canvas 组件未初始化',
        icon: 'none'
      });
      console.error('wxml-to-canvas 组件未初始化');
      return;
    }
    let wxml = getwxml(that.data.qrcodeUrl, this.data.itemDetail.title, this.data.itemDetail.imageUrl);
    console.log(wxml, 'wxml');
    // 设置要绘制的 WXML 节点
    that.widget.renderToCanvas({wxml, style}).then((res) => {
      // 将 canvas 转为图片
      that.container = res
      that.extraImage()
    }).catch((err) => {
      console.error('渲染 canvas 失败', err);
      wx.showToast({
        title: `${err}`,
        icon: 'none'
      });
    });
  },
  extraImage() {
    const p2 = this.widget.canvasToTempFilePath()
    p2.then(res => {
      this.setData({
        shareImagePath: res.tempFilePath,
      })
    })
  },
  // 生成二维码
  showQRCode() {
    let that = this;
    let url = 'https://3d-usdz.4dkankan.com/index.html?m=13719751007/captureModel/202503131501024131/data'
    drawQrcode({
        width: 72,
        height: 72,
        canvasId: 'myQrcode',
        text: url,
        correctLevel: 3
      })

    // 创建一个选择器查询对象
    const query = wx.createSelectorQuery();
    // 执行查询并获取 canvas 节点的实例
    query.select('#myQrcode').boundingClientRect()
    // 查询结束后执行回调函数
    query.exec((res) => {
      if (res[0]) {
        // res[0] 是 canvas 节点信息，确保节点存在
        wx.canvasToTempFilePath({
          canvasId: 'myQrcode',
          success(res) {
            const tempFilePath = res.tempFilePath;
            console.log(tempFilePath);
            that.setData({
              qrcodeUrl: tempFilePath
            })
          },
          fail(err) {
            console.error( err);
          }
        });
      } else {
        console.error('未能找到对应的 canvas 节点');
      }
    });
  },
  // 保存图片到本地
  saveToLocal: function() {
    const that = this;
    if (!that.data.shareImagePath) {
      wx.showToast({
        title: '图片生成中，请稍候',
        icon: 'none'
      });
      return;
    }
    
    // 获取保存图片到相册的权限
    wx.getSetting({
      success: function(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success: function() {
              that.saveImageToAlbum();
            },
            fail: function() {
              wx.showModal({
                title: '提示',
                content: '需要您授权保存图片到相册',
                showCancel: false,
                success: function() {
                  wx.openSetting();
                }
              });
            }
          });
        } else {
          that.saveImageToAlbum();
        }
      }
    });
  },
  // 保存图片到相册
  saveImageToAlbum: function() {
    const that = this;
    wx.saveImageToPhotosAlbum({
      filePath: that.data.shareImagePath,
      success: function() {
        wx.showToast({
          title: '保存成功',
          icon: 'success'
        });
      },
      fail: function() {
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    });
  },
  // 复制链接
  copyLink: function() {
    wx.setClipboardData({
      data: this.data.shareUrl,
      success: function() {
        wx.showToast({
          title: '链接已复制',
          icon: 'success'
        });
      }
    });
  },

  // 分享到微信好友
  shareToWechat: function() {
    if (!this.data.shareImagePath) {
      wx.showToast({
        title: '图片生成中，请稍候',
        icon: 'none'
      });
      return;
    }
    
    wx.showShareImageMenu({
      path: this.data.shareImagePath
    })
  },

  // 分享到朋友圈
  shareToTimeline: function() {
    if (!this.data.shareImagePath) {
      wx.showToast({
        title: '图片生成中，请稍候',
        icon: 'none'
      });
      return;
    }
    
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareTimeline']
    });
  },

  // 分享给朋友（小程序自带分享功能）
  onShareAppMessage: function() {
    return {
      title: this.data.itemDetail ? this.data.itemDetail.title : '文物详情',
      path: '/pages/guicangDetails/index?id=' + this.data.id,
      imageUrl: this.data.shareImagePath || ''
    };
  },

  // 关闭下载APP提示栏
  closeAppBanner: function() {
    this.setData({
      showAppBanner: false
    });
  },

  // 下载APP - 跳转到webview页面
  downloadApp: function() {
    const downloadUrl = 'https://test.4dmuseum.cn/admin/swkzMobile.html';
    
    wx.navigateTo({
      url: `/pages/webview/index?url=${encodeURIComponent(downloadUrl)}`
    });
  }
})