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';
import * as Parse from "parse"
import {NzModalRef, NzModalService} from 'ng-zorro-antd/modal';

(Parse as any).serverURL = "https://web2023.fmode.cn/parse";
// https://web2023.fmode.cn/s0210490/api/user/login
Parse.initialize("dev")

@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: '简单面',
              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 modalService: NzModalService, private route: ActivatedRoute, private router: Router) {
    this.completion = new TestChatCompletion(this.messagesList)

    this.nzOptions = this.options;
    //判断是否有未完成的进度
    this.initialize();

  }

  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() {
    const chatWindow = this.chatWindowRef.nativeElement;
    chatWindow.scrollTop = chatWindow.scrollHeight;
  }

  createReport: boolean = false
  //弹出框里面的值
  errorMessage = '';


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

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

  //是否继续上次未完成的答题
  isContinue = false;

  modalRef!: NzModalRef;

  showModal(): Promise<void> {
    return new Promise<void>((resolve) => {
      this.modalRef = this.modalService.create({
        nzTitle: '面试环节',
        nzContent: this.errorMessage,
        nzOnCancel: () => {
          this.handleCancel();
          resolve();
        },
        nzOnOk: () => {
          this.handleOk();
          resolve();
        },
      });
    });
  }

  handleOk(): void {
    this.isContinue = true;
    this.isVisible = false;
  }

  handleCancel(): void {
    this.isContinue = false;
    this.isVisible = false;
  }

  async saveUserInterviewData() {
    // 获取当前用户
    const currentUser: any = Parse.User.current();

    // 创建 LjUserInterviewData 对象
    const UserInterviewData = Parse.Object.extend('LjUserInterviewData');
    const userInterviewData = new UserInterviewData();


    // 设置指针字段 user 关联到当前用户
    userInterviewData.set('user', currentUser);
    userInterviewData.set('number', this.typeQuestion);
    userInterviewData.set('question', this.finalResult);
    userInterviewData.set('answer', this.resultAnswers);
    userInterviewData.set('userList', this.messagesListUser);
    userInterviewData.set('aiList', this.messagesList);
    //判断当前是否结束了
    let isOver = 0
    if (this.isStart != 0) {
      isOver = 1
    }
    userInterviewData.set('interviewResult', isOver);


    // 保存 LjUserInterviewData 对象到 Parse 服务器
    await userInterviewData.save().then(async (savedUserInterviewData: any) => {
      console.log(savedUserInterviewData)
    }).catch((error: any) => {
      console.error('Error saving LjUserInterviewData:', error);
    });


  }

  async initialize() {
    const currentUser: any = Parse.User.current();

    // 创建查询
    const query = new Parse.Query('LjUserInterviewData');

    // 设置查询条件为当前用户
    query.equalTo('user', currentUser);

    // 设置 interviewResult 字段降序排列
    query.descending('interviewResult');

    // 查询 LjUserInterviewData 表中当前用户的数据
    await query.find().then(async (results: any) => {
      console.log(results[0].get('interviewResult'))
      if (results[0].get('interviewResult') == 1) {
        this.errorMessage = '您有未完成的面试环节,请问您是否要继续';
        await this.showModal()
        if (this.isContinue) {
          console.log("继续面试")
          this.messagesListUser = results[0].get('userList');
          this.finalResult = results[0].get('question');
          this.resultAnswers = results[0].get('answer');
          this.messagesList = results[0].get('aiList');
          this.typeQuestion = results[0].get('number');
          this.isStart = results[0].get('interviewResult');
        }

      }
    });
  }

  async getUserInterviewData() {
    // 获取当前用户
    const currentUser: any = Parse.User.current();

    // 创建查询
    const query = new Parse.Query('LjUserInterviewData');

    // 设置查询条件为当前用户
    query.equalTo('user', currentUser);

    // 设置 interviewResult 字段降序排列
    query.descending('interviewResult');

    // 查询 LjUserInterviewData 表中当前用户的数据
    await query.find().then(async (results: any) => {
      console.log(results.length)
      if (results[0].get('interviewResult') != 0) {
        const userInterviewData = results[0];

        // 修改数据
        userInterviewData.set('number', this.typeQuestion);
        userInterviewData.set('question', this.finalResult);
        userInterviewData.set('answer', this.resultAnswers);
        userInterviewData.set('userList', this.messagesListUser);
        userInterviewData.set('aiList', this.messagesList);
        userInterviewData.set('interviewResult', this.isStart);

        //判断当前是否结束了
        let isOver = 0;
        if (this.isStart != 0) {
          isOver = 1;
        }
        userInterviewData.set('interviewResult', isOver);

        // 保存修改后的数据
        await userInterviewData.save().then((savedUserInterviewData: any) => {
          console.log('User Interview Data updated:', savedUserInterviewData);
        }).catch((error: any) => {
          console.error('Error updating User Interview Data:', error);
        });
      } else {
        await this.saveUserInterviewData()
        console.log("saveU")
      }

    }).catch((error: any) => {
      console.error('Error retrieving User Interview Data:', error);
    });
  }

  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.isStart = 0
      await this.getUserInterviewData()
      this.typeQuestion = 0
      this.createReport = true
      this.messagesListUser.push({
        role: "user",
        content: this.inputText += '回答完毕',
      });
      this.scrollToBottom()
      this.messagesListUser.push(
        {
          role: 'user',
          content: "感谢您的回答,请稍等,正在生成报告.....",
        }
      )
      this.scrollToBottom()
      setTimeout(async () => {
        await this.createAiReport()
      }, 1000)


    } else {
      if (this.isStart == 0) {
        this.messagesListUser.push({
            role: "user",
            content: "开始面试",
          },
          {
            role: "assistant",
            content: "请等待,对话生成中....."
          });
        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
        });
        this.scrollToBottom()

        this.isStart++;
        this.typeQuestion++;
        await this.getUserInterviewData()


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

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

          this.messagesListUser.push(
            {
              role: "assistant",
              content: this.finalResult[this.typeQuestion].question
            }
          );
          console.log(this.resultAnswers);
          this.scrollToBottom()
          this.inputText = "";
          // 将滚动条滚动到底部
          this.typeQuestion++;
          await this.getUserInterviewData()
        } else {
          this.errorMessage = '您的输入为空，请检查输入';
          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,
        }
      );
      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])
  }


}


