import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core'

@Component({
  selector: 'app-page7',
  templateUrl: './page7.component.html',
  styleUrls: ['./page7.component.css']
})
export class Page7Component implements OnInit {
  @Input() curPageData: Array<any>
  @Input() hasMate: boolean
  @Output() getAllAnswer = new EventEmitter<any>()
  curAllQues: Object
  selectedObj: Object
  questions: Array<any>;
  constructor() {}

  ngOnInit() {
    this.curAllQues = {}
    this.selectedObj = {}
    this.questions = []
    this.setOptionSelected()
  }
  getAnswer(question, options) {
    debugger;
    //获取当前页面问题id
    const questionId = question['questionId']
    if (!this.selectedObj[questionId]) {
      this.selectedObj[questionId] = options
      options['selected'] = true
    } else {
      if (this.selectedObj[questionId].optionId != options.optionId) {
        this.selectedObj[questionId]['selected'] = false
        options['selected'] = true
        this.selectedObj[questionId] = options
      }
    }
    this.curAllQues[questionId] = options
    const questions = Object.keys(this.curAllQues).map(questionId => {
      return { questionId, 
               options: [this.curAllQues[questionId]]
              }
    })
    for (let j = 0; j < this.questions.length; j++) {
      for (let i = 0; i < questions.length; i++) {
      if (questions[i]['questionId'] != this.questions[j]['questionId']) {
        questions.push(this.questions[j]);
        break;
      }
      break;
    }
  }
    const ret = {
      pageId: 7,
      questions
    }
    // console.log(ret)
    this.getAllAnswer.emit(ret)
  }

  setOptionSelected() {
    const questions2 = this.curPageData['questions']
    // console.log(questions)
    if (!questions2) {
      return
    }
    questions2.map(question => {
      question['options'].forEach(option => {
        if (option['selected']) {
          this.selectedObj[question['questionId']] = option
        }
      })
    })

    const questions = Object.keys(this.selectedObj).map(questionId => {
      return { questionId, options: [this.selectedObj[questionId]] }
    })
    this.questions = questions
    const ret = {
      pageId: 7,
      questions
    }
    this.getAllAnswer.emit(ret)
  }
}
