var util = require('../../utils/util.js'); // 确保你有这样一个文件
var app = getApp(),
  n = '';
Page({
  data: {
    dataUrl: '',
    dataImage: '',
    preview: '',
    type: '',
    wxid: '',
    alias: '',
    videoSize: 0, // 初始化视频大小为0
    totalLength: 0,
    isExtracting: false,
    read_count: 0,

  },
  onLoad: function (options) {
    console.log(options)
    this.setData({
      dataUrl: decodeURIComponent(options.url), // 视频链接
      dataImage: decodeURIComponent(options.image) || '', // 视频封面
      preview: decodeURIComponent(options.preview), // 视频标题
      type: decodeURIComponent(options.type) || '', // 设置type的值
      wxid: decodeURIComponent(options.wxid) || '', // 设置微信id
      alias: decodeURIComponent(options.alias) || '', // 设置微信号
      read_count: decodeURIComponent(options.read_count) || 0, // 设置微信号
    });
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })

  },
  onShow: function () {

    app.checkUpdateVersion()
    // 页面显示前更新数据
    console.log('执行video.js onShow')
    app.getPopupConfig()
    .then(() => {
      // 从本地缓存读取数据
      const isEnabled = wx.getStorageSync('popupEnabled');
      const popupType = wx.getStorageSync('popupType');
      const popupContent = wx.getStorageSync('popupContent');

      if (isEnabled) {
        this.setData({
          showPopup: true,
          popupType: popupType,
          popupContent: popupContent
        });
      }
    })
    .catch((error) => {
      console.error('获取弹窗配置失败:', error);
    });
    console.log(this.data.type)
    app.getUserInfo().then(() => {
      console.log('获取用户信息开始');
      console.log(wx.getStorageSync('defaultDailyFreeParseNum'), )
      // 判断type，并发送提取记录到后端
      if (this.data.type === 'weixin' & wx.getStorageSync('defaultDailyFreeParseNum') > 0) {
        console.log('来源微信')
        this.getVideoSize(decodeURIComponent(this.data.dataUrl))
        //更新次数
      } else {
        this.getVideoSize(app.globalData.downloadPrefix + decodeURIComponent(this.data.dataUrl))
      }
      console.log('获取用户信息结束');
    }).catch(error => {
      console.error('获取用户信息失败:', error);
    }).finally(() => {
      console.log('getUserInfo调用完成');
    });
    wx.showToast({
      title: '提取成功',
      icon: 'success',
      duration: 1500,
    });

  },

  updateExtractingStatus: function (status) {
    console.log(status)
    this.setData({
      isExtracting: status,
    });
  },



  getVideoSize: function (url) {
    let that = this;
    wx.request({
      url: url,
      method: 'HEAD', // HEAD请求不会下载资源的body，只请求header信息
      success: function (res) {
        if (res.statusCode === 200 && res.header['CONTENT-LENGTH'] || res.header['X-Content-Length']) {
          let size = res.header['CONTENT-LENGTH'] || res.header['X-Content-Length'];
          let sizeInMb = (size / (1024 * 1024)).toFixed(2); // 将大小转换为MB
          that.setData({
            videoSize: sizeInMb, // 更新页面数据,
            totalLength: size
          });
        }
      },
      fail: function (err) {
        console.log('获取视频大小失败', err);
      }
    });
  },
  //复制
  copyUrl: async function () {
    if (this.data.type == 'weixin') {
      wx.showLoading({
        title: '正在请求复制...',
      });
      if (!await this.CreditLimit()) return
    }
    wx.setClipboardData({
      data: this.data.dataUrl,
      success: () => {
        wx.showToast({
          title: '复制成功',
          duration: 2200,
        });
      },
    });
  },

  // 扣除额度
  CreditLimit() {
    return new Promise((resolve, reject) => {
      app.apiRequest({
        url: '/myapp/increment-download-count/',
        method: "POST",
        data: {
          uuid: wx.getStorageSync("uuid"),
          openid: wx.getStorageSync("openid")
        },
        success: function (e) {
          console.log(e, !e.data.success)
          if (e.data.success === false) {
            wx.hideLoading()
            wx.showModal({
              title: "提取视频",
              content: '哎呀！去开通会员不限次数使用哦',
              confirmColor: "#00B269",
              cancelColor: "#858585",
              success: function (e) {
                e.confirm ? (console.log("确定"), wx.navigateTo({
                  url: "../vip_recharge/vip_recharge?show=true"
                })) : e.cancel && console.log("取消");
              }
            })
            resolve(false)
          }
          resolve(true)
        }
      })
    })
  },
  onAdClick: function() {
    app.广告();
},
  //提取视频
  download: async function () {
    wx.showLoading({
      title: '正在下载...',
    });
    if (this.data.type == 'weixin') {
      if (!await this.CreditLimit()) return
    }
    var t = this,
      e = t.data.dataUrl;
    if (t.data.type === 'index') {
      e = app.globalData.downloadPrefix + t.data.dataUrl; // 通过nginx中转
    } else {
      e = t.data.dataUrl;
    }
    // 开始实际的下载任务
    const downloadTask = wx.downloadFile({
      url: e,
      success: function (o) {
        wx.hideLoading();
        wx.saveVideoToPhotosAlbum({
          filePath: o.tempFilePath,
          success: function (o) {
            t.showToast('保存成功', 'success');
            setTimeout(function () {
              wx.setClipboardData({
                data: '',
              });
              t.goBack();
            }, 1000);
          },
          fail: function (o) {
            t.showToast('保存失败');
          }
        });
      },
      fail: function (o) {
        wx.hideLoading();
        t.showToast('下载失败');
      }
    });

    // 监听下载进度并计算百分比
    downloadTask.onProgressUpdate((o) => {
      let percent = this.data.totalLength ? (o.totalBytesWritten / this.data.totalLength) * 100 : o.progress;
      if (percent < 100) {
        wx.showToast({
          title: `保存中 ${Math.round(percent)}%`,
          mask: true, // 添加 mask 参数，保证覆盖式显示
          icon: 'loading'
        });
      } else {
        wx.hideLoading(); // 下载完成后隐藏加载提示
      }
    });
  },

  // showToast: function (title, icon = 'none') {
  //   wx.showToast({
  //     title: title,
  //     icon: icon,
  //     duration: 2000
  //   });
  // },



  // 保存到相册
  postSave: function () {

    var that = this;
    wx.getSetting({
      success(res) {
        // 检查用户是否已授权小程序写入相册的权限
        if (res.authSetting['scope.writePhotosAlbum']) {
          // 用户已授权，下载视频
          that.download();
        } else {
          // 用户未授权，请求相册权限
          wx.authorize({
            scope: 'scope.writePhotosAlbum',
            success() {
              // 用户授权成功，下载视频
              that.download();
            },
            fail() {
              // 用户拒绝授权，显示提示对话框引导用户开启权限
              wx.showModal({
                title: '提示',
                content: '保存视频到相册需要您授权',
                showCancel: false,
                success(modalRes) {
                  if (modalRes.confirm) {
                    // 引导用户前往设置页面手动开启权限
                    wx.openSetting({
                      success(settingData) {
                        if (settingData.authSetting['scope.writePhotosAlbum']) {
                          // 用户在设置页面授权成功，下载视频
                          that.download();
                        } else {
                          // 用户最终未授权，可能需要展示一些提示信息
                          wx.showToast({
                            title: '授权失败，无法保存视频',
                            icon: 'none'
                          });
                        }
                      }
                    });
                  }
                }
              });
            }
          });
        }
      }
    });

  },


  performDownload: function () {
    // 在这里实现下载视频并保存到相册的逻辑
    this.download();
  },


  removeTimestampAndMergeLines: function (textWithTimestamp) {
    let txt = textWithTimestamp.replace(/\[.*\]/g, ""); // 去掉时间前缀
    console.log(txt);
    txt = txt.replace(/\s+/g, ""); // 去掉换行、空格字符
    console.log(txt);
    return txt; // 删除前后的空白字符并返回
  },

  // 提取文案功能
  extractText: function () {
    // if (this.data.videoSize > 300 || !this.data.videoSize) {
    //   wx.showToast({
    //     title: '视频太大，无法提取',
    //     icon: 'none'
    //   })
    //   return
    // }
    let openid = wx.getStorageSync('openid') || '';
    let uuid = wx.getStorageSync('uuid') || '';
    let type = this.data.type || '';
    let wxid = this.data.wxid || '';
    let alias = this.data.alias || '';
    let url = this.data.dataUrl;
    console.log('文案提取：' + url);
    wx.showLoading({
      title: '后台处理中',
    });
    var that = this;
    app.apiRequest({
      url: '/myapp/video_to_text/', // 后端接口URL，根据实际情况调整
      method: 'POST',
      header: {
        'content-type': 'application/json',
      },
      data: {
        url: url,
        openid: openid,
        uuid: uuid,
        type: type,
        wxid: wxid,
        alias: alias,
      },
      success(res) {
        if (res.data.success === false) {
          wx.showModal({
            title: "提取视频",
            content: '哎呀！去开通会员不限次数使用哦',
            confirmColor: "#00B269",
            cancelColor: "#858585",
            success: function (e) {
              e.confirm ? (console.log("确定"), wx.navigateTo({
                url: "../vip_recharge/vip_recharge?show=true"
              })) : e.cancel && console.log("取消");
            }
          })
          wx.hideLoading()
          return
        }
        let data = res.data;
        let taskId = (data?.Data?.TaskId) || data.task_id;
        if (data.result) {
          wx.hideLoading();
          let text = that.removeTimestampAndMergeLines(data.result);
          text = encodeURIComponent(text);
          wx.navigateTo({
            url: "../extract/extract?text=" + text + "&type=" + type + "&wxid=" + wxid + "&alias=" + alias,
          });

        } else if (taskId) {
          that.search_result(taskId, openid, uuid, type, wxid, alias, (result) => {
            wx.hideLoading();
            console.log('处理查询结果:', result);
            if (result != 0) {
              wx.showToast({
                title: '提取成功',
                icon: 'success'
              });

              let text = that.removeTimestampAndMergeLines(result);
              text = encodeURIComponent(text);
              wx.navigateTo({
                url: "../extract/extract?text=" + text + "&type=" + type + "&wxid=" + wxid + "&alias=" + alias,
              });
            } else {
              wx.showToast({
                title: '异常',
                icon: 'error'
              });
            }
          });
        } else {
          wx.showToast({
            title: '发送文件失败',
            icon: 'none'
          });
        }
      },
      fail(err) {
        wx.hideLoading();
        wx.showToast({
          title: '网络异常',
          icon: 'none'
        });
      }
    });
  },

  // 查询任务状态
  search_result: function (task_id, openid, uuid, type, wxid, alias, handleResult) {
    console.log('查询任务');
    const checkResult = (maxRetries) => {
      const fetchTaskStatus = () => {
        app.apiRequest({
          url: '/myapp/query_task/',
          method: 'POST',
          header: {
            'content-type': 'application/json',
          },
          data: {
            task_id: task_id,
            openid: openid,
            uuid: uuid,
            type: type,
            wxid: wxid,
            alias: alias,
          },
          success: function (res) {
            const data = res.data;
            console.log('查询任务：', data)
            if (data.result) {
              handleResult(data.result);
            } else if (maxRetries > 0) {
              setTimeout(fetchTaskStatus, 3000); // 每3秒查询一次
              maxRetries--;
            } else {
              wx.hideLoading();
              wx.showToast({
                title: '请稍重试',
                icon: 'error'
              });
              handleResult(0);
              console.log('已达到最大重试次数，停止查询。');
            }
          },
        });
      };
      fetchTaskStatus(); // 启动任务状态查询
    };

    const maxRetries = 100;
    checkResult(maxRetries);
  },

  // 去掉时间戳并合并行
  removeTimestampAndMergeLines: function (textWithTimestamp) {
    let txt = textWithTimestamp.replace(/\[.*\]/g, ""); // 去掉时间前缀
    console.log(txt);
    txt = txt.replace(/\s+/g, ""); // 去掉换行、空格字符
    console.log(txt);
    return txt; // 删除前后的空白字符并返回
  },

  // 更新提取状态
  updateExtractingStatus: function (status) {
    this.setData({
      extracting: status
    });
  },
  onUnload: function () {
    console.log('页面卸载');
  },
  goBack: function () {
    wx.reLaunch({
      url: '/pages/index/index',
    });
  },

  showToast: function (title, icon = 'none', duration = 2000) {
    wx.showToast({
      title: title,
      icon: icon,
      duration: duration
    });
  },


  onShareAppMessage: function () {
    return {
      title: '推荐一款免费又超好用的视频文案创作工具，分享给大家一起使用',
      path: '/pages/index/index?uuid=' + wx.getStorageSync('uuid'),
      imageUrl: '/images/1.png',
      success: function (e) {
        wx.showToast({
          title: "分享成功",
          icon: "success",
          duration: 2e3
        });
      },
      fail: function (e) {
        wx.showToast({
          title: "分享失败",
          icon: "none",
          duration: 2e3
        });
      }
    }
  },
  onShareTimeline: function () {
    return {
      title: '推荐一款免费又超好用的视频文案创作工具，分享给大家一起使用',
      path: '/pages/index/index?uuid=' + wx.getStorageSync('uuid'),
      imageUrl: '/images/1.png',
      success: function (e) {
        wx.showToast({
          title: "分享成功",
          icon: "success",
          duration: 2e3
        });
      },
      fail: function (e) {
        wx.showToast({
          title: "分享失败",
          icon: "none",
          duration: 2e3
        });
      }
    }
  },


  // 发送提取记录到后端的方法 
  sendExtractionRecordToBackend: function (e) {
    const {
      dataUrl,
      dataImage,
      preview,
      wxid,
      alias
    } = this.data;
    app.apiRequest({
      url: '/myapp/record_extraction/', // 后端接口URL
      method: 'POST',
      data: {
        openid: wx.getStorageSync('openid'),
        uuid: wx.getStorageSync('uuid'),
        videoUrl: dataUrl,
        videoTitle: preview,
        wxid: wxid,
        wechatAlias: alias,
        type: e || 'weixin'
      },
      success(res) {
        console.log('提取记录发送成功', res);
        // 可以在这里处理后端返回的响应
      },
      fail(err) {
        console.error('提取记录发送失败', err);
        // 错误处理
      }
    });
  },
});