import { Component, OnInit, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { Router } 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;
  allPerformanceInfo: any;
  performanceList: Array<any>;
  performanceInfo: any;
  performanceSelectedFlag: string;
  leftWidth: any;
  products: Plans[];
  productInfo: Plans;
  inquiry: User;
  firstAnnouncementTitle: string;
  //判断是否显示我的团队
  isShow: boolean;

  constructor(
    private router: Router,
    private lifeCommonService: LifeCommonService,
    private myService: MyService,
    private ls: LocalStorage
  ) {
  }

  ngOnInit() {
    this.deviceType = this.lifeCommonService.checkDeviceType();
    this.lifeCustomerInfo = JSON.parse(localStorage.getItem('lifeCustomerInfo')) ? JSON.parse(localStorage.getItem('lifeCustomerInfo')) : null;
    this.announcementQuery();
    this.subordinateSystemMemberQuery();
    setTimeout(() => {
      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: 'teamRank' },
            { no: 16, subtitle: '团队增员', icon: 'icon-tuanduiguanlisvg', path: '', routerLink: '' },
            // { no: 16, subtitle: '团队增员', icon: 'icon-tuanduiguanlisvg', path: '', routerLink: 'recruiting' },
            { no: '', subtitle: '', icon: '', 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
        }
      ];
    }, 300)

    this.performanceList = [
      { type: 'month', name: '本月' },
      { type: 'year', name: '本年度' }
    ]
    this.brokerInfoQuery();
    this.recommendPlanQuery();
  }

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

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

  //查询排行
  brokerInfoQuery() {
    const practitionerId = JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'];
    this.myService.brokerInfoQuery({ practitionerId: practitionerId }).subscribe((res) => {
      if (res['success']) {
        this.allPerformanceInfo = res['data']['commissionInfo'];
        // sessionStorage.setItem('allPerformanceInfo', JSON.stringify((this.allPerformanceInfo)));
        //初始化查本月业绩
        this.selectRang('month', 'fyp');
      }
    })
  }

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

  selectRang(e, rankType) {
    if (e == 'year') {
      if (rankType == 'fyp') {
        this.performanceInfo = this.allPerformanceInfo['thisYearInfo']['onlineInfo']['rankByFYP']['practitionerInfo'];
      } else if (rankType == 'fyc') {
        this.performanceInfo = this.allPerformanceInfo['thisYearInfo']['onlineInfo']['rankByFYC']['practitionerInfo'];
      } else if (rankType == 'count') {
        this.performanceInfo = this.allPerformanceInfo['thisYearInfo']['onlineInfo']['rankByCount']['practitionerInfo'];
      } else {
        return;
      }
      this.leftWidth = '30%';
    }
    if (e == 'month') {
      if (rankType == 'fyp') {
        this.performanceInfo = this.allPerformanceInfo['thisMonthInfo']['onlineInfo']['rankByFYP']['practitionerInfo'];
      } else if (rankType == 'fyc') {
        this.performanceInfo = this.allPerformanceInfo['thisMonthInfo']['onlineInfo']['rankByFYC']['practitionerInfo'];
      } else if (rankType == 'count') {
        this.performanceInfo = this.allPerformanceInfo['thisMonthInfo']['onlineInfo']['rankByCount']['practitionerInfo'];
      } else {
        return;
      }
      this.leftWidth = '15%';
    }
    this.performanceSelectedFlag = e;
  }

  // 大家都在买产品查询列表
  recommendPlanQuery() {
    this.myService.queryproductlistbytag({ mdTagId: 17 }).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: { searchType: 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;
      } else {
        this.isShow = false;
      }
    })
  }
}
