import common from '../../utils/util';
import main from '../../utils/main';

const app = getApp();

Page({
  data: {
    Menu:[],
    cameraActive: true,
  },
  onLoad: function (options) {
    app.globalData.OCRWords=[];
    main.checkGenerating();
  },
  onShow:function(){
    let that = this;
    that.setData({
      cameraActive: true,
      Menu:[{Name:"相册",CSS:"",Fun:"chooseImage"},{Name:"拍照",CSS:"Selected",Fun:"retake"}]
    });
  },
  retake() {
    this.data.Menu[0].CSS="";
    this.data.Menu[1].CSS="Selected";
    this.setData({
      Menu:this.data.Menu,
      cameraActive: true,
    });
  },
  // 拍照识别
  takePhoto() {
    const ctx = wx.createCameraContext();
    ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        this.setData({
          imageUrl: res.tempImagePath,
          cameraActive: false,
        })
        this.performOCR(res.tempImagePath)
      },
      fail: (err) => {
        console.error('拍照失败:', err)

        wx.showToast({
          title: '拍照失败，请重试',
          icon: 'none'
        })
      }
    })
  },
  chooseImage() {
    this.data.Menu[0].CSS="Selected";
    this.data.Menu[1].CSS="";
    this.setData({
      Menu:this.data.Menu,
      cameraActive: false,
    });

    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath
        this.setData({
          imageUrl: tempFilePath,
          cameraActive: false,
        })
        this.performOCR(tempFilePath)
      },
      fail: (err) => {
        console.error('选择图片失败:', err)
        wx.showToast({
          title: '选择图片失败',
          icon: 'none'
        })
      }
    })
  },
  // 加强版的OCR识别方法
  async performOCR(imagePath) {
    let that=this;
    if (!imagePath) {
      console.error('图片路径无效')
    }

    wx.showLoading({ title: '识别中...', mask: true })

    try {
      // 1. 压缩图片
      const compressed = await new Promise((resolve, reject) => {
        wx.compressImage({
          src: imagePath,
          quality: 70,
          success: resolve,
          fail: () => resolve({ tempFilePath: imagePath })
        })
      })
      //console.log("1");
      // 2. 转换为base64
      const fileRes = await new Promise((resolve, reject) => {
        wx.getFileSystemManager().readFile({
          filePath: compressed.tempFilePath,
          encoding: 'base64',
          success: resolve,
          fail: reject
        })
      })
      //console.log("2");
      // 3. 调用云函数（添加超时处理）
      let postData={ ImageBase64: `data:image/jpeg;base64,${fileRes.data}` };
      
      let url = common.Encrypt("OCRImageData?UserID="+app.globalData.userInfo.UserID);
      url=app.globalData.serverUrl+url;
      //console.log("url:"+url);
      const cloudRes = await new Promise((resolve, reject) => {
        wx.request({
          url: url,
          method: "POST",
          data: postData,
          success: resolve,
          fail: reject,
        })
      });
      //console.log("3");

      // 4. 验证返回结果
      if (!cloudRes || !cloudRes.data.result) {
        throw new Error('无效的响应格式')
      }
      //console.log("4");
      if (!cloudRes.data.result) {
        throw new Error(cloudRes.data.result.message || '识别服务返回空数据')
      }

      // 5. 处理识别结果
      const texts = cloudRes.data.result.TextDetections.map(item => ({
        text: item.DetectedText || '未识别到文字',
        pos: this.convertPosition(item.ItemPolygon || { Points: [] })
      })).filter(item => item.DetectedText !== '未识别到文字')

      //console.log("5");

      if (texts.length === 0) {
        throw new Error('未识别到有效文字')
      }

      debugger;
      // 6.提取英文单词
      const engTexts=this.extractEnglishWords(texts);

      // let arr=[];
      // for(var i=0;i<engTexts.length;i++){
      //   let obj={};
      //   obj.Word=engTexts[i];
      //   obj.Selected=0;
      //   arr.push(obj);
      // }
      app.globalData.OCRWords=engTexts;
      //debugger;
      
      wx.redirectTo({
        url: "./selectword",
      });

      that.setData({
        cameraActive: true,
      })

    } catch (err) {
      console.error('OCR处理失败:', err)
      wx.showToast({
        title: err.message || '识别失败',
        icon: 'none',
        duration: 3000
      })
    } finally {
      wx.hideLoading();
      that.setData({
        cameraActive: true,
      })
    }
  },

  // 加强坐标转换
  convertPosition(polygon) {
    try {
      const points = polygon.Points || []
      if (points.length === 0) {
        return { x: 50, y: 50, width: 200, height: 30 }
      }

      const xs = points.map(p => p.X || 0)
      const ys = points.map(p => p.Y || 0)
      return {
        x: Math.min(...xs),
        y: Math.min(...ys),
        width: Math.max(...xs) - Math.min(...xs),
        height: Math.max(...ys) - Math.min(...ys)
      }
    } catch (e) {
      return { x: 50, y: 50, width: 200, height: 30 }
    }
  },

  // 提取英语单词的函数 - 增强版
  extractEnglishWords(texts) {
    //console.group('英语单词提取');
    const words = new Set();
    texts.forEach(item => {
      const text = item.text;
      //console.log('处理文本:', text);
      
      // 使用多种分隔符分割文本（空格、逗号、句号、感叹号、中文字符等）
      // 这个正则表达式会匹配任何非英文字母、撇号或连字符的字符作为分隔符
      const parts = text.split(/[^A-Za-z''-]+/).filter(Boolean);
      
      //console.log('分割后的部分:', parts);
      
      // 处理每个可能的单词
      parts.forEach(part => {
        // 清理并验证单词
        const cleanWord = this.cleanWord(part);
        
        // 特殊处理单词"I"
        if (cleanWord === 'I' || cleanWord === 'a') {
          words.add(cleanWord); // 添加小写的"i"
          //console.log('添加单词: I (特殊处理)');
        }
        // 处理其他单词（长度>=2）
        else if (cleanWord && cleanWord.length >= 2 && /^[A-Za-z''-]+$/.test(cleanWord)) {
          let lowerWord = cleanWord.toLowerCase();
          if (lowerWord=="i'm"){
            lowerWord="I'm";
          }
          words.add(lowerWord);
          //console.log('添加单词:', lowerWord);
        }
      });
    });
    
    //const result = Array.from(words).sort();
    let result = Array.from(words);
    result = common.removeDuplicateAndTrimStrings(result);
    //console.log('提取结果:', result);
    //console.groupEnd();
    return result;
  },
  
  // 清理单词，去除非字母字符
  cleanWord(word) {
    if (!word) return '';
    
    // 去除单词前后的非字母字符
    const cleaned = word.replace(/^[^A-Za-z]+|[^A-Za-z]+$/g, '');
    
    // 保留单词中间的撇号和连字符
    return cleaned.replace(/[^A-Za-z''-]/g, '');
  },

  onShareAppMessage: function () {
    return {
      title: app.globalData.ShareTitle,
      path: app.globalData.SharePath + '?UserID=' + app.globalData.userInfo.UserID,
      imageUrl: app.globalData.ShareImage,
    }
  },
})