import { Component} from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Response } from '@angular/http';
import { AppService } from '../../service/appHttpService';

@IonicPage()
@Component({
  selector: 'page-search',
  templateUrl: 'search.html'
})

export class SearchPage {

  searchValue:string;

  contactPersons: Array<string>[];

  //组织部门id
  orgId:string = '';
  orgName:string = '';

  constructor(
    public navCtrl: NavController, 
    public navParams: NavParams,
    public appService:AppService
  ) {

    if(!typeof(this.navParams.get("orgid")) == undefined){
        this.orgId = this.navParams.get("orgid");
    }
    if(!typeof(this.navParams.get("orgName")) == undefined){
        this.orgName = this.navParams.get("orgName");
    }
    
  }

  clearValue(){
    this.searchValue="";
  }

  searchUser(){
    console.log("searchValue:"+this.searchValue);
    let nameval =  encodeURIComponent(this.searchValue) ;
    this.appService.ObserverHttpPost("/wisdomgroup/app/getUserByName",{"name":nameval,"orgId":this.orgId})
    .subscribe((res: Response) => {
        let data = res.json();
        this.contactPersons = data;
        if(this.orgId !=null && this.orgId !=''){
            //同组织部门下
            this.contactPersons.forEach(element => {
              element["orgName"] = this.orgName; 
              element["hasgeneralpersonsflag"] = false;      
            });
        }else{
            this.contactPersons.forEach(element => {
              this.getOrgName(element["id"],result=>{ 
                element["orgName"] = result["orgName"];
                element["hasgeneralpersonsflag"] = false;
              });
            });
        }
      }, error => {        
        this.appService.alert('网络异常！');  
      }   
    );
  }


  //跳转联系人信息页面
  contactPersonInfo(contactPerson){
    console.log("contactPerson:"+JSON.stringify(contactPerson));
    this.navCtrl.push("ContractPersoninfoPage",{"contactPerson":contactPerson});
  }

  //根据用户id获取部门信息
  getOrgName(id,callback?): any {
    this.appService.ObserverHttpPost("/wisdomgroup/app/getOrgName",{"userid":id})
    .toPromise() 
    .then(res => { 
      var data = res.json();     
      callback(data == null ? "[]" : data); 
    }) 
    .catch(error => {    
    });
  }
}
