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

@Component({
  selector: 'app-age',
  templateUrl: './age.component.html',
  styleUrls: ['./age.component.css']
})
export class AgeComponent implements OnInit {
  // 家庭结构
  type: any;
  curPageData: any;
  isShow: boolean;
  curQues: any;

  pageAnswers: any;
  // 可添加的孩子总个数
  totalChildLimitCount: number;
  questionSubId: number;
  question: any;
  // 上一次的答案
  lastQuestions: Array<any>;
  nextBtn: boolean = false;
  targetObj: 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.totalChildLimitCount = 2;
    this.questionSubId = 0;
    this.pageAnswers = {
      pageId: '',
      questions: [],
    };
  }

  ngOnInit() {
    this.lastQuestions = this.commonService.todosCopy.filter(item => item.pageId == 3).pop();
    this.commonService.surveyInfo().then(res => {
      this.curPageData = res['data']['survey']['pages'].filter(item => item.pageId === 3).pop();
      this.pageAnswers.pageId = this.curPageData['pageId'];
      if (this.type == 1) {
        this.handleData([3, 4]);
      } else if (this.type == 2) {
        this.handleData([4]);
      } else if (this.type == 3) {
        this.handleData([3]);
      } else {
        this.handleData([]);
      }
      if (this.lastQuestions) {
        // 检测增加了几个孩子
        const childLength = this.lastQuestions['questions'].filter(item => item.questionSubId).length;
        if (childLength > 0) {
          for (let i = 0; i < childLength; i++) {
            this.addChild();
          }
        }
        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) {
              if (this.lastQuestions['questions'][i]['questionSubId'] == this.curPageData['questions'][j]['questionSubId']) {
                this.lastQuestions['questions'][i]['options'].forEach(option => {
                  if (Object.keys(option).indexOf('optionId') > -1) {
                    this.targetObj = option;
                  }
                  this.showToast(this.curPageData['questions'][j])
                  this.selectedAge(this.targetObj);
                });
              }
            }
          }
        }
      } else {
        return;
      }
    });
  }

  // 选择年龄
  selectedAge(options) {
    const question = {
      questionId: this.curQues.questionId,
      questionSubId: this.curQues.questionSubId,
      questionName: this.curQues.questionName,
      options: [options]
    };
    for (let j = 0; j < this.curPageData['questions'].length; j++) {
      if (this.curPageData['questions'][j].questionId == this.curQues.questionId) {
        // 如果有孩子，需要考虑是孩子几的年龄
        if (this.curPageData['questions'][j]['questionSubId'] == this.curQues.questionSubId) {
          this.curPageData['questions'][j].optionName = options.optionName;
          for (let m = 0; m < this.curPageData['questions'][j].options.length; m++) {
            if (this.curPageData['questions'][j].options[m].optionId == options.optionId) {
              this.curPageData['questions'][j].options[m]['selected'] = true;
            } else {
              this.curPageData['questions'][j].options[m]['selected'] = false;
            }
          }
        }
      }
    }
    // 答案去重
    for (let i = 0; i < this.pageAnswers.questions.length; i++) {
      if (this.pageAnswers.questions[i].questionId == this.curQues.questionId) {
        if (this.pageAnswers.questions[i]['questionSubId'] == this.curQues.questionSubId) {
          const index = this.pageAnswers.questions.indexOf(this.pageAnswers.questions[i]);
          this.pageAnswers.questions.splice(index, 1);
        }
      }
    }
    this.pageAnswers.questions.push(question);
    this.commonService.addAnswer(this.pageAnswers);
    this.closeToast();
    if (this.curPageData['questions'].length == this.pageAnswers.questions.length) {
      this.nextBtn = true;
    } else {
      this.nextBtn = false;
    }
  }

  showToast(question) {
    this.isShow = true;
    this.curQues = question;
    for (let i = 0; i < question['options'].length; i++) {
      if (question.optionName == question['options'][i].optionName) {
        question['options'][i]['selected'] = true
      } else {
        question['options'][i]['selected'] = false
      }
    }

  }

  closeToast() {
    this.isShow = false;
  }

  // 增加孩子
  addChild() {
    this.totalChildLimitCount--;
    if (this.totalChildLimitCount < 0) {
      return;
    }
    // 增加问题，添加questionSubId区分孩子
    this.question = Object.assign({}, this.curPageData['questions'].filter(item => item.questionId == 4).pop());
    this.question.questionSubId = ++this.questionSubId;
    this.question.optionName = null;
    this.question.questionName = '孩子' + this.questionSubId + '年龄';
    this.curPageData['questions'].push(this.question);
    if (this.curPageData['questions'].length == this.pageAnswers.questions.length) {
      this.nextBtn = true;
    } else {
      this.nextBtn = false;
    }
  }

  // 根据家庭结构处理展示数据
  handleData(questionId) {
    for (let m = 0; m < this.curPageData['questions'].length; m++) {
      for (let n = 0; n < questionId.length; n++) {
        if (this.curPageData['questions'][m].questionId == questionId[n]) {
          const index = this.curPageData['questions'].indexOf(this.curPageData['questions'][m]);
          this.curPageData['questions'].splice(index, 1);
        }
      }
    }
  }

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

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