import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { IonContent, IonHeader, IonTitle, IonToolbar, IonButton, IonLabel, IonItem, IonList, IonBackButton, IonButtons, IonIcon, IonItemDivider, IonAvatar, IonThumbnail, IonItemOptions, IonItemOption, IonItemSliding, IonInput, IonCheckbox, IonRadio, IonToggle, IonRadioGroup, IonSearchbar, IonSegment, IonSegmentButton, IonDatetime, IonFooter, IonCardContent, IonCardTitle, IonCardHeader, IonCard, IonCol, IonRow, IonGrid, IonChip, IonImg, PickerController, IonPicker } from '@ionic/angular/standalone';
import { CommonModule } from '@angular/common';
import { HttpClient } from '@angular/common/http';

import { pinyin } from 'pinyin-pro';
import { CloudQuery, CloudUser } from 'src/lib/ncloud';

@Component({
  selector: 'time',
  templateUrl: './time.component.html',
  styleUrls: ['./time.component.scss'],
  standalone: true,
  imports: [IonContent, IonHeader, IonTitle, IonToolbar, IonButton, IonInput, IonItem, IonList, IonIcon, IonContent, IonHeader, IonTitle, IonToolbar, IonButton, IonLabel, IonLabel, IonList, IonItem, IonBackButton, IonButtons, IonIcon, IonItemDivider, IonAvatar, IonThumbnail, IonItemOptions, IonItemSliding, IonItemOption, IonItemOptions, IonInput, IonCheckbox, IonRadio, IonToggle, IonRadioGroup, IonSearchbar, IonSegment, IonSegmentButton, IonDatetime, IonFooter, IonCardContent, IonCardTitle, IonCardHeader, IonCard, IonCol, IonRow, IonGrid, IonChip, IonImg, CommonModule, IonPicker]
})
export class TimeComponent  implements OnInit {

  curYear: number;
  curMonth: number;
  week: string[] = ['一', '二', '三', '四', '五', '六', '日'];
  firstDays: number[] = [];
  curDays: number[] = [];
  nextDaysArray: number[] = [];
  selectedDate: number | null = null;

  pickerColumns: any[] = [];
  pickerButtons: any[] = [];
  checkedDates: string[] = [

  ];
  selectTime: string = ""//选中元素的时间按照“2024-12-20”格式

  async loadDates() {
    // let currentUser = new CloudUser();
    // const cloudQuery = new CloudQuery("fitUser");
    // cloudQuery.equalTo("user", currentUser.toPointer());
    // const userData = await cloudQuery.find();
    // console.log("userData::",userData[0].data.checkeddays);
    // this.checkedDates=userData[0].data.checkeddays
    
  }

  @Input() value2: string = ""; // 接收父组件传递的值
  @Output() ionChange2 = new EventEmitter<string>(); // 输出事件
  // async fetchWeatherData() {
  //   try {
  //     this.weatherData = await this.weatherService.getWeatherData(); // 提取 data 字段
  //     console.log('天气数据:', this.weatherData); // 打印天气数据
  //   } catch (error) {
  //     console.error('获取天气数据失败:', error);
  //     alert('无法获取天气数据，请检查网络连接或API状态。');
  //   }
  // }
  weather: any = [
  ];
  fetchWeatherData() {
    // 第一个请求，获取 adcode
    // const apiUrl = '/api/api/weather/city/101240101';
    // this.http.get(apiUrl)
    //   .subscribe((response: any) => {
    //     const adcode = response; // 获取 adcode 字段
    //     if (adcode) {
    //       this.weather = adcode.data.forecast
    //       console.log(this.weather);
    //       console.log("adcode",adcode);
          

    //       // 使用 adcode 获取天气信息
    //     } else {
    //       console.error('adcode not found in response:', response);
    //     }
    //   }, error => {
    //     console.error('Error fetching adcode:', error);
    //   });


    let a={
      "message": "success感谢又拍云(upyun.com)提供CDN赞助",
      "status": 200,
      "date": "20241225",
      "time": "2024-12-25 17:35:09",
      "cityInfo": {
          "city": "南昌市",
          "citykey": "101240101",
          "parent": "江西",
          "updateTime": "13:32"
      },
      "data": {
          "shidu": "43%",
          "pm25": 110,
          "pm10": 137,
          "quality": "轻度",
          "wendu": "11.3",
          "ganmao": "儿童、老年人及心脏、呼吸系统疾病患者人群应减少长时间或高强度户外锻炼",
          "forecast": [
              {
                  "date": "25",
                  "high": "高温 13℃",
                  "low": "低温 5℃",
                  "ymd": "2024-12-25",
                  "week": "星期三",
                  "sunrise": "07:07",
                  "sunset": "17:26",
                  "aqi": 93,
                  "fx": "北风",
                  "fl": "2级",
                  "type": "晴",
                  "notice": "愿你拥有比阳光明媚的心情"
              },
              {
                  "date": "26",
                  "high": "高温 12℃",
                  "low": "低温 6℃",
                  "ymd": "2024-12-26",
                  "week": "星期四",
                  "sunrise": "07:07",
                  "sunset": "17:26",
                  "aqi": 75,
                  "fx": "北风",
                  "fl": "3级",
                  "type": "晴",
                  "notice": "愿你拥有比阳光明媚的心情"
              },
              {
                  "date": "27",
                  "high": "高温 12℃",
                  "low": "低温 7℃",
                  "ymd": "2024-12-27",
                  "week": "星期五",
                  "sunrise": "07:07",
                  "sunset": "17:27",
                  "aqi": 61,
                  "fx": "北风",
                  "fl": "3级",
                  "type": "晴",
                  "notice": "愿你拥有比阳光明媚的心情"
              },
              {
                  "date": "28",
                  "high": "高温 10℃",
                  "low": "低温 3℃",
                  "ymd": "2024-12-28",
                  "week": "星期六",
                  "sunrise": "07:08",
                  "sunset": "17:28",
                  "aqi": 48,
                  "fx": "东北风",
                  "fl": "3级",
                  "type": "晴",
                  "notice": "愿你拥有比阳光明媚的心情"
              },
              {
                  "date": "29",
                  "high": "高温 12℃",
                  "low": "低温 1℃",
                  "ymd": "2024-12-29",
                  "week": "星期日",
                  "sunrise": "07:08",
                  "sunset": "17:28",
                  "aqi": 59,
                  "fx": "东北风",
                  "fl": "1级",
                  "type": "晴",
                  "notice": "愿你拥有比阳光明媚的心情"
              },
              {
                  "date": "30",
                  "high": "高温 13℃",
                  "low": "低温 7℃",
                  "ymd": "2024-12-30",
                  "week": "星期一",
                  "sunrise": "07:08",
                  "sunset": "17:29",
                  "aqi": 65,
                  "fx": "西北风",
                  "fl": "1级",
                  "type": "阴",
                  "notice": "不要被阴云遮挡住好心情"
              },
              {
                  "date": "31",
                  "high": "高温 15℃",
                  "low": "低温 6℃",
                  "ymd": "2024-12-31",
                  "week": "星期二",
                  "sunrise": "07:09",
                  "sunset": "17:30",
                  "aqi": 57,
                  "fx": "东北风",
                  "fl": "2级",
                  "type": "晴",
                  "notice": "愿你拥有比阳光明媚的心情"
              },
              {
                  "date": "01",
                  "high": "高温 13℃",
                  "low": "低温 7℃",
                  "ymd": "2025-01-01",
                  "week": "星期三",
                  "sunrise": "07:09",
                  "sunset": "17:30",
                  "aqi": 50,
                  "fx": "东北风",
                  "fl": "2级",
                  "type": "多云",
                  "notice": "阴晴之间，谨防紫外线侵扰"
              },
              {
                  "date": "02",
                  "high": "高温 9℃",
                  "low": "低温 5℃",
                  "ymd": "2025-01-02",
                  "week": "星期四",
                  "sunrise": "07:09",
                  "sunset": "17:31",
                  "aqi": 45,
                  "fx": "东北风",
                  "fl": "3级",
                  "type": "阴",
                  "notice": "不要被阴云遮挡住好心情"
              },
              {
                  "date": "03",
                  "high": "高温 11℃",
                  "low": "低温 4℃",
                  "ymd": "2025-01-03",
                  "week": "星期五",
                  "sunrise": "07:09",
                  "sunset": "17:32",
                  "aqi": 43,
                  "fx": "东北风",
                  "fl": "3级",
                  "type": "多云",
                  "notice": "阴晴之间，谨防紫外线侵扰"
              },
              {
                  "date": "04",
                  "high": "高温 12℃",
                  "low": "低温 4℃",
                  "ymd": "2025-01-04",
                  "week": "星期六",
                  "sunrise": "07:10",
                  "sunset": "17:32",
                  "aqi": 47,
                  "fx": "北风",
                  "fl": "2级",
                  "type": "晴",
                  "notice": "愿你拥有比阳光明媚的心情"
              },
              {
                  "date": "05",
                  "high": "高温 14℃",
                  "low": "低温 6℃",
                  "ymd": "2025-01-05",
                  "week": "星期日",
                  "sunrise": "07:10",
                  "sunset": "17:33",
                  "aqi": 56,
                  "fx": "北风",
                  "fl": "2级",
                  "type": "阴",
                  "notice": "不要被阴云遮挡住好心情"
              },
              {
                  "date": "06",
                  "high": "高温 12℃",
                  "low": "低温 7℃",
                  "ymd": "2025-01-06",
                  "week": "星期一",
                  "sunrise": "07:10",
                  "sunset": "17:34",
                  "aqi": 43,
                  "fx": "东北风",
                  "fl": "3级",
                  "type": "晴",
                  "notice": "愿你拥有比阳光明媚的心情"
              },
              {
                  "date": "07",
                  "high": "高温 12℃",
                  "low": "低温 5℃",
                  "ymd": "2025-01-07",
                  "week": "星期二",
                  "sunrise": "07:10",
                  "sunset": "17:35",
                  "aqi": 46,
                  "fx": "东北风",
                  "fl": "2级",
                  "type": "晴",
                  "notice": "愿你拥有比阳光明媚的心情"
              },
              {
                  "date": "08",
                  "high": "高温 14℃",
                  "low": "低温 6℃",
                  "ymd": "2025-01-08",
                  "week": "星期三",
                  "sunrise": "07:10",
                  "sunset": "17:35",
                  "aqi": 61,
                  "fx": "北风",
                  "fl": "1级",
                  "type": "阴",
                  "notice": "不要被阴云遮挡住好心情"
              }
          ],
          "yesterday": {
              "date": "24",
              "high": "高温 12℃",
              "low": "低温 3℃",
              "ymd": "2024-12-24",
              "week": "星期二",
              "sunrise": "07:06",
              "sunset": "17:25",
              "aqi": 94,
              "fx": "北风",
              "fl": "2级",
              "type": "晴",
              "notice": "愿你拥有比阳光明媚的心情"
          }
      }

  }
  this.weather = a.data.forecast



  }

  //转化成拼音
  convertToPinyin(text: string): string {
    const result = pinyin(text, {
      toneType: 'none', // 不带声调
      type: 'array', // 返回拼音数组
    });
    return result.join(''); // 将拼音数组转换为字符串
  }
  getWeatherType(year: number, month: number, day: number): string {
    // 格式化日期为 "YYYY-MM-DD"
    const dateStr = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;

    // 查找对应的天气数据
    const weatherData = this.weather.find((item: { ymd: string; }) => item.ymd === dateStr);

    // 如果找到天气数据，返回类型，否则返回空字符串
    return weatherData ? "assets/durian/" + this.convertToPinyin(weatherData.type) + ".png" : '';
  }



  constructor(private pickerCtrl: PickerController, private http: HttpClient) {
    const today = new Date();
    this.curYear = today.getFullYear();
    this.curMonth = today.getMonth() + 1; // 当前月，0-11
    this.selectedDate = today.getDate(); // 选中当天的日期
    this.updateCalendar();
    this.initializePicker();
    this.loadDates()
  }

  ngOnInit() {
    this.fetchWeatherData();
  }
  daka() {
    //打卡，点击之后，被选中的日期元素背景色被标为绿色
    if (this.checkedDates.includes(this.selectTime)) {
      console.log("之前就有记录");
      return

    }
    this.checkedDates.push(this.selectTime)
    console.log(this.checkedDates);

  }
  initializePicker() {
    this.pickerColumns = [
      {
        name: 'year',
        options: this.createYearOptions(),
      },
      {
        name: 'month',
        options: this.createMonthOptions(),
      },
    ];

    this.pickerButtons = [
      {
        text: '取消',
        role: 'cancel',
      },
      {
        text: '确定',
        handler: (value: { year: { value: number; }; month: { value: number; }; }) => {
          this.curYear = value.year.value;
          this.curMonth = value.month.value;
          this.updateCalendar();
        },
      },
    ];
  }

  updateCalendar() {
    const firstDay = this.getFirstDayOfMonth(this.curYear, this.curMonth);
    const daysInMonth = this.getDaysInMonth(this.curYear, this.curMonth);

    this.firstDays = this.createArray(firstDay === 0 ? 6 : firstDay - 1);
    this.curDays = this.createArray(daysInMonth);
    this.nextDaysArray = this.createArray(7 - this.getLastDayOfMonth(this.curYear, this.curMonth));
  }

  preMonth() {
    this.curMonth--;
    if (this.curMonth < 1) {
      this.curYear--;
      this.curMonth = 12;
    }
    this.updateCalendar();
  }

  nextMonth() {
    this.curMonth++;
    if (this.curMonth > 12) {
      this.curYear++;
      this.curMonth = 1;
    }
    this.updateCalendar();
  }
  formatDate(year: number, month: number, day: number): string {
    return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
  }
  selectDate(day: number) {
    this.selectedDate = day; // 选中日期
    this.selectTime = `${this.curYear}-${this.curMonth < 10 ? '0' + this.curMonth : this.curMonth}-${day < 10 ? '0' + day : day}`; // 格式化时间
    console.log("组件运作", this.selectTime);
    this.ionChange2.emit(this.selectTime);
  }

  tolast(item: number) {
    this.nextMonth();
    this.selectedDate = item; // 选中日期
  }

  topre(item: number) {
    this.preMonth();
    this.selectedDate = item; // 选中日期
  }

  async openPicker() {
    const picker = await this.pickerCtrl.create({
      columns: this.pickerColumns,
      buttons: this.pickerButtons,
    });
    await picker.present();
  }

  createArray(n: number): number[] {
    return Array.from({ length: n }, (_, index) => index + 1); // 从1开始
  }

  getDaysInMonth(year: number, month: number): number {
    return new Date(year, month, 0).getDate();
  }

  getFirstDayOfMonth(year: number, month: number): number {
    return new Date(year, month - 1, 1).getDay(); // 注意：月份是0-11
  }

  getLastDayOfMonth(year: number, month: number): number {
    return new Date(year, month, 0).getDay(); // 获取当月最后一天是星期几
  }

  createYearOptions() {
    const currentYear = new Date().getFullYear();
    const years = [];
    for (let i = currentYear - 10; i <= currentYear + 10; i++) {
      years.push({ text: `${i}`, value: i });
    }
    return years;
  }

  createMonthOptions() {
    const months = [];
    for (let i = 1; i <= 12; i++) {
      months.push({ text: `${i}`, value: i });
    }
    return months;
  }
}

