import { Component, OnInit } from '@angular/core';
import { CustomHeaderComponent } from 'src/lib/component/custom-header/custom-header.component';
import { IonButton, IonCard, IonCardTitle, IonContent, IonInput, IonItem, IonLabel, IonList } from '@ionic/angular/standalone';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-eco-fashion',
  templateUrl: './eco-fashion.component.html',
  styleUrls: ['./eco-fashion.component.scss'],
  standalone: true,
  imports: [CustomHeaderComponent, IonContent, IonItem, IonLabel, IonInput, IonButton, IonList, CommonModule,
    FormsModule, IonCard, IonCardTitle
  ]
})
export class EcoFashionComponent implements OnInit {
  constructor(private http: HttpClient) { }
  async ngOnInit() {
    // await this.getLocation();
    // await this.handleLocation();
    // await this.getMap();
    await this.search('旧衣改造');
  }
  /**
   * @内置函数逻辑
   */
  /*获取位置信息*/
  location: any | undefined;
  async getLocation() {
    const proxyUrl = 'http://localhost:3000/proxy';
    const targetUrl = 'https://restapi.amap.com/v5/place/text?keywords=衣物回收&region=南昌市&key=35b3a049194864d0b80bd7c258c33608';
    const response = await fetch(`${proxyUrl}?url=${encodeURIComponent(targetUrl)}`, {
      headers: {
        "accept": "application/json",
      },
      "method": "GET",
      "mode": "cors",
      "credentials": "omit"
    });

    //检查响应状态并解析JSON数据
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json(); // 解析JSON响应
    console.log(data); // 输出解析后的数据
    this.location = data; // 将数据赋值给location变量
  }
  /*处理位置信息，获取经纬度坐标*/
  latAndLong: Array<any> = [];
  async handleLocation() {
    for (let i = 0; i < this.location.pois.length; i++) {
      console.log("正在获取经纬度信息(" + (i + 1) + "/" + this.location.count + ")");
      const location = this.location.pois[i].location;
      //location直接加入latAndLong数组中
      this.latAndLong[i] = location;
      console.log(location);
    }
  }
  //请求地图
  map: any;
  async getMap(latAndLong?: string) {
    let markers = "mid,0xFF0000,A:";
    if (latAndLong) {
      markers += latAndLong;
    }
    else {
      for (let i = 0; i < this.latAndLong.length; i++) {
        markers += `${this.latAndLong[i]};`;
      }
      markers = markers.slice(0, -1);
    }
    console.log("markers: " + markers);
    const url = `https://restapi.amap.com/v3/staticmap?size=750*400&markers=${markers}&key=35b3a049194864d0b80bd7c258c33608`
    const response = await fetch(url, {
      headers: {
      },
      "method": "GET",
      "mode": "cors",
      "credentials": "omit"
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    // 获取二进制响应数据
    console.log(response);
    const blob = await response.blob();
    // 创建一个ObjectURL，它可以作为<img>标签的src属性
    const objectURL = URL.createObjectURL(blob);
    // 假设您有一个<img>标签用于显示地图
    const imgElement = document.getElementById('map-image') as HTMLImageElement;
    imgElement.src = objectURL;
  }

  /**
   * @用户操作函数逻辑
  */
  /*用户点击位置*/
  clickLocation(latAndLong: string) {
    this.getMap(latAndLong);
  }
  /*搜索*/
  posts: any;
  async search(keyword: string) {
    this.http.get<any[]>(`http://localhost:3000/scrape?keyword=${keyword}`)
      .subscribe(data => {
        this.posts = data;
      }, error => {
        console.error('Error fetching posts', error);
      });
  }
}
