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

@Component({
  selector: "app-children-health",
  templateUrl: "./children-health.component.html",
  styleUrls: ["./children-health.component.css"]
})
export class ChildrenHealthComponent implements OnInit {
  // 问题数据
  curPageData: any;
  // 获取是第几个孩子的健康状况
  id: any;
  // 获取家庭结构
  type: any;
  // 本页面答案
  pageAnswers: any;
  // 暂存健康状况
  questions: Array<any> = [];
  // 总共有几个孩子
  childTotalCount: any;
  // 暂存多个孩子的答案
  childTotalQuestions: 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.params["childId"];
    this.pageAnswers = {
      pageId: "",
      questions: [
        {
          questionId: "",
          questionName: "",
          options: [
            { optionId: "", optionName: "", optionOrder: "", selected: "" }
          ]
        }
      ]
    };
  }

  ngOnInit() {
    this.surveyInfo();
  }

  // 选择健康情况（多选）
  selectedHealth(option, lastFlag) {
    if (lastFlag === false) {
      option["selected"] = !option["selected"];
    }
    this.id = this.route.snapshot.params["childId"];
    this.questions = [];
    this.getOptions(99, option);
    const questions = {
      questionId: this.curPageData["questions"]["0"]["questionId"],
      questionName: "孩子" + ((this.id - 1) === 0 ? "" : (this.id - 1)) + "的健康状态",
      childId: this.id,
      options: this.questions
    };
    for (let i = 0; i < this.childTotalQuestions.length; i++) {
      if (this.childTotalQuestions[i].childId == questions.childId) {
        this.childTotalQuestions.splice(
          this.childTotalQuestions.indexOf(this.childTotalQuestions[i]),
          1
        );
        break;
      }
    }
    this.childTotalQuestions.push(questions);
    this.pageAnswers = {
      pageId: this.curPageData["pageId"],
      questions: this.childTotalQuestions
    };
    if (this.pageAnswers.questions.every(item => item.options.length > 0)) {
      this.nextBtn = true;
    } else {
      this.nextBtn = false;
    }
    this.commonService.addAnswer(this.pageAnswers);
  }

  // 获取所有用户选择的健康选项
  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]);
      }
    }
  }

  surveyInfo() {
    this.commonService.surveyInfo().then(res => {
      if (res["success"]) {
        this.curPageData = res["data"]["survey"].pages["12"];
        this.lastQuestions = this.commonService.todosCopy
          .filter(item => item.pageId == 13)
          .pop();
        this.id = this.route.snapshot.params["childId"];
        for (let j = 0; j < this.curPageData["questions"].length; j++) {
          this.curPageData["questions"][j]["questionName"] = "孩子" + ((this.id - 1) === 0 ? "" : (this.id - 1)) + "的健康状态";
          break;
        }
        if (this.lastQuestions) {
          this.childTotalQuestions = this.lastQuestions["questions"];
          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.id == this.lastQuestions["questions"][i]["childId"]) {
                  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);
                      }
                    }
                  );
                }
              }
            }
          }
        }
      }
    });
  }

  //   下一步
  next() {
    const age = this.commonService.todosCopy
      .filter(item => item.pageId == 3)
      .pop();
    this.childTotalCount = age["questions"].filter(
      item => item.questionId == 4
    ).length;
    if (this.nextBtn) {
      this.id = this.route.snapshot.params["childId"];
      // 查看有几个孩子，一个直接跳到疾病页，多个跳多个孩子页
      if (this.id < parseInt(this.childTotalCount, 0)) {
        this.router.navigate(["/children_health", parseInt(this.id, 0) + 1], {
          queryParams: {
            type: this.type
          }
        });
        this.nextBtn = false;
        this.surveyInfo();
      } else {
        this.router.navigate(["/disease"], {
          queryParams: { type: this.type }
        });
      }
    } else {
      return;
    }
  }

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