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

// declare let returnCitySN: any;
let returnCitySN: any = {
  cip: '',
  cname: ''
};

@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;
  selfDisease: boolean = false;
  spouseDisease: boolean = false;
  childrenDisease: boolean = false;
  cityName: string;
  curPage: any;
  totalPage: any;
  constructor(private commonService: CommonService,
    private router: Router,
    private route: ActivatedRoute) {
    this.type = this.route.snapshot.queryParams['type'];
    this.totalPage = this.route.snapshot.queryParams['totalPage'];
    this.curPage = this.route.snapshot.queryParams['curPage'];
    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], 'isReturn')
              }
            }
          }, 300)
        }
      }
    })
  }

  showToast() {
    this.isShow = true
  }

  selectProvince(option) {
    if (this.provinceName != option.provinceName) {
      this.cityName = null;
      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, isReturn?: any) {
    this.showAddress = true;
    this.cityName = e.cityName;
    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;
    }
    if (!isReturn) {
      this.next(null);
    }
  }

  next(type) {
    if (this.nextBtn == true) {
      const param = {
        survey: {
          customerId: sessionStorage.getItem('customerId'),
          orderId: sessionStorage.getItem('orderId'),
          shareCode: sessionStorage.getItem('shareCode'),
          pages: this.commonService.todosCopy
        },
        ipInfo: {
          ipAddress: returnCitySN['cip'] ? returnCitySN['cip'] : null,
          ipRegion: returnCitySN['cname'] ? returnCitySN['cname'] : null
        },
      };
      // 有campaignInfo表示 自动评测
      if (sessionStorage.getItem('campaignInfo')) {
        const double12_customerInfo = localStorage.getItem('double12_customerInfo') ? JSON.parse(localStorage.getItem('double12_customerInfo')) : null;
        const lifeCustomerInfo = localStorage.getItem('lifeCustomerInfo') ? JSON.parse(localStorage.getItem('lifeCustomerInfo')) : null;
        if (lifeCustomerInfo) {
          param.survey.customerId = lifeCustomerInfo.customerId;
          const orderIdParam = {
            name: lifeCustomerInfo.practitionerBasicInfo.name,
            customerId: lifeCustomerInfo.customerId,
            campaignInfo: {
              "campaignCode": JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignCode'],
              "campaignTaskCode": JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignTaskCode']
            }
          }
          if (type !== 1 && (JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignTaskCode'] == '12task1' || JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignTaskCode'] == 'AItask1')) {
            this.getOrderId(orderIdParam);
            return;
          }
        }
        if (double12_customerInfo) {
          param.survey.customerId = double12_customerInfo.customerId;
          const orderIdParam = {
            name: double12_customerInfo.customerName,
            customerId: double12_customerInfo.customerId,
            campaignInfo: {
              "campaignCode": JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignCode'],
              "campaignTaskCode": JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignTaskCode']
            }
          }
          if (type !== 1 && (JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignTaskCode'] == '12task1' || JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignTaskCode'] == 'AItask1')) {
            this.getOrderId(orderIdParam);
            return;
          }
        }
        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 {
            const task = JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignTaskCode'];
            // 判断有无疾病
            if (this.isDisease && (task == '12task1' || task == 'AItask1')) {
              // 双12活动有疾病出弹框，确定后跳活动首页
              this.autoEvaluationModal = true;
            } else {
              // 无疾病判断如果是任务二或者任务三跳活动首页否则条查看方案
              if (task == '12task2' || task == '12task3') {
                setTimeout(() => {
                  window.location.href = `${environment.hostName}/2019Double12/index.html?customerId=${sessionStorage.getItem('customerId')}`;
                }, 2000)
              } else {
                if (task == 'AItask1') {
                  // 智能AI
                  window.location.href = `${environment.hostName}/customizedPlanList/3?orderId=${sessionStorage.getItem('orderId')}&customerId=${sessionStorage.getItem('customerId')}`;
                } else {
                  // 跳转到方案详情页面
                  window.location.href = `${environment.hostName}/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;
    }
    if (!this.loginData.name) {
      this.errorModal('姓名不能为空');
      return;
    } else {
      const NAME_REGEXP = /(^[\u4e00-\u9fa5]{1}[\u4e00-\u9fa5\.·()（）。]{0,48}[\u4e00-\u9fa5]{1}$)|(^[a-zA-Z]{1}[a-zA-Z\s]{0,48}[a-zA-Z]{1}$)/;
      if (!NAME_REGEXP.test(this.loginData.name)) {
        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, campaignInfo: { campaignCode: JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignCode'] } }).then(response => {
          if (response['success']) {
            const double12_customerInfo = {
              customerId: response['data']['customerId'],
              customerName: this.loginData.name,
              mobileNo: this.loginData.mobileNo
            };
            localStorage.setItem('double12_customerInfo', JSON.stringify(double12_customerInfo));
            // 登录成功
            this.loginModalFlag = false;
            //获取customerId后调用获取orderId接口
            if (response['data']['customerId']) {
              sessionStorage.setItem('customerId', response['data']['customerId']);
            }
            this.getOrderId(null);
          } else {
            // 登录失败
            this.errorModal(res['message']);
          }
        });
      } else {
        // 验证码错误
        this.errorModal(res['message']);
      }
    })
  }

  // 获取orderId后调用保存问卷
  getOrderId(obj) {
    let orderIdParam;
    if (obj) {
      orderIdParam = obj;
    } else {
      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(1);

      } 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, 1);
    this.diseaseQuestions(spouseQuestionsArr, 14, 83, 2);
    this.diseaseQuestions(childrenQuestionsArr, 15, 99, 3);
  }

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

  }

  // 不能进行自动评测
  confirm() {
    this.autoEvaluationModal = false;
    if (JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignTaskCode'] && JSON.parse(sessionStorage.getItem('campaignInfo'))['campaignTaskCode'] == 'AItask1') {
      window.location.href = `${environment.hostName}/index`;
    } else {
      window.location.href = `${environment.hostName}/2019Double12/index.html?customerId=${sessionStorage.getItem('customerId')}`;
    }

  }

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

  //  解决IOSinput框被顶上去的bug
  scrollTo() {
    window.scrollTo(0, 0);
  }

}
