import {Component, ElementRef, ViewChild, OnInit} from '@angular/core';
import {trigger, state, style, animate, transition} from '@angular/animations';
import {TestChatCompletion, TestChatMessage} from '../class-chat-completion';
import {ActivatedRoute} from '@angular/router';
import {NzCascaderOption} from "ng-zorro-antd/cascader";
import {Router} from '@angular/router';

@Component({
  selector: 'app-mock-interviews',
  templateUrl: './mock-interviews.component.html',
  styleUrls: ['./mock-interviews.component.scss'],
  animations: [
    trigger('fadeAnimation', [
      state('visible', style({opacity: 1})),
      state('hidden', style({opacity: 0})),
      transition('visible => hidden', animate('500ms')),
    ])
  ]
})
export class MockInterviewsComponent {
  showContent: boolean = false;
  showProgress: boolean = false;
  progress: number = 0;

  finalResult: Array<any> = []
  resultAnswers: Array<any> = []

  startAnimation() {
    this.showProgress = true;
    this.showContent = true;
  }

  completion: TestChatCompletion


  nzOptions: NzCascaderOption[];
  options = [
    {
      value: '阿里面试官',
      label: '阿里面试官',
      children: [
        {
          value: '技术面试',
          label: '技术面试',
          children: [
            {
              value: '简单面',
              label: '简单面',
              isLeaf: true
            },
            {
              value: '中等难',
              label: '中等难',
              isLeaf: true
            },
            {
              value: '技术牛',
              label: '技术牛',
              isLeaf: true
            },
          ]
        },
      ]
    },
    {
      value: '华为面试官',
      label: '华为面试官',
      children: [
        {
          value: '技术面试',
          label: '技术面试',
          children: [
            {
              value: '简单面',
              label: '简单面',
              isLeaf: true
            },
            {
              value: '中等难',
              label: '中等难',
              isLeaf: true
            },
            {
              value: '技术牛',
              label: '技术牛',
              isLeaf: true
            },
          ]
        },
      ]
    },
    {
      value: '苹果面试官',
      label: '苹果面试官',
      children: [
        {
          value: '技术面试',
          label: '技术面试',
          children: [
            {
              value: '简单面',
              label: '简单面',
              isLeaf: true
            },
            {
              value: '中等难',
              label: '中等难',
              isLeaf: true
            },
            {
              value: '技术牛',
              label: '技术牛',
              isLeaf: true
            },
          ]
        },
      ]
    }
  ];


  constructor(private route: ActivatedRoute, private router: Router) {
    this.completion = new TestChatCompletion(this.messagesList)

    this.nzOptions = this.options;

  }

  messagesList: Array<TestChatMessage> = [
    {
      role: "assistant",
      content: "哈喽我的您的面试官,请点击发送,我们将准备开始面试"
    },
  ]
  messagesListUser: Array<TestChatMessage> = [
    {
      role: "assistant",
      content: "哈喽我的您的面试官,请点击发送,我们将准备开始面试"
    },
  ]


  inputText = '';

  getAvatar(role: string): string {
    if (role === 'assistant') {
      return 'assets/images/page-mine/myAvatar.png';
    } else {
      return 'assets/images/page-mine/myAvatar.png';
    }
  }

  getReceived(role: string): boolean {
    return role !== 'assistant';
  }

  handleShiftEnter() {
    this.inputText += '\n';
  }

  async handleEnter() {
    await this.send()
  }

  handleKeyDown(event: KeyboardEvent) {
    if (event.shiftKey && event.key === 'Enter') {
      event.preventDefault()
      this.handleShiftEnter();
    } else if (event.key === 'Enter') {
      event.preventDefault()
      this.handleEnter();
    }
  }

  isStart: number = 0
  typeQuestion: number = 0;

  @ViewChild('chatWindow') chatWindowRef!: ElementRef;
  @ViewChild('chatContainer') chatContainerRef!: ElementRef;

  // 滚动到底部
  scrollToBottom() {
    console.log(1)
    const chatWindow = this.chatWindowRef.nativeElement;
    chatWindow.scrollTop = chatWindow.scrollHeight;
    const chatContainer = this.chatContainerRef.nativeElement;
    const chatWindowOther = chatContainer.querySelector('.chat-window');
    chatWindowOther.scrollTop = chatWindowOther.scrollHeight;
  }

  createReport: boolean = false


  async handleButton() {
    try {
      await this.send()
    } catch (e) {
      console.log(e)
    }
  }

  //空消息弹出提示框
  isVisible = false;

  showModal(): void {
    this.isVisible = true;
  }

  handleOk(): void {
    console.log('Button ok clicked!');
    this.isVisible = false;
  }

  handleCancel(): void {
    console.log('Button cancel clicked!');
    this.isVisible = false;
  }

  async send() {
// if (this.isStart == 0) {
    //   this.getQuestion()
    //   this.isStart += 1
    // }
    // if (this.isStart == 1) {
    //   this.messagesList.push({
    //     role: "user",
    //     content: "开始面试",
    //   });
    //   this.inputText = "";
    //   this.completion.createCompletionByStream();
    //   this.isStart += 1
    //   return;
    // }
    console.log(this.typeQuestion)
    if (this.typeQuestion == 9) {
      this.typeQuestion = 0
      this.createReport = true
      this.messagesListUser.push({
        role: "user",
        content: this.inputText += '回答完毕',
      });
      await this.scrollToBottom()
      this.messagesListUser.push(
        {
          role: 'user',
          content: "感谢您的回答,请稍等,正在生成报告.....",
        }
      )
      await this.scrollToBottom()
      setTimeout(async () => {
        await this.createAiReport()
      }, 1000)


    } else {
      if (this.isStart == 0) {
        this.messagesListUser.push({
            role: "user",
            content: "开始面试",
          },
          {
            role: "assistant",
            content: "请等待,对话生成中....."
          });
        await this.scrollToBottom()


        await this.getQuestion();


        console.log(this.finalResult);
        console.log(this.finalResult[0].question);
        this.messagesListUser.push({
          role: "assistant",
          content: this.finalResult[this.typeQuestion].question
        });
        await this.scrollToBottom()


        this.isStart++;
        this.typeQuestion++;


      } else {
        if (this.inputText != '') {

          console.log(this.inputText);
          this.messagesListUser.push({
            role: "user",
            content: this.inputText += '回答完毕',
          });
          await this.scrollToBottom()
          this.resultAnswers.push(this.inputText);

          this.messagesListUser.push(
            {
              role: "assistant",
              content: this.finalResult[this.typeQuestion].question
            }
          );
          console.log(this.resultAnswers);
          this.inputText = "";
          // 将滚动条滚动到底部
          await this.scrollToBottom()

          this.typeQuestion++;
        } else {
          this.showModal()
          return

        }

      }

    }
  }

  allAnswerStr: String = '';

  async createAiReport() {
    return new Promise(async (resolve, reject) => {
      //所有回答字符串
      for (let str of this.resultAnswers) {
        this.allAnswerStr += str + '\n';
      }
      console.log(this.allAnswerStr);
      this.messagesList.push(
        {
          role: "user",
          content: "下列是我对您提出的问题的回答," +
            this.allAnswerStr + '\n' +
            "请帮我针对每个回答进行评分,然后支出每条回答里面存在的问题和可以改进的地方,请十分详细的给出,并且严格按照下面的格式" +
            "提出的问题......" +
            "我的回答........" +
            "我的回答存在的问题" +
            "我的回答可以改进的地方" + '\n',
        });
      await this.completion.createCompletionByStream();
      console.log(this.messagesList[this.messagesList.length - 1]);
      this.messagesListUser.splice(this.messagesListUser.length - 1, 1);
      this.messagesListUser.push(
        {
          role: 'assistant',
          content: this.messagesList[this.messagesList.length - 1].content,
        }
      );
      await this.scrollToBottom()
      resolve(undefined);
    });
  }

  async getQuestion() {
    return new Promise(async (resolve, reject) => {
      if (this.selectedValue[0]) {
        this.messagesList.push({
          role: "user",
          content: "您需要扮演一名" + this.selectedValue[0] + "公司的技术总监刘，并主持一场，" + this.selectedValue[1] + "岗位招聘的第二轮技术面试。\n" +
            "当前招聘前端开发工程师，需要熟悉HTML,JS,CSS基础，会Angular前端框架的优先，具有nodejs使用经验的优先。\n" +
            "您是比较负责且严谨的面试官，提问内容" + this.selectedValue[2] + "。\n" +
            "接下来，请您根据面试岗位招聘要求，分别从技术能力、团队协作、职业规划三个方面想出一个面试问题。\n" +
            "请严格按照下列格式来生成问题,而且您只需要严格按照下列格式生成问题即可,我之后会给您我的回答,强调一点,你生成的回答不需要任何的修饰,只需要按照下列格式来生成响应的问题即可,注意#后面不要用空格" +

            "#技术能力方面:" +
            "1." +
            "2." +
            "3." +
            "#团队协作方面:" +
            "1." +
            "2." +
            "3." +
            "#职业规划方面:" +
            "1." +
            "2." +
            "3."
        });
      } else {
        this.messagesList.push({
          role: "user",
          content: "您需要扮演一名华为公司的技术总监刘，并主持一场，后端开发岗位招聘的第二轮技术面试。\n" +
            "当前招聘前端开发工程师，需要熟悉HTML,JS,CSS基础，会Angular前端框架的优先，具有nodejs使用经验的优先。\n" +
            "您是比较负责且严谨的面试官，提问内容是面向高级后端工程师的难度。\n" +
            "接下来，请您根据面试岗位招聘要求，分别从技术能力、团队协作、职业规划三个方面各想出三个面试问题。\n" +
            "请严格按照下列格式来生成问题,而且您只需要严格按照下列格式生成问题即可,我之后会给您我的回答,强调一点,你生成的回答不需要任何的修饰,只需要按照下列格式来生成响应的问题即可" +

            "技术能力方面:" +
            "1." +
            "2." +
            "3." +
            "团队协作方面:" +
            "1." +
            "2." +
            "3." +
            "职业规划方面:" +
            "1." +
            "2." +
            "3."
        });
      }

      await this.completion.createCompletionByStream();
      console.log(this.messagesList[this.messagesList.length - 1]);

      //正则
      const regex = /(.+?):\n([\s\S]+?)(?=\n\n|$)/g;

      let match;
      while ((match = regex.exec(this.messagesList[this.messagesList.length - 1].content))) {
        const typeSection = match[1].trim();
        const questionSection = match[2].trim();
        const type = typeSection.split('\n')[0];

        const questionRegex = /(\d+)\.\s(.+)/g;
        let questionMatch;
        while ((questionMatch = questionRegex.exec(questionSection))) {
          const questionNumber = questionMatch[1];
          const question = questionMatch[2];

          this.finalResult.push({
            type,
            question: `${questionNumber}. ${question}`,
          });
        }
      }

      console.log(this.finalResult);

      // 删除"请等待,对话生成中....."
      await this.messagesListUser.splice(this.messagesListUser.length - 1, 1);


      // if () {
      //   console.log(technicalAbilityQuestions)
      //   console.log(teamworkQuestions)
      //   console.log(careerPlanningQuestions);
      //   console.log(this.formattedQuestionsArray)
      // } else {
      //   this.messagesListUser.push(
      //     {
      //       role: 'assistant',
      //       content: "生成失败,请检查余额",
      //     }
      //   )
      // }


      // this.messagesListUser.push({
      //   role: 'assistant',
      //   content: this.messagesList[this.messagesList.length - 1].content,
      // });
      resolve(undefined);
    });

  }

  //路由跳转默认进入逻辑
  selectedIndex = 0;


  ngOnInit() {
    this.route.queryParams.subscribe(params => {
      console.log(params)
      this.selectedIndex = params['tabIndex'] || 0;
    });
  }

  //级联数据
  selectedValue: any[] = []


  onChanges(values: string[]): void {
    console.log(values);
  }

  //联级的确认按钮
  isLoadingOne = false;

  loadOne(): void {
    this.isLoadingOne = true;
    setTimeout(() => {
      this.isLoadingOne = false;
      this.handleClick()
    }, 1000);

  }

  handleClick(): void {
    this.selectedIndex = 2
    console.log(this.selectedValue)
    console.log(this.selectedValue[0])
  }


}


