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

@Component({
  selector: 'app-live',
  templateUrl: './live.component.html',
  styleUrls: ['./live.component.css']
})
export class LiveComponent implements OnInit {
  curPageData: any;
  provinceList: Array<any>;
  isShow: boolean;
  provinceId: number;
  provinceName: string;
  cityList: Array<any>;
  // 页面是否显示地址
  showAddress: boolean;
  // 入参地址
  address: any;
  // 页面地址
  strAddress: string;
  pageAnswers: any;
  type: any;
  nextBtn: boolean;
  lastQuestions: Array<any>;
  tipsFlag: boolean;
  loginModalFlag: boolean;
  timeHtml: string = '获取验证码';
  loginData: any;
  tipsHtml: any;
  timeCount: number = 60;
  timer: any;
  sendBtnFlag: boolean;
  // 是否有疾病
  isDisease: boolean = true;
  // 不能进行自动评测
  autoEvaluationModal: boolean;

  constructor(private commonService: CommonService,
              private router: Router,
              private route: ActivatedRoute) {
    this.type = this.route.snapshot.queryParams['type'];
    this.pageAnswers = {
      pageId: '',
      questions: [{
        questionId: '',
        questionName: '',
        options: [{optionId: '', optionName: '', optionOrder: '', selected: ''}]
      }],
    };
    this.loginData = {
      mobileNo: null,
      code: null
    };
  }

  ngOnInit() {
    this.nextBtn = false;
    this.showAddress = false;
    this.tipsFlag = false;
    this.lastQuestions = this.commonService.todosCopy.filter(item => item.pageId == 16).pop();
    // 获取省份
    this.commonService.provinceqry({insurerId: 11}).then(res => {
      if (res['success']) {
        this.provinceList = res['data'].provinceList;
      }
    })
    setTimeout(() => {
      this.surveyInfo()
    }, 200)


  }

  surveyInfo() {

    // 获取问题
    this.commonService.surveyInfo().then(res => {
      if (res['success']) {
        this.curPageData = res['data']['survey'].pages['15'];
        if (this.lastQuestions) {
          let customerInput = this.lastQuestions['questions'][0]['options'][0]['customerInput']
          customerInput = customerInput.split(',')
          const left = customerInput[0]
          const right = customerInput[1]
          if (this.provinceList.length > 0) {
            for (let i = 0; i < this.provinceList.length; i++) {
              if (this.provinceList[i].provinceName == left) {
                this.selectProvince(this.provinceList[i])

              }
            }
          }
          setTimeout(() => {
            for (let j = 0; j < this.cityList.length; j++) {
              if (this.cityList[j].cityName == right) {
                this.selectCity(this.cityList[j])
              }
            }
          }, 200)

        }

      }
    })

  }

  showToast() {
    this.isShow = true
  }

  selectProvince(option) {
    this.provinceName = option.provinceName;
    this.provinceId = option.provinceId;
    for (let i = 0; i < this.provinceList.length; i++) {
      if (option['provinceId'] == this.provinceList[i]['provinceId']) {
        this.provinceList[i]['selected'] = true;
      } else {
        this.provinceList[i]['selected'] = false;
      }
    }
    this.getCityqry();
  }

  closeToast() {
    this.isShow = false;
  }

  getCityqry() {
    const param = {
      insurerId: 11,
      provinceId: this.provinceId
    }
    this.commonService.getCityqry(param).then(res => {
      if (res['success']) {
        this.cityList = res['data'].cityList;
      }
    })
  }

  selectCity(e) {
    this.showAddress = true;
    this.strAddress = this.provinceName + e.cityName;
    this.address = {
      customerInput: this.provinceName + ',' + e.cityName
    };
    this.pageAnswers = {
      pageId: this.curPageData['pageId'],
      questions: [{
        questionId: this.curPageData['questions']['0']['questionId'],
        questionName: this.curPageData['questions']['0']['questionName'],
        options: [this.address]
      }],
    };
    this.commonService.addAnswer(this.pageAnswers);
    if (this.pageAnswers['questions'].length > 0) {
      this.nextBtn = true;
    } else {
      this.nextBtn = false;
    }
  }

  next() {
    if (this.nextBtn == true) {
      const param = {
        survey: {
          customerId: sessionStorage.getItem('customerId'),
          orderId: sessionStorage.getItem('orderId'),
          pages: this.commonService.todosCopy
        }
      };
      // questionnaireSource 为 1 表示 自动评测
      if (sessionStorage.getItem('questionnaireSource') === '1') {
        if (!param || !param.survey.customerId || param.survey.customerId === 'null' || param.survey.customerId === 'undefined') {
          this.loginModalFlag = true;
          return;
        }
      }
      this.commonService.saveCustomerAnwers(param).then(res => {
        if (res['success']) {
          this.router.navigate(['/transit3']);
        } else {
          this.tipsFlag = true;
          this.errorModal('提交失败，请稍后重试');
          setTimeout(() => {
            this.tipsFlag = false;
          }, 2000)
        }
      });
    } else {
      return;
    }

  }

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

//  获取验证码
  sendCode() {
    if (this.sendBtnFlag) {
      return;
    }
    const MOBILE_REGEXP = /^(1)\d{10}$/;
    if (!this.loginData.mobileNo || (this.loginData.mobileNo && !MOBILE_REGEXP.test(this.loginData.mobileNo))) {
      this.errorModal('手机号码输入有误');
      return;
    } else if (this.loginData.mobileNo) {
      this.commonService.verificationCode({mobileNo: this.loginData.mobileNo, type: '1'}).then(res => {
        if (res['success']) {
          this.sendBtnFlag = true;
          this.errorModal('发送成功');
          this.timer = setInterval(() => {
            this.timeCount--;
            this.timeHtml = `${this.timeCount}(S)`;
            if (this.timeCount <= 0) {
              clearInterval(this.timer);
              this.timeCount = 60;
              this.timeHtml = '重新获取';
              this.sendBtnFlag = false;
            }
          }, 1000)
        } else {
          this.errorModal(res['message'])
        }
      })
    }
  }

// 注册
  loginIn() {
    this.commonService.compare({
      'mobileNo': this.loginData.mobileNo,
      'verificationCode': this.loginData.code,
      'expireTime': '3600'
    }).then(res => {
      if (res['success']) {
        // 登录
        this.commonService.login({'mobileNo': this.loginData.mobileNo}).then(response => {
          if (response['success']) {
            // 登录成功
            this.loginModalFlag = false;
            this.hasDisease(this.commonService.todosCopy);
            if (this.isDisease) {
              this.autoEvaluationModal = true;
            } else {
              // 跳转到方案详情页面
              // window.location.href = `http://localhost:4200/customizedPlanList/3?orderId=14793&customerId=16`;
            }
          } else {
            // 登录失败
            this.errorModal(res['message']);
          }
        });
      } else {
        // 验证码错误
        this.errorModal(res['message']);
      }
    })
  }

// 判断家庭是否存在疾病
  hasDisease(arr) {
    const selfArr = arr.filter(item => item.pageId === 11).pop();
    const selfQuestionsArr = selfArr.questions || [];
    const spouseArr = arr.filter(item => item.pageId === 12).pop();
    const spouseQuestionsArr = spouseArr ? spouseArr.questions : [];
    const childrenArr = arr.filter(item => item.pageId === 13).pop();
    const childrenQuestionsArr = childrenArr ? childrenArr.questions : [];
    this.diseaseQuestions(selfQuestionsArr, 13, 67);
    this.diseaseQuestions(spouseQuestionsArr, 14, 84);
    this.diseaseQuestions(childrenQuestionsArr, 15, 99);
  }

// 循环疾病选项
  diseaseQuestions(arr, questionId, optionId) {
    if (arr && arr.length > 0) {
      arr.forEach((item, index, arr) => {
        item.options.forEach((list, i, array) => {
          if (item.questionId === questionId && list.optionId !== optionId) {
            this.isDisease = true;
            return;
          } else {
            this.isDisease = false;
            return;
          }
        });
      });
    }

  }

// 不能进行自动评测
  confirm() {
    this.autoEvaluationModal = false;
  }

//  报错信息弹窗
  errorModal(errorText) {
    this.tipsFlag = true;
    this.tipsHtml = errorText;
    setTimeout(() => {
      this.tipsFlag = false;
    }, 2000)
  }
}
