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;
  approvarList:Array<any>;
  dotFlag:boolean = false;
  isShowSalay:boolean;
  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.isShowSalay = this.lifeCustomerInfo.canSeeSalaryList==1?true:false;
    // this.announcementQuery();
    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();
    this.listQuery();
    this.canSeeSalaryList();
  }

  ngAfterViewInit() {
    // setTimeout(() => {
    //   this.firstAnnouncementTitle = this.getStr(this.hide.nativeElement.innerText, '32')
    // }, 400);
  }

  getMenuList() {
    this.menuLists = [
      {
        title: '营销工具',
        content: [
          { no: 2, subtitle: 'AI保险医生', icon: 'ai', path: `https://${window.location.host}/questionnaire/#/index?campaign=AIRobot&task=AItask1&customerId=${this.lifeCustomerInfo.customerId}`, routerLink: '',showSubMenu:true },
          { no: 1, subtitle: '獴哥保险诊所', icon: 'clinic', path: `https://${window.location.host}/consulting`, routerLink: '' ,showSubMenu:true},
          { no: 4, subtitle: '线上投保', icon: 'online', path: `https://${window.location.host}/index?source=dyd`, routerLink: '' ,showSubMenu:true},
          { no: 13, subtitle: '我的商机', icon: 'line', path: '', routerLink: 'business',showSubMenu:true },
          { no: 9, subtitle: '执业证书', icon: 'card', path: `https://${window.location.host}/brokerQry/#/brokerDetail/${this.lifeCustomerInfo.practitionerId}?source=0`, routerLink: '',showSubMenu:true },
          { no: 10, subtitle: '职业类别', icon: 'job', path: 'https://www.ydinsurance.cn/occupationQry/', routerLink: '',showSubMenu:true },
          { no: 7, subtitle: '文章分享', icon: 'article', path: '', routerLink: 'article/null' ,showSubMenu:true},
          { no: 3, subtitle: '产品海报', icon: 'poster_p', path: '/salesDetail', routerLink: 'material',showSubMenu:true },
        ],
        isShow: true
      },
      {
        title: '我的团队',
        content: [
          { no: 15, subtitle: '我的团队', icon: 'team', path: '', routerLink: '',showSubMenu:true },
          // { no: 16, subtitle: '团队增员', icon: 'recruiting', path: '', routerLink: '',showSubMenu:true },
          { no: 16, subtitle: '团队增员', icon: 'recruiting', path: '', routerLink: 'recruiting' ,showSubMenu:true},
          { no: 18, subtitle: '招募海报', icon: 'poster_r', path: '', routerLink: '',showSubMenu:true },
          { no: 22, subtitle: '报聘审批', icon: 'approval', path: '', routerLink: 'approval_list',dot: this.dotFlag,showSubMenu:true}
        ],
        // isShow: this.isShow
        isShow: true
      },
      {
        title: '我的展业',
        content: [
          { no: 12, subtitle: '销售保单', icon: 'policy', path: '', routerLink: '',showSubMenu:true },
          { no: 20, subtitle: '我的客户', icon: 'customer', path: '', routerLink: '',showSubMenu:true },
          // { no: 14, subtitle: '我的佣金', icon: 'commission', path: '', routerLink: '',showSubMenu:true },
          { no: 19, subtitle: '薪资单', icon: 'salary', path: '', routerLink: 'salary',showSubMenu:this.isShowSalay },
          { no: 21, subtitle: '公司制度', icon: 'management', path: '', routerLink: '',showSubMenu:true },
          { no: 23, subtitle: '我的报聘', icon: 'pin', path: '', routerLink: 'my_application' ,showSubMenu:true},
          { no: 24, subtitle: '目标设置', icon: 'set', path: '', routerLink: 'target',showSubMenu:true },
          { no: 25, subtitle: '', icon: 'default', path: '', routerLink: '' ,showSubMenu:true},
          { no: 26, subtitle: '', icon: 'default', path: '', routerLink: '' ,showSubMenu:true}

        ],
        isShow: true
      },
      {
        title: '教育培训',
        content: [
          { no: 5, subtitle: '保险ABC', icon: 'abc', path: `https://${window.location.host}/issue`, routerLink: '' ,showSubMenu:true},
          { no: 6, subtitle: '培训课件', icon: 'train', path: '', routerLink: 'training',showSubMenu:true },
          { no: 11, subtitle: '文件下载', icon: 'download', path: 'https://www.ydinsurance.cn/?page_id=13957', routerLink: 'fileUpload',showSubMenu:true },
          { no: 17, subtitle: '产品库', icon: 'product', path: '', routerLink: 'product' ,showSubMenu:true}

        ],
        isShow: true
      }
    ];
  }

  getImgUrl(Img) {
    return 'assets/images/' + Img + '.png'
  }

  // 菜单导航
  menuNavigation(item) {
    if (item.routerLink) {
      this.router.navigate([`./${item.routerLink}`]);
    } else if (item.path) {
      window.open(item.path);
    }
    //  else if (item.no === 9) {
    //   this.shareIdCard();
    // }
    else if (item.no === 12) {
      this.router.navigate(['/salesDetail'], { queryParams: { searchType: this.performanceSelectedFlag, showType: 'orderform' } });
    } else if (item.no === 14) {
      this.router.navigate(['/salesDetail'], { queryParams: { searchType: this.performanceSelectedFlag, showType: 'sales' } });
    } else if (item.no === 15) {
      this.router.navigate(['/teamPanel'])
      // this.router.navigate(['/team_area'])
    } else if (!item.subtitle) {
      return;
    } else if (item.no === 18) {
      this.router.navigate(['/material'], { queryParams: { recruit: 'recruit' } });
    }else if(item.no === 21){
      this.router.navigate(['/fileUpload'], { queryParams: { fileUploadType: 'management' } });
    }else {
      this.isNeedAlert = true;
      this.dialogInfo = {
        title: null,
        content: { value: '即将开发，敬请期待！', align: 'center' },
        footer: [{ value: '我知道了', routerLink: '', className: 'weui-dialog__btn_primary' }],
      };
    }
  }

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

  //  分享名片
  shareIdCard() {
    const imgUrl = this.lifeCustomerInfo.practitionerBasicInfo.headImagePath ? this.lifeCustomerInfo.practitionerBasicInfo.headImagePath : `${environment.ORIGINNAME}/ydLife/assets/images/icons/meng.png`;
    this.lifeCommonService.shareStatusPublish(1);
    this.lifeCommonService.wxShare(
      `银盾保险经纪 ${this.lifeCustomerInfo.practitionerBasicInfo.name}`,
      '您的家庭保险专家、财务策划师。规划成就人生。',
      `https://${window.location.host}/brokerQry/#/brokerDetail/${this.lifeCustomerInfo.practitionerId}`,
      imgUrl);
  }

  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 {
    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 } });
  }

  //查询是否团队长
  subordinateSystemMemberQuery() {
    const practitionerId = JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'];
    this.myService.subordinateSystemMemberQuery({ practitionerId: practitionerId, time: 1 }).subscribe((res) => {
      if (res['success']) {
        this.isShow = true;
        sessionStorage.setItem('isTeamleader', '1');
        sessionStorage.setItem('subordinateSystemName', res['data']['subordinateSystemName']);
      } else {
        this.isShow = false;
        sessionStorage.setItem('isTeamleader', '0');
      }
    })
  }

  //经纪人商机分数统计
  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}`
  }

  //查看判断待审批列表小圆点
  listQuery(){
    this.myService.listQuery({practitionerId:this.lifeCustomerInfo.practitionerId,approvingStatus:0}).subscribe((res)=>{
      if(res['success']){
        this.approvarList = res['data']['hiringListInfoList'];
        if(this.approvarList.length>0){
          this.dotFlag = true;
          this.getMenuList();
        }else{
          this.dotFlag = false;
        }
      }else{
        alert(res['message'])
      }
    })
  }

  //判断是否显示薪资单
  canSeeSalaryList(){
    const practitionerId = JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'];
    this.myService.canSeeSalaryList(practitionerId).subscribe((res)=>{
      if(res['data'] && res['data'].canSeeSalaryList == 1){
        this.isShowSalay  = true;
        this.getMenuList();
      }else{
        this.isShowSalay  = false;
        this.getMenuList();
      }
    })
  }
}
