import {Component, OnInit} from '@angular/core';
import {CommonService} from '../common.service';
import {Router} from "@angular/router";
@Component({
  selector: 'app-family',
  templateUrl: './family.component.html',
  styleUrls: ['./family.component.css']
})
export class FamilyComponent implements OnInit {
  curPageData: Array<any>;
  pageAnswers: any;
  selectedOptionId: any;
  // 上一次的答案
  lastQuestions: Array<any>;
  nextBtn: boolean = false;

  constructor(private commonService: CommonService, private router: Router) {
    this.pageAnswers = {
      pageId: '',
      questions: [{
        questionId: '',
        questionName: '',
        options: [{optionId: '', optionName: '', optionOrder: '', selected: ''}]
      }],
    };
  }

  ngOnInit() {
    this.lastQuestions = this.commonService.todosCopy.filter(item => item.pageId == 2).pop();
    this.commonService.surveyInfo().then(res => {
      this.curPageData = res['data']['survey']['pages'].filter(item => item.pageId === 2).pop();
      // for (let i = 0; i < this.lastQuestions['questions'].length; i++) {
      //   for (let j = 0; j < this.curPageData['questions'].length; j++) {
      //     if (this.lastQuestions['questions'][i].questionId == this.curPageData['questions'][j].questionId) {
      //       for (let m = 0; m < this.lastQuestions['questions'][i].options.length; m++) {
      //         for (let n = 0; n < this.curPageData['questions'][i].options.length; n++) {
      //           if (this.lastQuestions['questions'][i].options[m].optionId == this.curPageData['questions'][i].options[n].optionId) {
      //             this.selectedFamily(this.curPageData['questions'][i].options[n]);
      //           }
      //         }
      //       }
      //     }
      //   }
      // }
      // console.log(this.curPageData)
    });
  }

//  选择家庭结构
  selectedFamily(option) {
    this.selectedOptionId = option.optionId;
    const options = this.curPageData['questions'][0]['options'];
    for (let i = 0; i < options.length; i++) {
      if (option['optionId'] == options[i]['optionId']) {
        options[i]['selected'] = true;
      } else {
        options[i]['selected'] = false;
      }
    }
    this.pageAnswers = {
      pageId: this.curPageData['pageId'],
      questions: [{
        questionId: this.curPageData['questions']['0']['questionId'],
        questionName: this.curPageData['questions']['0']['questionName'],
        options: [option]
      }],
    };
    this.commonService.addAnswer(this.pageAnswers);
    // console.log(this.pageAnswers)
    if (this.pageAnswers.questions[0].options.every((item) => {
        return item.selected;
      })) {
      this.nextBtn = true;
    } else {
      this.nextBtn = false;
    }
  }

//   下一步
  next() {
    if (this.nextBtn) {
      this.router.navigate(['/age'], {queryParams: {type: this.selectedOptionId}});
    } else {
      return;
    }

  }
}
