import { Component, OnInit } from '@angular/core';
import { CommonService } from '../common.service';
import { ActivatedRoute, Router } from "@angular/router";

@Component({
  selector: 'app-health',
  templateUrl: './health.component.html',
  styleUrls: ['./health.component.css']
})
export class HealthComponent implements OnInit {
  // 问题数据
  curPageData: any;
  // 获取是您的健康情况还是配偶的健康情况
  id: any;
  // 获取家庭结构
  type: any;
  // 本页面答案
  pageAnswers: any;
  // 暂存健康状况
  questions: Array<any> = [];
  nextBtn: boolean = false;
  lastQuestions: Array<any>;

  constructor(private commonService: CommonService,
    private router: Router,
    private route: ActivatedRoute) {
    /**
     * 1:单身贵族
     * 2：二人世界
     * 3：独立带娃
     * 4：多口之家
     * @type {any}
     */
    this.type = this.route.snapshot.queryParams['type'];
    this.id = this.route.snapshot['data']['0']['id'];
    this.pageAnswers = {
      pageId: '',
      questions: [{
        questionId: '',
        questionName: '',
        options: [{ optionId: '', optionName: '', optionOrder: '', selected: '' }]
      }],
    };
  }

  ngOnInit() {
    if (this.id == 1) {
      this.lastQuestions = this.commonService.todosCopy.filter(item => item.pageId == 11).pop();
    } else {
      this.lastQuestions = this.commonService.todosCopy.filter(item => item.pageId == 12).pop();
    }

    this.surveyInfo();
  }

  surveyInfo() {
    this.commonService.surveyInfo().then(res => {
      if (res['success']) {
        if (this.id == 1) {
          this.curPageData = res['data'].survey.pages['10'];
          if (this.lastQuestions) {
            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) {
                  this.lastQuestions['questions'][i]['options'].forEach(option => {
                    if (Object.keys(option).indexOf('optionId') > -1) {
                      const targetObj = option;
                      this.curPageData['questions'][j]['options'].forEach(option => {
                        if (targetObj['optionId'] == option['optionId']) {
                          this.curPageData['questions'][j]['options'][this.curPageData['questions'][j]['options'].indexOf(option)] = targetObj;
                        }
                      });
                      this.selectedHealth(targetObj, true);
                    }
                  });
                }
              }
            }
          }

        } else {
          this.curPageData = res['data'].survey.pages['11'];
          if (this.lastQuestions) {
            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) {
                  this.lastQuestions['questions'][i]['options'].forEach(option => {
                    if (Object.keys(option).indexOf('optionId') > -1) {
                      const targetObj = option;
                      this.curPageData['questions'][j]['options'].forEach(option => {
                        if (targetObj['optionId'] == option['optionId']) {
                          this.curPageData['questions'][j]['options'][this.curPageData['questions'][j]['options'].indexOf(option)] = targetObj;
                        }
                      });
                      this.selectedHealth(targetObj, true);
                    }
                  });
                }
              }
            }
          }

        }
      }
    })
  }

  // 选择健康情况（多选）
  selectedHealth(option, lastFlag) {
    if (lastFlag === false) {
      option['selected'] = !option['selected'];
    }
    this.questions = [];
    if (this.id == 1) {
      this.getOptions(67, option);
    } else if (this.id == 2) {
      this.getOptions(83, option);
    }
    this.pageAnswers = {
      pageId: this.curPageData['pageId'],
      questions: [{
        questionId: this.curPageData['questions']['0']['questionId'],
        questionName: this.curPageData['questions']['0']['questionName'],
        options: this.questions
      }],
    };
    this.commonService.addAnswer(this.pageAnswers);
    if (this.curPageData['questions'].length == this.pageAnswers.questions.length) {
      if (this.pageAnswers.questions.every(item => item.options.length > 0)) {
        this.nextBtn = true;
      } else {
        this.nextBtn = false;
      }
    } else {
      this.nextBtn = false;
    }
  }

  // 获取所有用户选择的健康选项
  getOptions(nonDiseaseOptionId, option) {
    for (let i = 0; i < this.curPageData['questions'][0]['options'].length; i++) {
      if (option.optionId == nonDiseaseOptionId && option['selected']) {
        this.curPageData['questions'][0]['options'][i]['selected'] = false;
        if (this.curPageData['questions'][0]['options'][i]['optionId'] == nonDiseaseOptionId) {
          this.curPageData['questions'][0]['options'][i]['selected'] = true;
        }
      } else {
        if (this.curPageData['questions'][0]['options'][i]['optionId'] == nonDiseaseOptionId) {
          this.curPageData['questions'][0]['options'][i]['selected'] = false;
        }
      }
      // 拿到所有selected为true的选项
      if (this.curPageData['questions'][0]['options'][i]['selected']) {
        this.questions.push(this.curPageData['questions'][0]['options'][i]);
      }
    }
  }

  //   下一步
  next() {
    if (this.nextBtn) {
      // 如果是二人世界或是多口之家跳转到配偶页
      // 先判断当前页是您的页还是配偶页
      if (this.id == 1) {
        if (this.type == 2 || this.type == 4) {
          this.router.navigate(['/spouse_health'], { queryParams: { type: this.type } });
        } else if (this.type == 3) {
          this.router.navigate(['/children_health', 1], {
            queryParams: {
              type: this.type
            }
          });
        } else if (this.type == 1) {
          this.router.navigate(['/disease'], { queryParams: { type: this.type } });
        }
      } else {
        if (this.type == 1 || this.type == 2) {
          this.router.navigate(['/disease'], { queryParams: { type: this.type } });
        } else if (this.type == 3 || this.type == 4) {
          this.router.navigate(['/children_health', 1], {
            queryParams: {
              type: this.type
            }
          });
        } else {
          this.router.navigate(['/disease'], { queryParams: { type: this.type } });
        }
      }
    } else {
      return;
    }

  }

  //  上一步
  before() {
    this.commonService.before();
  }
}
