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';

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;

  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.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 }
    ]
    //初始化调本月线上 保费+ 本月线下保费
    this.rank(1, 1, 1)
    this.rank(1, 2, 1)
    this.recommendPlanQuery();
    //判断是否团队长
    this.subordinateSystemMemberQuery();
    this.opportunityStatistics();
  }

  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: '' },
          { no: 1, subtitle: '獴哥保险诊所', icon: 'clinic', path: `https://${window.location.host}/consulting`, routerLink: '' },
          { no: 4, subtitle: '线上投保', icon: 'online', path: `https://${window.location.host}/index?source=dyd`, routerLink: '' },
          { no: 13, subtitle: '我的商机', icon: 'line', path: '', routerLink: 'business' },
          { no: 9, subtitle: '我的名片', icon: 'card', path: `https://${window.location.host}/brokerQry/#/brokerDetail/${this.lifeCustomerInfo.practitionerId}?source=0`, routerLink: '' },
          { no: 10, subtitle: '职业类别', icon: 'job', path: 'https://www.ydinsurance.cn/occupationQry/', routerLink: '' },
          { no: 7, subtitle: '文章分享', icon: 'article', path: `https://${window.location.host}/discovery`, routerLink: '' },
          { no: 3, subtitle: '产品海报', icon: 'poster_p', path: '/salesDetail', routerLink: 'material' },
        ],
        isShow: true
      },
      {
        title: '我的团队',
        content: [
          { no: 15, subtitle: '我的团队', icon: 'team', path: '', routerLink: '' },
          // { no: 16, subtitle: '团队增员', icon: 'recruiting', path: '', routerLink: '' },
          { no: 16, subtitle: '团队增员', icon: 'recruiting', path: '', routerLink: 'recruiting' },
          { no: 18, subtitle: '招募海报', icon: 'poster_r', path: '', routerLink: '' },
          { no: '', subtitle: '', icon: 'default', path: '', routerLink: '' }
        ],
        isShow: this.isShow
      },
      {
        title: '教育培训',
        content: [
          { no: 5, subtitle: '保险ABC', icon: 'abc', path: `https://${window.location.host}/issue`, routerLink: '' },
          { no: 6, subtitle: '培训课件', icon: 'train', path: '', routerLink: 'training' },
          { no: 11, subtitle: '文件下载', icon: 'download', path: 'https://www.ydinsurance.cn/?page_id=13957', routerLink: 'fileUpload' },
          { no: 17, subtitle: '产品库', icon: 'product', path: 'https://www.ydinsurance.cn/?page_id=14331', routerLink: '' }

        ],
        isShow: true
      }, {
        title: '我的展业',
        content: [
          { no: 12, subtitle: '我的保单', icon: 'policy', path: '', routerLink: '' },
          { no: 20, subtitle: '我的客户', icon: 'customer', path: '', routerLink: '' },
          // { no: 14, subtitle: '我的佣金', icon: 'commission', path: '', routerLink: '' },
          { no: 19, subtitle: '薪资单', icon: 'salary', path: '', routerLink: 'salary' },
          { no: '', subtitle: '', icon: 'default', path: '', routerLink: '' }
        ],
        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'])
    } else if (!item.subtitle) {
      return;
    } else if (item.no === 18) {
      this.router.navigate(['/material'], { queryParams: { recruit: 'recruit' } });
    } 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;
    const param = {
      mobileNo: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['mobileNo'],
      time: time,
      platform: platform,
      type: type
    }
    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'];
        }
      }
    })
  }

  //截取字符串
  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;
  }

  // 大家都在买产品查询列表
  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);
  }

  jumpUrl() {
    window.location.href = `https://${window.location.host}/mk/ydviphexincoupon`
  }

  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'])
        this.getMenuList();
      } else {
        this.isShow = false;
        sessionStorage.setItem('isTeamleader', '0')
        this.getMenuList();
      }
    })
  }

  //经纪人商机分数统计
  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 '第四季度';
    }
  }
}
