import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { LifeCommonService } from "../../common/life-common.service";
import { environment } from "../../../environments/environment";
import { MyService } from "../my.service";
import { Plans } from '../../domain/plans';
import { User } from '../../domain/user';
import { LocalStorage } from '../../domain/local.storage';
import * as dayjs from 'dayjs';
declare var wx: any;
@Component({
  selector: 'ydlife-my-center-home',
  templateUrl: './my-center-home.component.html',
  styleUrls: ['./my-center-home.component.scss'],
})
export class MyCenterHomeComponent implements OnInit, AfterViewInit {
  @ViewChild('hide') hide: ElementRef
  menuLists: Array<any>;
  isNeedAlert: boolean;
  dialogInfo: any;
  lifeCustomerInfo: any;
  deviceType: number;
  announcementLists: Array<any>;
  firstAnnouncement: string;
  performanceList: Array<any>;
  performanceSelectedFlag: string;
  leftWidth: any;
  products: Plans[];
  productInfo: Plans;
  inquiry: User;
  firstAnnouncementTitle: string;
  //判断是否显示我的团队
  isShow: boolean;
  onlineInfo: any;
  offlineInfo: any;
  activities_grade: any;
  taskLen:Array<any> = [];
  person:any;
  showFlag:boolean = false;
  isShowSalay:boolean;
  showSubMenu:boolean;
  //初始化不显示面板数据
  isShowDashBoardData:boolean = true;
  // 0是未看 1是已看
  viewStatus:number;
  constructor(
    private router: Router,
    public lifeCommonService: LifeCommonService,
    private myService: MyService,
    private ls: LocalStorage,
    private activatedRoute: ActivatedRoute,
  ) {
  }

  ngOnInit() {
    const title = this.activatedRoute.snapshot.data[0]['title'];
    this.lifeCommonService.setTitle(title);
    this.deviceType = this.lifeCommonService.checkDeviceType();
    this.lifeCustomerInfo = JSON.parse(localStorage.getItem('lifeCustomerInfo')) ? JSON.parse(localStorage.getItem('lifeCustomerInfo')) : null;
    this.performanceList = [
      { name: `${this.lifeCommonService.dateFormat(new Date, ('M'))}月`, time: 1 },
      { name: `${this.getQuarter(this.lifeCommonService.dateFormat(new Date, ('M')))}`, time: 3 },
      { name: '本年度', time: 2 },
      // { name:'往期历史' , time: 4 }
    ]
    //初始化调本月线上 保费+ 本月线下保费
    this.rank(1, 1, 1)
    // this.rank(1, 2, 1)
    this.recommendPlanQuery();
    //判断是否团队长
    // this.subordinateSystemMemberQuery();
    this.opportunityStatistics();
    this.queryScheduleTrackList();
    //活动量得分查询
    this.queryPEPScore();
    // 查询是否有续期提醒订单
    if(sessionStorage.getItem('hadView')){
      this.viewStatus = 1;
    }else{
      this.queryNoticeList();
    }
  }

  closeDialog(e){
    if(e.target.className==='tipsInfoContainer'){
      this.viewStatus = 1;
      sessionStorage.setItem('hadView','true')
    }
  }
  viewDetail(){
    this.viewStatus = 1;
    sessionStorage.setItem('hadView','true');
    this.router.navigate(['/renewal_reminder'])
  }
  ngAfterViewInit() {
    // setTimeout(() => {
    //   this.firstAnnouncementTitle = this.getStr(this.hide.nativeElement.innerText, '32')
    // }, 400);
  }

   //截取字符串
   getStr(str, len) {
    if (!str) return "";
    if (len <= 0) return "";
    var templen = 0;
    for (var i = 0; i < str.length; i++) {
      if (str.charCodeAt(i) > 255) {
        templen += 2;
      } else {
        templen++;
      }
      if (len == templen || len == templen + 1) {
        return str.substring(0, i + 1) + '...';
      } else if (templen > len + 1) {
        return str.substring(0, i);
      }
    }
    return str;
  }





  // 关闭弹窗
  getPopInfo() {
    this.isNeedAlert = false;
  }



  announcementQuery() {
    this.myService.announcementQuery(null, null).subscribe(res => {
      if (res['success']) {
        this.announcementLists = res['data']['announcementInfoList'];
        this.firstAnnouncement = this.announcementLists[0]['title'];
      }
    });
  }

  getOut() {
    localStorage.removeItem('lifeCustomerInfo');
    this.router.navigate(['/login']);
  }

  /**
   * time  1-month,2-year,3-季度
   * type 1-保费,2-佣金 3-件数
   * platform //1-online,2-offline
   */
  rank(time, platform, type) {
    this.performanceSelectedFlag = time;
    if(time==4){
      this.router.navigate(['/historical_rank'])
    }else{
      const param = {
        mobileNo: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['mobileNo'],
        time: time,
        platform: platform,
        type: type,
        isPersonal:0
      }
      if (time == 1) {
        this.leftWidth = '15%';
      } else if (time == 2) {
        this.leftWidth = '30%';
      } else {
        this.leftWidth = '17%';
      }
      this.myService.rank(param).subscribe((res) => {
        if (res['success']) {
          if (platform == 1) {
            this.onlineInfo = res['data']['practitionerInfo'];
          }
          if (platform == 2) {
            this.offlineInfo = res['data']['practitionerInfo'];
          }
        }
      });
    }
  }

  // 大家都在买产品查询列表
  recommendPlanQuery() {
    this.myService.queryproductlistbytag({ mdTagId: 97 }).subscribe(res => {
      this.products = res['data'].plans;
    })
  }

  // 点击产品进入详情页
  goProductDetail(product: Plans): void {
    if(product.isThirdpartyPurchase == 1){
      if(product.thirdpartyPurchaseUrl){
        window.location.href = product.thirdpartyPurchaseUrl;
      }else{
        alert('请配置跳转链接');
      }
    }else{
      this.productInfo = product;
      this.productInfo.type = 2;
      this.inquiry = {
        planId: this.productInfo.planId,
        adultCount: this.productInfo.adultCount,
        childCount: this.productInfo.childCount,
        eldCount: this.productInfo.eldCount,
        dayCount: this.productInfo.minDay
      };
      this.setInitDate();
      this.ls.setObject('inquiry', this.inquiry);
      if (this.productInfo.noPlanProduct === true) {
        window.location.href = `https://${window.location.host}/life/${this.productInfo.productId}`
      } else {
        if (this.productInfo.productCategoryId === 1 || this.productInfo.productCategoryId === 4) {
          window.location.href = `https://${window.location.host}/pdetail/${this.productInfo.planId}`
        } else if (this.productInfo.productCategoryId === 2) {
          window.location.href = `https://${window.location.host}/hProductDetail/${this.productInfo.planId}?type=7`
        } else if (this.productInfo.productCategoryId === 5) {
          window.location.href = `https://${window.location.host}/hProductDetail/${this.productInfo.planId}?type=9`
        } else {
          window.location.href = `https://${window.location.host}/life/${this.productInfo.productId}`
          this.router.navigate(['/pdetail', this.productInfo.planId]);
        }
      }
    }
  }

  // 根据开始时间设置结束时间,天数应减1，当日~当日是一天
  setInitDate() {
    this.productInfo.dayCount = this.lifeCommonService.yearDayCount(this.productInfo.dayCount, this.productInfo.insurerId == '5');
    this.lifeCommonService.setInitDate(this.productInfo.dayCount);
  }

  jumpToDetail() {
    this.router.navigate(['/rank'], { queryParams: { time: this.performanceSelectedFlag } });
  }



  //经纪人商机分数统计
  opportunityStatistics() {
    const practitionerId = JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'];
    this.myService.opportunityStatistics({ practitionerId: practitionerId }).subscribe((res) => {
      if (res['success']) {
        this.activities_grade = res['data'];
      } else {
        this.activities_grade = null;
      }
    })
  }

  //获取季度
  getQuarter(quarter) {
    if (quarter == '1' || quarter == '2' || quarter == '3') {
      return '第一季度';
    }
    if (quarter == '4' || quarter == '5' || quarter == '6') {
      return '第二季度';
    }
    if (quarter == '7' || quarter == '8' || quarter == '9') {
      return '第三季度';
    }
    if (quarter == '10' || quarter == '11' || quarter == '12') {
      return '第四季度';
    }
  }

  //获取今日任务数量
  queryScheduleTrackList(){
    this.myService.queryScheduleTrackList({practitionerId:this.lifeCustomerInfo.practitionerId,trackTime:dayjs().format('YYYY-MM-DD')}).subscribe((res)=>{
      if(res['success']){
        this.taskLen = res['data']['dataList'];
      }else{
        this.taskLen =[];
      }
    })
  }

  //活动量得分统计
  queryPEPScore(){
    this.myService.queryPEPScore({ practitionerId: this.lifeCustomerInfo.practitionerId }).subscribe((res)=>{
      if(res['success']){
        this.person = res['data']['person'];
      }
    })
  }

  //跳转到春雨医生
  jumpToChunYu(){
    window.location.href = `https://h5.futurebaobei.com/h5/product/detail/7?channel=yindun&channelStaff=${this.lifeCustomerInfo.practitionerId}`
  }

  // 获取是否有续期提醒订单
  queryNoticeList(){
    this.myService.queryNoticeList({practitionerId:this.lifeCustomerInfo.practitionerId,status:0}).subscribe(res=>{
      if(res['success']){
        if(res['data']['list'] && res['data']['list'].length > 0){
          this.viewStatus = 0;
        }else{
          sessionStorage.setItem('hadView','true')
        }
      }
    })
  }


}

