import { HttpClient } from '@angular/common/http';
import { Component, Input } from '@angular/core';
import { IonButton, IonButtons, IonContent, IonHeader, IonIcon, IonTitle, IonToolbar, ModalController } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { arrowBack } from 'ionicons/icons';
import * as mammoth from 'mammoth';

@Component({
  selector: 'app-image1-popup',
  templateUrl: './image1-popup.component.html',
  styleUrls: ['./image1-popup.component.scss'],
  standalone: true,
  imports: [IonContent, IonHeader, IonButton, IonButtons, IonToolbar, IonTitle, IonIcon,]
})
export class Image1PopupComponent {
  @Input() imageUrl: string = '';
  @Input() description: string = '';
  content: any = null;

  constructor(private http: HttpClient,private modalController: ModalController) {
    addIcons({arrowBack});
  }
  
  ngOnInit() {this.loadAndParseWordFile();}
  
 // 加载并解析本地 Word 文件
 // 加载并解析本地 Word 文件
loadAndParseWordFile() {
  // 从本地 assets 文件夹获取文件
  const fileName = 'ssbt.docx';  // 请替换为你实际的文件名
  this.http.get(`assets/${fileName}`, { responseType: 'arraybuffer' })
    .subscribe(
      (arrayBuffer: ArrayBuffer) => {
        console.log('Received arrayBuffer:', arrayBuffer);  // 调试日志，查看是否成功加载

        // 使用 mammoth 提取文本
        mammoth.extractRawText({ arrayBuffer: arrayBuffer })
          .then((result: any) => {
            this.content = {
              text: result.value,
              images: []
            };
            console.log('Extracted Text:', result.value);  // 输出解析的文本内容
          })
          .catch((err: any) => {
            console.error('Error parsing Word file:', err);
          });

        // 使用 mammoth 将 Word 转换为 HTML
        mammoth.convertToHtml({ arrayBuffer: arrayBuffer })
          .then((result: any) => {
            console.log('Converted HTML:', result.value);  // 输出转换的 HTML
            const imgMatches = result.value.match(/<img.*?src="([^"]+)"/g);
            if (imgMatches) {
              this.content.images = imgMatches.map((img: string) => {
                const match = img.match(/src="([^"]+)"/);
                return match ? match[1] : '';
              });
            }
            console.log('Extracted Images:', this.content.images);
          })
          .catch((err: any) => {
            console.error('Error parsing images from Word file:', err);
          });
      },
      (error) => {
        console.error('Error loading Word file:', error);  // 加载文件时出现错误
      }
    );
}




  close() {
    this.modalController.dismiss();
  }
}
