const app = getApp();

Page({
    data: {
        mode: 'link', // 默认模式为链接提取
        videoUrl: '', // 视频链接
        uploadFilePath: '', // 上传文件路径
        uuid: '', // 页面参数 uuid
        showPopup: false, // 弹窗显示状态
        popupType: '', // 弹窗类型
        popupContent: '', // 弹窗内容
        showMask: false,
        records: [],
        page: 1,
        isLoading: false,
        hasMore: true,
        externalOpenid:''
    },

    // 切换单选框模式
    switchMode(e) {
        const selectedMode = e.currentTarget.dataset.value; // 获取当前点击的值
        console.log("选择的模式：", selectedMode);
        this.setData({
            mode: selectedMode
        });
    },

    // 输入视频链接
    bindVideoInput(e) {
        this.setData({
            videoUrl: e.detail.value // 更新输入的视频链接
        });
    },

//文案提取记录
  // 显示记录蒙版
  showRecordMask() {
    this.setData({ showMask: true });
    console.log('显示记录蒙版')
    this.loadRecords();
},

// 隐藏蒙版
hideMask() {
    this.setData({ showMask: false });
},

// 阻止冒泡
preventDefault() {
    return;
},

// 加载记录
// 加载记录
// 加载记录
loadRecords() {
  if (this.data.isLoading || !this.data.hasMore) return;
  
  this.setData({ isLoading: true });
  
  app.apiRequest({
      url: '/myapp/get_transcription_records/',
      method: "POST",
      data: {
          page: this.data.page,
          uuid: wx.getStorageSync("uuid"),
          openid: wx.getStorageSync("openid")
      },
      success: (res) => {
          console.log('原始数据:', res.data);
          
          if (!res.data || !res.data.records) {
              console.error('返回数据格式错误');
              return;
          }

          // 获取当前records
          const currentRecords = this.data.records || [];
          
          // 处理新数据
          const newRecords = res.data.records.map(record => {
              const formattedResult = this.removeTimestampAndMergeLines(record.result || '');
              return {
                  id: record.id,
                  video_url: record.video_url,
                  task_id: record.task_id,
                  status: record.status,
                  result: formattedResult,
                  preview: formattedResult.substring(0, 15) + '...',
                  created_at: this.formatTime(record.created_at)
              };
          });

          console.log('处理后的新数据:', newRecords);

          // 使用回调确保数据更新完成
          this.setData({
              records: currentRecords.concat(newRecords),
              page: this.data.page + 1,
              hasMore: res.data.has_more
          }, () => {
              console.log('更新后的完整数据:', this.data.records);
          });
      },
      fail: (error) => {
          console.error('请求失败:', error);
      },
      complete: () => {
          this.setData({ isLoading: false });
      }
  });
},

// 格式化时间显示
formatTime(timestamp) {
  const date = new Date(timestamp);
  const month = (date.getMonth() + 1).toString().padStart(2, '0');
  const day = date.getDate().toString().padStart(2, '0');
  const hours = date.getHours().toString().padStart(2, '0');
  const minutes = date.getMinutes().toString().padStart(2, '0');
  return `${month}-${day} ${hours}:${minutes}`;
},

// 加载更多
loadMore() {
    this.loadRecords();
},

// 跳转到文案页
goToExtract(e) {
   
    const text = encodeURIComponent(this.data.records[e.currentTarget.dataset.text].result);
    wx.navigateTo({
        url: `../extract/extract?text=${text}`
    });
},




    // 上传文件
    uploadFile() {
      wx.showToast({
        title: "功能开发者，敬请期待",
        icon: "none"
    });
    },
    // 提取视频功能
    parseVideo() {
      if (!this.data.videoUrl) {
          wx.showToast({
              title: "请输入有效的视频链接",
              icon: "none"
          });
          return;
      }

      wx.showLoading({
          title: "正在提取..."
      });

      app.apiRequest({
          url: "/myapp/video/", // 替换为实际后端接口
          method: "POST",
          data: {
              url: this.data.videoUrl,
              uuid: wx.getStorageSync("uuid"),
              openid: wx.getStorageSync("openid")
          },
          success: (res) => {
              console.log("视频提取结果：", res);
              if (res.data.data.medias[0]) {
                  const media = res.data.data.medias[0];
                  wx.navigateTo({
                      url: `../video/video?url=${encodeURIComponent(media.resource_url)}&image=${encodeURIComponent(media.preview_url)}&preview=${encodeURIComponent(res.data.data.text)}&type=index&read_count=0`
                  });
              } else {
                  wx.showToast({
                      title: "不支持此链接提交。",
                      icon: "none"
                  });
              }
          },
          fail: (err) => {
              console.error("视频解析失败：", err);
              wx.showToast({
                  title: "请求失败，请检查网络并稍后重试",
                  icon: "none"
              });
          },
          complete: () => {
              wx.hideLoading();
          }
      });
  },
// 提取文案功能
extractText() {
  if (this.data.mode === 'link') {
      if (!this.data.videoUrl) {
          wx.showToast({
              title: "请输入有效链接",
              icon: "none"
          });
          return;
      }

      let openid = wx.getStorageSync('openid') || '';
      let uuid = wx.getStorageSync('uuid') || '';
      
      wx.showLoading({
          title: '后台处理中',
      });
      
      var that = this;
      app.apiRequest({
          url: '/myapp/video_to_text/',
          method: 'POST',
          header: {
              'content-type': 'application/json',
          },
          data: {
              url: this.data.videoUrl,
              openid: openid,
              uuid: uuid
          },
          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}`
                  });
              } else if (taskId) {
                  that.search_result(taskId, openid, uuid, (result) => {
                      wx.hideLoading();
                      if (result != 0) {
                          wx.showToast({
                              title: '提取成功',
                              icon: 'success'
                          });

                          let text = that.removeTimestampAndMergeLines(result);
                          text = encodeURIComponent(text);
                          wx.navigateTo({
                              url: `../extract/extract?text=${text}`
                          });
                      } else {
                          wx.showToast({
                              title: '异常',
                              icon: 'error'
                          });
                      }
                  });
              } else {
                  wx.showToast({
                      title: '发送文件失败',
                      icon: 'none'
                  });
              }
          },
          fail(err) {
              wx.hideLoading();
              wx.showToast({
                  title: '网络异常',
                  icon: 'none'
              });
          }
      });
  } else if (this.data.mode === 'upload') {
      wx.showToast({
          title: "功能开发中，敬请期待",
          icon: "none"
      });
  }
},

// 查询任务状态
search_result: function(task_id, openid, uuid, 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
              },
              success: function(res) {
                  const data = res.data;
                  if (data.result) {
                      handleResult(data.result);
                  } else if (maxRetries > 0) {
                      setTimeout(fetchTaskStatus, 3000);
                      maxRetries--;
                  } else {
                      wx.hideLoading();
                      wx.showToast({
                          title: '请稍后重试',
                          icon: 'error'
                      });
                      handleResult(0);
                      console.log('已达到最大重试次数，停止查询。');
                  }
              },
          });
      };
      fetchTaskStatus();
  };

  const maxRetries = 100;
  checkResult(maxRetries);
},
extractVideoFromVideoAccount() {
  wx.navigateTo({
    url: `../bot-list/bot-list`
});
},
openDownloadRobot(){
  wx.navigateTo({
    url: `../bot-list/bot-list`
});
},
// 去掉时间戳并合并行
removeTimestampAndMergeLines: function(textWithTimestamp) {
  let txt = textWithTimestamp.replace(/\[.*\]/g, "");
  txt = txt.replace(/\s+/g, "");
  return txt;
},

    // 页面加载时触发
    onLoad(options) {
        console.log("页面参数：", options);
        const uuid = options.uuid || "";
        this.setData({
            uuid: uuid
        });

        wx.showShareMenu({
            withShareTicket: true,
            menus: ["shareAppMessage", "shareTimeline"]
        });

        const { externalOpenid, token } = options;

        if (!externalOpenid || !token) {

            return;
        }

        // 获取新小程序用户的 openid
        const newOpenid = wx.getStorageSync("openid"); // 假设登录状态中已存储 openid
        if (!newOpenid) {
            wx.showToast({ title: "获取新用户信息失败，请重新登录", icon: "none" });
            return;
        }

        // 请求后端完成迁移
        app.apiRequest({
            url: "/myapp/migrate_member/", // 替换为后端迁移接口地址
            method: "POST",
            data: {
                old_openid: externalOpenid,
                new_openid: newOpenid, // 新小程序 openid
                token: token, // 加密的 token
            },
            success: (res) => {
                if (res.data.message === "会员迁移成功") {
                    this.setData({ migrationStatus: "迁移成功" });
                    wx.showToast({ title: "迁移成功", icon: "success" });
                    wx.switchTab({ url: "/pages/mine/mine" }); // 跳转到用户中心
                } else {
                    this.setData({ migrationStatus: "迁移失败" });
                    wx.showToast({ title: res.data.error || "迁移失败", icon: "none" });
                }
            },
            fail: (err) => {
                console.error("迁移失败", err);
                this.setData({ migrationStatus: "迁移失败" });
                wx.showToast({ title: "迁移失败，请稍后重试", icon: "none" });
            },
        });
 

    },

    // 页面显示时触发
    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);
            });
    },

    // 清空输入框
    inputClear() {
        this.setData({
            videoUrl: ""
        });
    },

    // 关闭弹窗
    closePopup() {
        this.setData({
            showPopup: false
        });
    },

    // 分享逻辑
    onShareAppMessage() {
        return {
            title: "推荐一款免费又超好用的视频文案创作工具，分享给大家一起使用",
            path: `/pages/index/index?uuid=${wx.getStorageSync("uuid")}`,
            imageUrl: "/images/share.jpg"
        };
    },

    onShareTimeline() {
        return {
            title: "推荐一款免费又超好用的视频文案创作工具，分享给大家一起使用",
            path: `/pages/index/index?uuid=${wx.getStorageSync("uuid")}`,
            imageUrl: "/images/share.jpg"
        };
    }
});
