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,
      name: 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)
    this.hasDisease(this.commonService.todosCopy);
  }

  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,
      optionId: e.cityId
    };
    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
        }
      };
      // 有campaignInfo表示 自动评测
      if (sessionStorage.getItem('campaignInfo')) {
        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']) {
          if (!sessionStorage.getItem('campaignInfo')) {
            this.router.navigate(['/transit3']);
          } else {
            //判断有无疾病  
            if (this.isDisease) {
              //双12活动有疾病出弹框，确定后跳活动首页
              this.autoEvaluationModal = true;
            } else {
              //无疾病判断如果是任务二或者任务三跳活动首页否则条查看方案
              const task = JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignTaskCode']
              if (task == '12task2' || task == '12task3') {
                setTimeout(() => {
                  window.location.href = `https://${window.location.host}/2019Double12/index.html?customerId=${sessionStorage.getItem('customerId')}`;
                }, 2000)
              } else {
                // 跳转到方案详情页面
                window.location.href = `https://${window.location.host}/customizedPlanList/3?orderId=${sessionStorage.getItem('orderId')}&customerId=${sessionStorage.getItem('customerId')}&leftTimes=1`;
              }

            }
          }
        } 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() {
    if (!this.loginData.mobileNo) {
      this.errorModal('请输入手机号');
      return;
    } else {
      const MOBILE_REGEXP = /^(1)\d{10}$/;
      if (!MOBILE_REGEXP.test(this.loginData.mobileNo)) {
        this.errorModal('手机号码输入有误');
        return;
      }
    }
    if (!this.loginData.code) {
      this.errorModal('请输入短信验证码');
      return;
    }
    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;
            //获取customerId后调用获取orderId接口
            if (response['data']['customerId']) {
              sessionStorage.setItem('customerId', response['data']['customerId']);
            }
            this.getOrderId();
          } else {
            // 登录失败
            this.errorModal(res['message']);
          }
        });
      } else {
        // 验证码错误
        this.errorModal(res['message']);
      }
    })
  }

  //获取orderId后调用保存问卷
  getOrderId() {
    const orderIdParam = {
      name: this.loginData.name,
      customerId: sessionStorage.getItem('customerId'),
      campaignInfo: {
        "campaignCode": JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignCode'],
        "campaignTaskCode": JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignTaskCode']
      }
    }
    this.commonService.createActivityOrder(orderIdParam).then(res => {
      if (res['success']) {
        sessionStorage.setItem('orderId', res['data']['orderId']);
        this.next();

      } 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, 83);
    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;
    window.location.href = `https://${window.location.host}/2019Double12/index.html?customerId=${sessionStorage.getItem('customerId')}`;
  }

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