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,
    private 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: '本月', time: 1 },
      { name: '季度', 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: 'icon-AI', path: `https://${window.location.host}/questionnaire/#/index?campaign=AIRobot&task=AItask1&customerId=${this.lifeCustomerInfo.customerId}`, routerLink: '' },
          { no: 1, subtitle: '獴哥保险诊所', icon: 'icon-zhensuozhongxin', path: `https://${window.location.host}/consulting`, routerLink: '' },
          { no: 4, subtitle: '线上投保', icon: 'icon-yidonghulianwang2', path: `https://${window.location.host}/index`, routerLink: '' },
          { no: 13, subtitle: '我的商机', icon: 'icon-xiansuo1', path: '', routerLink: 'business' },
          { no: 12, subtitle: '我的保单', icon: 'icon-baodanyangben', path: '', routerLink: '' },
          { no: 14, subtitle: '我的佣金', icon: 'icon-yongjin', path: '', routerLink: '' },
          { no: '', subtitle: '', icon: '', path: '', routerLink: '' },
          { no: '', subtitle: '', icon: '', path: '', routerLink: '' }
        ],
        isShow: true
      },
      {
        title: '我的团队',
        content: [
          { no: 15, subtitle: '我的团队', icon: 'icon-tuandui', path: '', routerLink: 'teamPanel' },
          // { no: 16, subtitle: '团队增员', icon: 'icon-tuanduiguanlisvg', path: '', routerLink: '' },
          { no: 16, subtitle: '团队增员', icon: 'icon-tuanduiguanlisvg', path: '', routerLink: 'recruiting' },
          { no: 18, subtitle: '招募海报', icon: 'icon-haibao-1', path: '', routerLink: '' },
          { no: '', subtitle: '', icon: '', path: '', routerLink: '' }
        ],
        isShow: this.isShow
      },
      {
        title: '教育培训',
        content: [
          { no: 5, subtitle: '保险ABC', icon: 'icon-zidian', path: `https://${window.location.host}/issue`, routerLink: '' },
          { no: 6, subtitle: '培训课件', icon: 'icon-ziliaoku', path: '', routerLink: 'training' },
          { no: 11, subtitle: '文件下载', icon: 'icon-xiazai1', path: 'https://www.ydinsurance.cn/?page_id=13957', routerLink: 'fileUpload' },
          { no: 17, subtitle: '产品库', icon: 'icon-jingxuanchanpinku', path: 'https://www.ydinsurance.cn/?page_id=14331', routerLink: '' },

        ],
        isShow: true
      }, {
        title: '展业工具',
        content: [
          { no: 9, subtitle: '我的名片', icon: 'icon-zhiyezhenghao', path: `https://${window.location.host}/brokerQry/#/brokerDetail/${this.lifeCustomerInfo.practitionerId}`, routerLink: '' },
          { no: 10, subtitle: '职业类别', icon: 'icon-zhiye', path: 'https://www.ydinsurance.cn/occupationQry/', routerLink: '' },
          { no: 7, subtitle: '文章分享', icon: 'icon-fenxiangwenzhang', path: `https://${window.location.host}/discovery`, routerLink: '' },
          { no: 3, subtitle: '产品海报', icon: 'icon-haibao-1', path: '/salesDetail', routerLink: 'material' },
        ],
        isShow: true
      }
    ];
  }

  // 菜单导航
  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.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;
      }
    })
  }
}
