import { CommonModule } from '@angular/common';
import { Component, Input, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { IonAvatar, IonButton, IonCard, IonContent, IonItem, IonItemOption, IonItemOptions, IonItemSliding, IonLabel, IonList, IonListHeader, IonProgressBar, NavController } from '@ionic/angular/standalone';
import { addIcons } from 'ionicons';
import { arrowBackOutline } from 'ionicons/icons';
import { map, switchMap } from 'rxjs';
import { CustomHeaderComponent } from 'src/lib/component/custom-header/custom-header.component';
import { CloudObject, CloudQuery } from 'src/lib/ncloud';
addIcons({ arrowBackOutline });
@Component({
  selector: 'app-generate-result',
  templateUrl: './generate-result.component.html',
  styleUrls: ['./generate-result.component.scss'],
  standalone: true,
  imports: [IonContent, CustomHeaderComponent, IonCard, IonLabel, CommonModule, IonButton, IonAvatar,
    IonProgressBar, IonItem, IonList
  ],
})

export class GenerateResultComponent implements OnInit {
  @Input() objectId: string | null = '';
  constructor(private navCtrl: NavController, private route: ActivatedRoute) {
    this.keys.forEach(key => {
      this.detailsShown[key] = false;
    });
  }
  async ngOnInit() {
    this.route.paramMap.pipe(
      switchMap((params: ParamMap) => this.route.queryParamMap.pipe(
        map(() => params.get('resultId'))
      ))
    ).subscribe(resultId => {
      this.objectId = resultId;
      // 现在您可以使用 this.objectId
    });
    console.log("正在加载历史记录：" + this.objectId)
    this.getGenerateResult();
    this.ECScore[0] = await this.getAllData();
    this.startAnimation();
    this.ECScore[1] = this.getFunctionScore();
    this.ECScore[2] = await this.getRegionScore();
    this.ECScore[3] = await this.getDesignScore();
  }
  /**
   * @页面跳转函数
   */
  goSendPost(image: string, name: string) {
    //传递参数
    this.navCtrl.navigateForward(['/sendPost'], {
      state: { image, name }
    });
  }
  /*获取相应生成记录*/
  history: CloudObject | undefined;
  jsonData: Record<string, any> = {};
  keys: Array<string> = [];
  async getGenerateResult() {
    let query = new CloudQuery('GenerateResult');
    query.equalTo('objectId', this.objectId);
    let result = await query.find();
    this.history = result[0];
    console.log(this.history);
    this.jsonData = JSON.parse(this.history?.get('content'));
    console.log(this.jsonData);
    this.keys = Object.keys(this.jsonData['schemeList']);
    console.log(this.keys);
  }
  /**
   * @项目展开函数
   */
  /*点击切换展示状态*/
  detailsShown: Record<string, boolean> = {};
  toggleDetails(key: string) {
    this.detailsShown[key] = !this.detailsShown[key];
  }
  /*判断是否展示*/
  isDetailShown(key: string): boolean {
    return this.detailsShown[key];
  }
  /**
   * @生成记录评分函数
   */
  allData: Record<string, number> = {
    //搭配方案词典，记录出现次数
  }
  ECScore: any[] = [];
  async getAllData() {
    //获取所有生成记录，建立词典，记录出现次数
    let query = new CloudQuery('GenerateResult');
    let result = await query.find();
    for (let i = 0; i < result.length; i++) {
      let jsonData = JSON.parse(result[i]?.get('content'));
      let code = '';
      for (let key of ['季节', '功能', '区域风格', '设计理念', '艺术风格']) {
        code += jsonData[key];
      }
      if (this.allData[code]) {
        this.allData[code]++;
      }
      else {
        this.allData[code] = 1;
      }
    }
    this.allData['total'] = result.length;
    console.log(this.allData);
    //获得当前生成记录的代码数量
    let query_code = '';
    for (let key of ['季节', '功能', '区域风格', '设计理念', '艺术风格']) {
      query_code += this.jsonData[key];
    }
    const number = this.allData[query_code];
    //获得比当前生成记录代码数量更小的所有生成记录的数量
    let count = 0;
    for (let key in this.allData) {
      if (this.allData[key] < number) {
        count += this.allData[key];
      }
    }
    console.log(count)
    let score = count / this.allData['total'] * 10;
    return score.toFixed(1);
  }
  /*更改评分图标*/
  getIcon(score: string) {
    //将score转换为数字
    let num = Number(score);
    if (num == 0) {
      return 'https://s1.imagehub.cc/images/2025/01/11/fc2041e35a146350a7654ed1559f294c.png';
    }
    else if (num > 0 && num < 3) {
      return 'https://s1.imagehub.cc/images/2025/01/11/716566121c19ee91e3acbdda2ba1ca6e.png';
    }
    else if (num >= 3 && num < 6) {
      return 'https://s1.imagehub.cc/images/2025/01/11/0e5e74f3f76cee6364274ac339c15e43.png';
    }
    else if (num >= 6 && num < 7.5) {
      return 'https://s1.imagehub.cc/images/2025/01/11/e8eb352cc826f7e4cfc858cd9a239ab6.png';
    }
    else {
      return 'https://s1.imagehub.cc/images/2025/01/11/773c4fe23c418bc596aa76d993780d70.png';
    }
  }
  /*读取功能评分*/
  getFunctionScore() {
    let functionData: Record<string, number> = {}
    //读取this.allData中的每个key中的第三和第四个字符，组成functionData的key
    for (let key in this.allData) {
      let functionKey = key.charAt(2) + key.charAt(3);
      if (functionData[functionKey]) {
        functionData[functionKey] += this.allData[key];
      }
      else {
        functionData[functionKey] = this.allData[key];
      }
    }
    //获得比当前生成记录代码数量更小的所有生成记录的数量
    let count = 0;
    const funcString = this.jsonData['功能'].charAt(0) + this.jsonData['功能'].charAt(1);
    const number = functionData[funcString];
    for (let key in functionData) {
      if (functionData[key] < number) {
        count += functionData[key];
      }
    }
    console.log(count)
    let score = count / functionData['ta'];
    return score;
  }
  /*读取区域风格评分*/
  async getRegionScore() {
    let regionData: Record<string, number> = {}
    let query = new CloudQuery('GenerateResult');
    let result = await query.find();
    for (let i = 0; i < result.length; i++) {
      let jsonData = JSON.parse(result[i]?.get('content'));
      let regionKey = jsonData['区域风格'];
      if (regionData[regionKey]) {
        regionData[regionKey]++;
      }
      else {
        regionData[regionKey] = 1;
      }
    }
    regionData['total'] = result.length;
    //获得比当前生成记录代码数量更小的所有生成记录的数量
    let count = 0;
    const regionString = this.jsonData['区域风格'];
    const number = regionData[regionString];
    for (let key in regionData) {
      if (regionData[key] < number) {
        count += regionData[key];
      }
    }
    console.log(count)
    let score = count / regionData['total'];
    return score;
  }
  /*读取设计理念评分*/
  async getDesignScore() {
    let designData: Record<string, number> = {}
    let query = new CloudQuery('GenerateResult');
    let result = await query.find();
    for (let i = 0; i < result.length; i++) {
      let jsonData = JSON.parse(result[i]?.get('content'));
      let designKey = jsonData['设计理念'];
      if (designData[designKey]) {
        designData[designKey]++;
      }
      else {
        designData[designKey] = 1;
      }
    }
    designData['total'] = result.length;
    //获得比当前生成记录代码数量更小的所有生成记录的数量
    let count = 0;
    const designString = this.jsonData['设计理念'];
    const number = designData[designString];
    for (let key in designData) {
      if (designData[key] < number) {
        count += designData[key];
      }
    }
    console.log(count)
    let score = count / designData['total'];
    return score;
  }
  /**
   * @评分动画函数
   */
  animatedScore = '0.0'; // 初始评分
  animationFrame: any; // 动画帧ID
  startTime: any; // 动画开始时间
  duration: number = 3000; // 动画总时长，单位为毫秒
  easeFunction: (t: number) => number = this.easeInOutQuad; // 缓动函数

  startAnimation() {
    this.startTime = Date.now(); // 记录当前时间
    this.animationFrame = requestAnimationFrame(() => this.animate());
  }

  animate() {
    const currentTime = Date.now() - this.startTime; // 计算当前时间相对于动画开始时间的偏移量
    const ease = this.easeFunction(currentTime / this.duration); // 计算缓动值
    const targetScore = parseFloat(this.ECScore[0]); // 将目标评分转换为浮点数
    const step = (targetScore - parseFloat(this.animatedScore)) / 5; // 计算每帧评分的增量
    this.animatedScore = (parseFloat(this.animatedScore) + step * ease).toFixed(1); // 更新评分，并保留一位小数

    if (currentTime < this.duration) {
      // 如果动画未结束，则请求下一帧
      this.animationFrame = requestAnimationFrame(() => this.animate());
    } else {
      // 如果动画结束，则清除动画帧ID
      cancelAnimationFrame(this.animationFrame);
      this.animatedScore = this.ECScore[0]; // 确保最终评分与目标评分一致
    }
  }

  // 缓动函数示例：easeInOutQuad（先加速后减速）
  easeInOutQuad(t: number) {
    return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
  }
}
