import {Component, OnInit} from '@angular/core';
import {LifeCommonService} from '../../common/life-common.service';
import {MyService} from '../../my/my.service';
import {Router} from "@angular/router";
import {ToastService } from 'ng-zorro-antd-mobile';
import { Plans } from '../../domain/plans';
import { LocalStorage } from '../../domain/local.storage';
import { User } from '../../domain/user';
@Component({
  selector: 'ydlife-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.scss']
})
export class ProductComponent implements OnInit {
  leftList: Array<any>;
  topList: Array<any> = [];
  rightList: Array<any> = [];
  leftSelectedId: number = null;
  filterSelectedFlag: boolean = false;
  tagIds:Array<any> = [];
  productInfos:Array<any>;
  productInfo: Plans;
  inquiry: User;
  rightIds:Array<any> = [];
  rightTagIds:Array<any> = [];
  topAndright:Array<any> = [];
  constructor(private myService: MyService, 
    public lifeCommonService: LifeCommonService, 
    private router: Router, 
    private _toast: ToastService,
    private ls: LocalStorage) {
  }

  ngOnInit() {
    this.lifeCommonService.setTitle('产品库');
    this.tagViewQuery(305);
    this.tagViewQuery(309);
    
  }

  //type:1表示左侧筛选2表示右侧筛选
  switchCategory(type,item?:any) {
    if(type == 1){
      if(item && item.tagId!=null){
        this.leftSelectedId = item.id;
        this.tagIds = [item.tagId]
      }else{
        this.leftSelectedId = null;
        this.tagIds = [];
      }
      this.queryProductBox();
    }else if(type==2){
      item.selected = !item.selected;
      for(let i=0;i<this.rightList.length;i++){
        if(this.rightList[i]['tagViewQueryInfos']){
          for(let j=0;j<this.rightList[i]['tagViewQueryInfos'].length;j++){
            if(this.rightList[i]['tagViewQueryInfos'][j]['selected'] == true){
               this.rightIds.push(this.rightList[i]['tagViewQueryInfos'][j]['id'])
           }else{
             for(let m=0;m<this.rightIds.length;m++){
               if(this.rightIds[m] == this.rightList[i]['tagViewQueryInfos'][j]['id']){
                 this.rightIds.splice(m,1)
               }
             }
           }
         }
        }
        
      }
      this.rightIds =  Array.from(new Set(this.rightIds))
    }
  }

  //type：305左侧，309上侧，306筛选
  tagViewQuery(type) {
    const param = {
      isActive: 1,
      tagViewType: type
    }
    this.myService.tagViewQuery(param).subscribe((res) => {
      if (res['success']) {
        if (type == 305) {
          this.leftList = res['data']['tagViewQueryInfos'];
          //初始化查推荐产品
          this.switchCategory(1,this.leftList[0])
        } else if (type == 309) {
          this.topList = res['data']['tagViewQueryInfos'];
        } else {
          this.rightList = res['data']['tagViewQueryInfos'];
          if(this.rightIds.length >0){
            for(let i=0;i<this.rightList.length;i++){
              if(this.rightList[i]['tagViewQueryInfos']){
                for(let j=0;j<this.rightList[i]['tagViewQueryInfos'].length;j++){
                  for(let m=0;m<this.rightIds.length;m++){
                    if(this.rightIds[m] == this.rightList[i]['tagViewQueryInfos'][j]['id']){
                      this.rightList[i]['tagViewQueryInfos'][j]['selected'] = true;
                    }
                  }
                }
              }
            }
          }
        }
      this.topAndright = this.rightList.concat(this.topList)
      }
    })
  }

// 筛选
  allFilter(type,item?:any) {
    this.filterSelectedFlag = true;
    if(type==1){
      this.tagViewQuery(306);
    }else{
      this.rightList = [item];
    }
  }

//  进入产品资料页面
  goData(productInfoItem) {
    this.router.navigate(['/productData', productInfoItem.productId],{queryParams:{planId:productInfoItem.planId}});
  }

  //根据标签查询产品
  queryProductBox(){
    this.rightTagIds=[];
    if(this.rightIds.length){
      for(let i=0;i<this.topAndright.length;i++){
        if(this.topAndright[i]['tagViewQueryInfos']){
          for(let j=0;j<this.topAndright[i]['tagViewQueryInfos'].length;j++){
            for(let m=0;m<this.rightIds.length;m++){
              if(this.rightIds[m] == this.topAndright[i]['tagViewQueryInfos'][j]['id']){
                this.rightTagIds.push(this.topAndright[i]['tagViewQueryInfos'][j]['tagId'])
              }
            }
          }
        }
      }
    }
    let tagIds = this.tagIds.concat(this.rightTagIds)
    this.myService.queryProductBox({tagIds:tagIds}).subscribe((res)=>{
      if(res['success']){
        this.productInfos = res['data']['productInfos'];
         //截取两个特色
         if(this.productInfos && this.productInfos.length>0){
          for(const productInfos of this.productInfos){
            if(productInfos.labels){
              productInfos.labels.splice(2);
            }
         }
        }
      }else{
        this.productInfos= [];
        const toast = ToastService.show(`${res['message']}`, 0);
        setTimeout(() => {
          ToastService.hide();
        }, 3000);
      }
    })
  }

  //重置
  restart(){
    for(let i=0;i<this.rightList.length;i++){
      if(this.rightList[i]['tagViewQueryInfos']){
        for(let j=0;j<this.rightList[i]['tagViewQueryInfos'].length;j++){
          this.rightList[i]['tagViewQueryInfos'][j]['selected'] = false;
          for(let m=0;m<this.rightIds.length;m++){
            if(this.rightIds[m] == this.rightList[i]['tagViewQueryInfos'][j]['id']){
              this.rightIds.splice(m,1)
            }
          }
        }
      }
    }
  }

  //确定搜索
  confirm(){
    this.filterSelectedFlag = false;
    this.queryProductBox();
  }


  // 点击产品进入详情页
  goProductDetail(product: Plans): void {
    this.productInfo = product;
    this.productInfo.type = 2;
    if(this.productInfo.isActive == 4){
      this.router.navigate(['/productData', product.productId],{queryParams:{planId:product.planId}});
    }else if(this.productInfo.isActive != 4){
        if(this.productInfo.isActive == 1 && this.productInfo.isThirdPartyPurchase==1 && this.productInfo.thirdPartyPurchaseUrl){
          window.location.href = this.productInfo.thirdPartyPurchaseUrl;
        }else{
          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);
  }

  showAll(item){
    item.showAll = !item.showAll;
  }
}
