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;
  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.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-btnconsult', path: `https://${window.location.host}/consulting`, routerLink: '' },
          { no: 4, subtitle: '银盾在线', icon: 'icon-zaixian', path: `https://${window.location.host}/index`, routerLink: '' },
          { no: 13, subtitle: '我的商机', icon: 'icon-shangji', path: '', routerLink: 'business' },
          { no: 12, subtitle: '我的保单', icon: 'icon-dailishangshenqing', path: '', routerLink: '' },
        ]
      }, {
        title: '教育培训',
        content: [
          { no: 5, subtitle: '保险ABC', icon: 'icon-xueshimao', path: `https://${window.location.host}/issue`, routerLink: '' },
          { no: 6, subtitle: '培训课件', icon: 'icon-jiaoyu', path: '', routerLink: 'training' },
          { no: 11, subtitle: '文件下载', icon: 'icon-xiazai1', path: 'https://www.ydinsurance.cn/?page_id=13957', routerLink: 'fileUpload' },
          { no: 8, subtitle: '', icon: '', path: '', routerLink: '' }

        ]
      }, {
        title: '展业工具',
        content: [
          { no: 9, subtitle: '执业分享', icon: 'icon-shenfenzheng', path: `https://${window.location.host}/brokerQry/#/brokerDetail/${this.lifeCustomerInfo.practitionerId}`, routerLink: '' },
          { no: 10, subtitle: '职业类别', icon: 'icon-zhiyeleibie', path: 'https://www.ydinsurance.cn/occupationQry/', routerLink: '' },
          { no: 7, subtitle: '文章分享', icon: 'icon-zhuanfaxian', path: `https://${window.location.host}/discovery`, routerLink: '' },
          { no: 3, subtitle: '产品海报', icon: 'icon-wenjian', path: '/salesDetail', routerLink: 'material' },

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

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

  // 菜单导航
  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: { type: this.performanceSelectedFlag } });
    }
    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'];
        //初始化查本月业绩
        this.selectRang('month');
      }
    })
  }

  //截取字符串
  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) {
    if (e == 'year') {
      this.performanceInfo = this.allPerformanceInfo['thisYearInfo'];
      this.leftWidth = '30%'
    }
    if (e == 'month') {
      this.performanceInfo = this.allPerformanceInfo['thisMonthInfo'];
      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(['/salesDetail'], { queryParams: { type: this.performanceSelectedFlag } });
  }
}
