import { Component, EventEmitter, Input, OnDestroy, OnChanges, OnInit, Output, ApplicationRef, ChangeDetectorRef } from '@angular/core';
import { JsonPipe } from '@angular/common';
import { NzMessageService } from 'ng-zorro-antd/message';
declare function commonPostMessageWithCallback(
  params: any,
  callback: (res: any) => void
): void;

@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit, OnChanges, OnDestroy {

  // 储存数据用
  saveKey = "jj_learn_word";
  
  // 储存对象
  item;

  posArr = [
    'n.',
    'adj.',
    'v.',
    'pron.',
    'adv.',
    'prep.',
    'conj.',
    'interj.',
    'art.',
    'num.',
    'abbr.',
    'phrase',
    'ordinal number',
    'det.'
  ];

  // 存储courseId
  courseId: string = '';
  constructor(private appRef: ApplicationRef, private changeDetectorRef: ChangeDetectorRef, 
    private message: NzMessageService) {

  }

  // 从父窗口URL获取参数
  getParentUrlParam(param: string): string | null {
    try {
      // 获取父窗口的URL
      const parentUrl = window.parent.location.href;
      // 创建URL对象来解析参数
      const url = new URL(parentUrl);
      // 获取指定的参数值
      return url.searchParams.get(param);
    } catch (e) {
      // 处理可能的跨域安全错误
      console.error("无法访问父窗口URL，可能是由于跨域限制:", e);
      return null;
    }
  }

  ngOnInit() {
    this.item = {};
    
    // 获取课程ID
    this.getCourseIdFromParent();
    
    // 获取存储的数据
    (<any>window).courseware.getData((data) => {
      if (data) {
        this.item = data;
        
        // 删除可能存在的quesArr属性
        if (this.item.quesArr) {
          delete this.item.quesArr;
        }
      }

      this.initItem();
      
      // 如果有courseId，设置为pictureBookId
      if (this.courseId) {
        const courseIdNum = parseInt(this.courseId, 10);
        if (!isNaN(courseIdNum)) {
          this.item.pictureBookId = courseIdNum;
        }
      }
      
      // 确保每个单词都有正确的ID（pictureBookId + 索引）
      this.ensureWordIds();
      
      console.log("this.item: ", JSON.stringify(this.item));
      
      this.init();
      this.changeDetectorRef.markForCheck();
      this.changeDetectorRef.detectChanges();
      this.refresh();
      
    }, this.saveKey);
  }

  initItem() {
    // 确保item有正确的数据结构
    if (!this.item.data) {
      this.item.data = [];
    }
    
    // 确保pictureBookId存在且为整数
    if (this.item.pictureBookId) {
      const pictureBookId = parseInt(this.item.pictureBookId, 10);
      this.item.pictureBookId = isNaN(pictureBookId) ? 0 : pictureBookId;
    } else {
      this.item.pictureBookId = 0;
    }
    
    // 确保每个单词都有正确的backContent结构
    if (this.item.data && this.item.data.length > 0) {
      this.item.data.forEach(word => {
        // 初始化backContent
        if (!word.backContent) {
          word.backContent = {
            content: '',
            audioUrl: '',
            answer: []
          };
        } else if (!word.backContent.answer) {
          // 确保answer数组存在
          word.backContent.answer = [];
        }
        
        // 确保pictureBookId是整数
        if (word.pictureBookId) {
          const pictureBookId = parseInt(word.pictureBookId, 10);
          word.pictureBookId = isNaN(pictureBookId) ? 0 : pictureBookId;
        } else {
          word.pictureBookId = this.item.pictureBookId;
        }
      });
    }
  }

  // 确保每个单词都有ID
  ensureWordIds() {
    if (!this.item.data || this.item.data.length === 0) {
      return;
    }

    // 确保pictureBookId是整数
    let pictureBookId = 0;
    if (this.item.pictureBookId) {
      pictureBookId = parseInt(this.item.pictureBookId, 10);
      if (isNaN(pictureBookId)) {
        pictureBookId = 0;
      }
    }
    this.item.pictureBookId = pictureBookId;
    
    // 为每个单词生成id（pictureBookId + 索引）
    this.item.data.forEach((word, index) => {
      // 生成id为pictureBookId和索引的拼接
      const wordIndex = index + 1;
      // 将id设置为pictureBookId和单词索引的拼接形式
      word.id = parseInt(`${pictureBookId}${wordIndex}`, 10);
      
      // 更新pictureBookId
      word.pictureBookId = pictureBookId;
    });
  }

  init() {
    // 如果没有任何数据，可以添加示例数据
    if (this.item.data.length === 0) {
      this.addSampleData();
    }
  }

  // 添加示例数据
  addSampleData() {
    // 确保pictureBookId是整数
    let pictureBookId = 0;
    if (this.item.pictureBookId) {
      pictureBookId = parseInt(this.item.pictureBookId, 10);
      if (isNaN(pictureBookId)) {
        pictureBookId = 0;
      }
    }
  
    this.item.data.push({
      id: 0, // 临时ID，将在ensureWordIds中设置正确的值
      pictureBookId: pictureBookId,
      word: '',
      displayType: 1, // 默认为"词卡单词"
      partOfSpeech: '',
      exampleSentence: '',
      wordAudioUrl: '',
      exampleSentenceAudioUrl: '',
      wordTranslation: '',
      exampleSentenceTranslation: '',
      imageUrl: '',
      britishPhonetic: '',
      americanPhonetic: '',
      englishDefinition: '',
      backContent: {
        content: '',
        audioUrl: '',
        answer: []
      },
      createdTime: new Date().toISOString()
    });
  }

  ngOnChanges() {
  }

  ngOnDestroy() {
  }

  onItemImgUploadSuccess(e, item, key='imageUrl') {
    item[key] = e.url;
    this.save();
  }

  onItemAudioUploadSuccess(e, item, key='wordAudioUrl') {
    item[key] = e.url;
    this.save();
  }

  onDeletaImg(item, key) {
    item[key] = '';
    this.save();
  }

  getNewSortItem() {
    // 深拷贝item对象
    const newItem = JSON.parse(JSON.stringify(this.item));
    
    // 删除可能存在的属性
    if (newItem.quesArr) {
      delete newItem.quesArr;
    }
    return newItem;
  }

  /**
   * 储存数据
   */
  save() {
    // 验证必填字段
    let hasError = false;
    if (this.item.data && this.item.data.length > 0) {
      this.item.data.forEach((word, index) => {
        if (!word.word || word.word.trim() === '') {
          this.message.warning(`第${index + 1}个单词的"单词"不能为空`);
          hasError = true;
        }
        if (!word.partOfSpeech || word.partOfSpeech.trim() === '') {
          this.message.warning(`第${index + 1}个单词的"词性"不能为空`);
          hasError = true;
        }
        if (!word.displayType) {
          this.message.warning(`第${index + 1}个单词的"显示类型"不能为空`);
          hasError = true;
        }
      });
    }
    
    // 如果有错误，不保存
    if (hasError) {
      return;
    }
    
    // 确保所有单词都有正确的ID（pictureBookId + 索引）
    this.ensureWordIds();
    
    const newItem = this.getNewSortItem();
    
    (<any>window).courseware.setData(newItem, null, this.saveKey);

    this.refresh();
    console.log('this.item = ' + JSON.stringify(this.item));

    this.message.create('success', "保存成功");
  }

  /**
   * 刷新 渲染页面
   */
  refresh() {
    setTimeout(() => {
      this.appRef.tick();
    }, 1);
  }

  // 添加新单词到data数组中
  addNewWord() {
    // 确保pictureBookId是整数
    let pictureBookId = 0;
    if (this.item.pictureBookId) {
      pictureBookId = parseInt(this.item.pictureBookId, 10);
      if (isNaN(pictureBookId)) {
        pictureBookId = 0;
      }
    }
    
    this.item.data.push({
      id: 0, // 临时ID，将在ensureWordIds中设置正确的值
      pictureBookId: pictureBookId,
      word: '',
      displayType: 1, // 默认为"词卡单词"
      partOfSpeech: '',
      exampleSentence: '',
      wordAudioUrl: '',
      exampleSentenceAudioUrl: '',
      wordTranslation: '',
      exampleSentenceTranslation: '',
      imageUrl: '',
      britishPhonetic: '',
      americanPhonetic: '',
      englishDefinition: '',
      backContent: {
        content: '',
        audioUrl: '',
        answer: []
      },
      createdTime: new Date().toISOString()
    });
    
    // 确保所有单词都有正确的ID（pictureBookId + 索引）
    this.ensureWordIds();
    
    this.save();
  }
  
  // 删除data数组中的单词
  deleteWord(index) {
    this.item.data.splice(index, 1);
    this.save();
  }

  // 生成单词音频
  generateWordAudio(word) {
    if (!word.word || word.word.trim() === '') {
      this.message.error('请先输入单词');
      return;
    }

    const call_back = (res) => {
      console.log("gennerateQuestionAudio res: ", res);

      try {
        const resData = JSON.parse(res);

        if (resData.msg == "success") {
          if (resData.data && word.word) {
            // 确保音频URL正确赋值
            word.wordAudioUrl = resData.data;
            this.save(); // 保存更改
            this.message.create("success", "题目音频生成成功");
          } else {
            this.message.create("warning", "生成的音频数据为空");
          }
        } else {
          this.message.create("error", "音频生成失败");
        }
      } catch (e) {
        console.error("解析音频生成响应出错:", e);
        this.message.create("error", "音频生成响应解析失败");
      }
    };

    // 检查方法是否存在
    const checkAndCall = (word: any) => {
      if (typeof commonPostMessageWithCallback === "function") {
        commonPostMessageWithCallback(
          {
            action: "generateTTS",
            data: word,
          },
          call_back
        );
      } else {
        // setTimeout(checkAndCall, 100);
        this.message.create("error", "通信方法不可用");
      }
    };

    checkAndCall(word.word);
    this.message.info(`准备为单词"${word.word}"生成音频`);
  }

  // 生成例句音频
  generateExampleAudio(word) {
    if (!word.exampleSentence || word.exampleSentence.trim() === '') {
      this.message.error('请先输入例句');
      return;
    }

    const call_back = (res) => {
      console.log("generateExampleAudio res: ", res);

      try {
        const resData = JSON.parse(res);

        if (resData.msg == "success") {
          if (resData.data && word.exampleSentence) {
            // 确保音频URL正确赋值
            word.exampleSentenceAudioUrl = resData.data;
            this.save(); // 保存更改
            this.message.create("success", "例句音频生成成功");
          } else {
            this.message.create("warning", "生成的音频数据为空");
          }
        } else {
          this.message.create("error", "音频生成失败");
        }
      } catch (e) {
        console.error("解析音频生成响应出错:", e);
        this.message.create("error", "音频生成响应解析失败");
      }
    };

    // 检查方法是否存在
    const checkAndCall = (sentence: any) => {
      if (typeof commonPostMessageWithCallback === "function") {
        commonPostMessageWithCallback(
          {
            action: "generateTTS",
            data: sentence,
          },
          call_back
        );
      } else {
        this.message.create("error", "通信方法不可用");
      }
    };

    checkAndCall(word.exampleSentence);
    this.message.info(`准备为例句生成音频`);
  }

  // 获取或初始化backContent
  getBackContent(word) {
    if (!word.backContent) {
      word.backContent = {
        content: '',
        audioUrl: '',
        answer: []
      };
    }
    
    // 确保answer数组存在
    if (!word.backContent.answer) {
      word.backContent.answer = [];
    }
    
    return word.backContent;
  }

  // 添加新选项
  addOption(word) {
    // 确保backContent及其answer数组存在
    const backContent = this.getBackContent(word);
    
    try {
      // 添加新选项
      backContent.answer.push({
        answer: '',
        audioUrl: '',
        isCorrect: false
      });
      this.save();
    } catch (error) {
      console.error('添加选项失败:', error);
      this.message.error('添加选项失败，请刷新页面后重试');
    }
  }

  // 删除选项
  deleteOption(word, index) {
    try {
      const backContent = this.getBackContent(word);
      // 检查索引是否有效
      if (backContent.answer && Array.isArray(backContent.answer) && index >= 0 && index < backContent.answer.length) {
        backContent.answer.splice(index, 1);
        this.save();
      } else {
        console.warn('尝试删除不存在的选项索引:', index);
      }
    } catch (error) {
      console.error('删除选项失败:', error);
      this.message.error('删除选项失败，请刷新页面后重试');
    }
  }

  // 思考问题音频上传成功回调
  onBackContentAudioUploaded(e, word) {
    const backContent = this.getBackContent(word);
    backContent.audioUrl = e.url;
    this.save();
  }

  // 选项音频上传成功回调
  onOptionAudioUploaded(e, option, word) {
    option.audioUrl = e.url;
    this.save();
  }

  // 生成思考问题音频
  generateQuestionAudio(word) {
    const backContent = this.getBackContent(word);
    if (!backContent.content || backContent.content.trim() === '') {
      this.message.error('请先输入题目内容');
      return;
    }

    const call_back = (res) => {
      console.log("generateQuestionAudio res: ", res);

      try {
        const resData = JSON.parse(res);

        if (resData.msg == "success") {
          if (resData.data && backContent.content) {
            backContent.audioUrl = resData.data;
            this.save();
            this.message.create("success", "题目音频生成成功");
          } else {
            this.message.create("warning", "生成的音频数据为空");
          }
        } else {
          this.message.create("error", "音频生成失败");
        }
      } catch (e) {
        console.error("解析音频生成响应出错:", e);
        this.message.create("error", "音频生成响应解析失败");
      }
    };

    const checkAndCall = (content) => {
      if (typeof commonPostMessageWithCallback === "function") {
        commonPostMessageWithCallback(
          {
            action: "generateTTS",
            data: content,
          },
          call_back
        );
      } else {
        this.message.create("error", "通信方法不可用");
      }
    };

    checkAndCall(backContent.content);
    this.message.info(`准备为题目生成音频`);
  }

  // 获取课程ID
  getCourseIdFromParent() {
    const call_back = (res) => {
      console.log("courseId res: ", res);
      this.courseId = res;
    }
    const checkAndCall = () => {
      if (typeof commonPostMessageWithCallback === "function") {
        commonPostMessageWithCallback(
          {
            action: "getCourseId",
          },
          call_back
        );
      } else {
        this.message.create("error", "通信方法不可用");
      }
    };
    checkAndCall();
  }

  // 生成选项音频
  generateOptionAudio(option, word) {
    if (!option.answer || option.answer.trim() === '') {
      this.message.error('请先输入选项内容');
      return;
    }

    const call_back = (res) => {
      console.log("generateOptionAudio res: ", res);

      try {
        const resData = JSON.parse(res);

        if (resData.msg == "success") {
          if (resData.data && option.answer) {
            option.audioUrl = resData.data;
            this.save();
            this.message.create("success", "选项音频生成成功");
          } else {
            this.message.create("warning", "生成的音频数据为空");
          }
        } else {
          this.message.create("error", "音频生成失败");
        }
      } catch (e) {
        console.error("解析音频生成响应出错:", e);
        this.message.create("error", "音频生成响应解析失败");
      }
    };

    const checkAndCall = (content) => {
      if (typeof commonPostMessageWithCallback === "function") {
        commonPostMessageWithCallback(
          {
            action: "generateTTS",
            data: content,
          },
          call_back
        );
      } else {
        this.message.create("error", "通信方法不可用");
      }
    };

    checkAndCall(option.answer);
    this.message.info(`准备为选项生成音频`);
  }

}