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;
  curQues: any;

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

  ngOnInit() {
    this.deviceType = this.checkDeviceType();
    this.disabled = false;
    this.lastQuestions = this.commonService.todosCopy.filter(item => item.pageId == 3).pop();
    this.surveyInfo();
  }

  surveyInfo() {
    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.selectedAge(this.curPageData['questions'][j], this.targetObj);
                });
              }
            }
          }
        }
      } else {
        return;
      }
    });
  }

  // 选择年龄
  selectedAge(questions, options) {
    this.curQues = questions;
    if (options) {
      for (let n = 0; n < options.length; n++) {
        if (this.curQues.optionName == options[n]['optionName']) {
          options = options[n];
        }
      }
    }
    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);
    if (this.curPageData['questions'].length == this.pageAnswers.questions.length) {
      this.nextBtn = true;
    } else {
      this.nextBtn = 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;
    }
    this.totalPage = Number(this.totalPage) + 1;
  }

  //删除孩子
  deleteChild(questionSubId) {
    this.totalChildLimitCount++;
    if (this.totalChildLimitCount >= 3) {
      return;
    }
    if (this.question['questionSubId'] == questionSubId) {
      this.curPageData['questions'] = this.curPageData['questions'].filter(item => item.questionSubId != questionSubId)
      this.question.questionSubId = --this.questionSubId;
      console.log(this.curPageData['questions'])
      for (let i = 0; i < this.curPageData['questions'].length; i++) {

      }
      // this.commonService.removeAnswer(this.curPageData['questions'])
    }
    this.totalPage = Number(this.totalPage) - 1;
  }

  // 根据家庭结构处理展示数据
  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, totalPage: this.totalPage } });
    } else {
      return;
    }
  }

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

  /**
 * 检测设备信息
 * deviceType:PC为1,移动端为2,微信为3
 */
  checkDeviceType() {
    let deviceType = null;
    if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
      if (navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1) {
        deviceType = 3;
      } else {
        deviceType = 2;
      }
    } else {
      deviceType = 1;
    }
    return deviceType;
  }
}
