import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";
import { LifeCommonService } from '../../common/life-common.service';
import { MyService } from '../my.service';
import { RecruitingQuery } from '../../domain/recruitingQuery';
import { EmployQuery } from '../../domain/employQuery';

@Component({
  selector: 'ydlife-recruiting-detail',
  templateUrl: './recruiting-detail.component.html',
  styleUrls: ['./recruiting-detail.component.scss']
})
export class RecruitingDetailComponent implements OnInit {
  editRecruiting: RecruitingQuery = new RecruitingQuery();
  employQuery: EmployQuery = new EmployQuery();
  //潜在增员的id
  potentialId: any;
  titleList: Array<any>;
  selectedId: number;

  readonlyFlag: boolean = true;
  //性别显示
  sexFlag: boolean;
  //显示女
  femaleFlag: boolean;
  //显示男
  maleFlag: boolean;
  isShow: boolean;
  recruitingStatusList: Array<any>;
  //控制tab可不可点
  clickFlag: boolean;
  educationLevelList: Array<any>;
  //新增增员记录的备注
  notice: any;
  trackStatusId: any;
  //控制弹框
  toastDialog: boolean;
  toastInfo: any;
  recruitTrackInfoList: Array<any>;
  resourceList: Array<any>;
  trackTime: any;
  status: any;
  remarkId: any;
  isPC: any;
  practitionerLevelInfos:Array<any>;
  practitionerList:Array<any>;
  hiringBasicInfoId:any;
  practitionerName:any;
  //-2已填完，null未填完，-1拒绝0通过
  approveStatus:any;
  practitionerListShow:Array<any>;
  defalutMentor:string = '请选择辅导人';
  defalutIntroducer:string = '请选择介绍人';
  totastType:any;
  toastFlag:boolean = false;
  isNeedAlert: boolean;
  dialogInfo: any;
  branchList:Array<any>;
  constructor(
    private activateRoute: ActivatedRoute,
    public lifeCommonService: LifeCommonService,
    private myService: MyService,
    private router: Router) {
    this.titleList = [
      { id: 1, name: '基本信息' },
      { id: 2, name: '简历' },
      { id: 3, name: '增员跟进' },
      { id: 4, name: '邀请报聘'}
    ]
  }

  ngOnInit() {
    this.practitionerName = JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerBasicInfo']['name'];
    this.isPC = this.lifeCommonService.checkDeviceType();
    //潜在增员id
    this.potentialId = Number(this.activateRoute.snapshot.paramMap.get('id'));
    //状态
    this.status = this.activateRoute.snapshot.queryParams['status'];
    this.hiringBasicInfoId = this.activateRoute.snapshot.queryParams['hiringBasicInfoId']?this.activateRoute.snapshot.queryParams['hiringBasicInfoId']:null;
    this.dropOptionsQuery(1);
    this.educationLevelQuery();
    this.organizationQuery();
    if (this.potentialId === 0) {
      this.readonlyFlag = false;
      this.sexFlag = true;
      this.maleFlag = true;
      this.femaleFlag = true;
      this.clickFlag = false;
      this.editRecruiting = new RecruitingQuery('', 1, '', '', '', '', '', '', '', null, '', '', '', '');
      this.selectTab(1);
    } else {
      this.clickFlag = true;
      this.selectTab(1);
      this.editRecruiting.resourceDropMasterId = ''
    }
    //获取基本信息
    this.recruitListQuery();
    
    
    
  }

  selectTab(id) {
    if (this.clickFlag == true) {
      if(id === 4){
        if(this.approveStatus != null && this.approveStatus != '-1'){
          this.openPopInfo(`${this.employQuery.name}已经提交所有报聘信息，不用重复邀请！`)
          return;
        }
      }
      this.selectedId = id;
      if (this.selectedId === 3) {
        //初始化
        this.trackStatusId = '';
        //跟进列表查询
        this.recruitTrackQuery();
        //招募来源列表
        this.dropOptionsQuery(2);
      }
      if (this.selectedId === 1 || this.selectedId === 2) {
        this.recruitListQuery()
      }
      if(this.selectedId === 4){
        this.employQuery.name = this.editRecruiting.name;
        this.practitionerTypeAndLevelQuery();
        this.practitionerListQuery();
        //初始化被邀请人信息
        if(this.hiringBasicInfoId){
          this.queryWholeInfo();
        }else{
          this.employQuery = new EmployQuery(this.employQuery.name,null,this.hiringBasicInfoId,this.potentialId,null,null,null,null,null,null,null,null,null,null,null,null)
        }
      }
    } else {
      this.selectedId = 1;
    }
  }

  //改为编辑状态出现男女选项
  editInfo() {
    this.readonlyFlag = false;
    this.sexFlag = true;
    this.maleFlag = true;
    this.femaleFlag = true;
  }

  //选男女
  selectedGender(e) {
    this.editRecruiting.gender = e;
  }

  //查询跟进记录
  recruitTrackQuery() {
    const param = {
      potentialId: this.potentialId ? this.potentialId : null,
      practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId']
    }
    this.myService.recruitTrackQuery(param).subscribe((res) => {
      if (res['success']) {
        this.recruitTrackInfoList = res['data']['recruitTrackInfoList'];
      }
    })
  }

  //跟进状态列表type=2跟进状态type=1招募列表
  dropOptionsQuery(type) {
    if (type === 1) {
      //招募来源列表
      this.myService.dropOptionsQuery({ code: 'team_building_source' }).subscribe((res) => {
        if (res['success']) {
          this.resourceList = res['data']['dropMasterInfoList']['0']['dropOptionsInfoList'];
        }
      })
    }
    if (type === 2) {
      //跟进状态列表
      this.myService.dropOptionsQuery({ code: 'team_building_track' }).subscribe((res) => {
        if (res['success']) {
          this.recruitingStatusList = res['data']['dropMasterInfoList']['0']['dropOptionsInfoList'];
        }
      })
    }
  }

  // 教育等级查询
  educationLevelQuery() {
    this.myService.educationLevelQuery().subscribe(res => {
      if (res['success']) {
        this.educationLevelList = res['data']['educationLevelList']
      }
    })
  }

  inputBlur() {
    window.scrollTo(0, 0)
  }

  //新增增员基本信息
  saveInfo() {
    this.editRecruiting = {
      ...this.editRecruiting,
      practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],
      potentialId: this.potentialId ? this.potentialId : null
    }
    if (!this.editRecruiting.name) {
      this.toastDialog = true;
      this.toastInfo = {
        status: 1,
        msg: '姓名不能为空！',
        timeout: 3000,
        align: 'center'
      };
      return;
    } else {
      this.editRecruiting.name = this.editRecruiting.name.trim();
      if (!this.lifeCommonService.nameValid(this.editRecruiting.name)) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '不要乱输姓名哦！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
    }
    const OVERZERO_REG = /^[0-9]*[1-9][0-9]*$/;
    if (this.editRecruiting.age) {
      if (OVERZERO_REG.test(this.editRecruiting.age)) {
        if (parseInt(this.editRecruiting.age) > 100) {
          this.toastDialog = true;
          this.toastInfo = {
            status: 1,
            msg: '年龄不能大于三位数！',
            timeout: 3000,
            align: 'center'
          };
          return;
        }
      } else {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '年龄只能输入正整数！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
    }
    if (!this.editRecruiting.mobileNo) {
      this.toastDialog = true;
      this.toastInfo = {
        status: 1,
        msg: '手机号不能为空！',
        timeout: 3000,
        align: 'center'
      };
      return;
    } else {
      this.editRecruiting.mobileNo = this.editRecruiting.mobileNo.trim()
      if (!this.lifeCommonService.mobileNoValid(this.editRecruiting.mobileNo)) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '输入手机号码错误',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
    }
    this.myService.recruit(this.editRecruiting).subscribe((res) => {
      if (res['success']) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: Number(this.potentialId) == 0 ? '添加增员对象成功！' : '修改成功！',
          timeout: 3000,
          align: 'center'
        };
        this.readonlyFlag = true;
        if (this.editRecruiting.gender) {
          this.sexFlag = true;
          if (this.editRecruiting.gender == '1') {
            this.maleFlag = true;
            this.femaleFlag = false;
          } else {
            this.femaleFlag = true;
            this.maleFlag = false;
          }
        } else {
          this.sexFlag = false;
        }
        //新增的时候要刷新页面replaceUrl: true更新路由后不把当前状态计入历史
        if (this.potentialId === 0) {
          if (res['data']['potentialId']) {
            this.potentialId = Number(res['data']['potentialId']);
            this.router.navigate([`/recruiting/${this.potentialId}`], { replaceUrl: true });
            this.clickFlag = true;
          }
        }
        this.recruitListQuery();
      } else {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: res['message'],
          timeout: 3000,
          align: 'center'
        };
      }
    })
  }

  //新增增员跟进记录
  addRecruitTrack(recruitTrackInfoItem?: any) {
    let param;
    if (!recruitTrackInfoItem) {
      const oppDate = new Date(this.trackTime + ' 23:59:59').getTime();
      const createDate = new Date(this.editRecruiting.createdAt).getTime();
      // if (nowDate < oppDate) {
      //   this.toastDialog = true;
      //   this.toastInfo = {
      //     status: 1,
      //     msg: '跟进时间不能大于当前时间！',
      //     timeout: 3000,
      //     align: 'center'
      //   };
      //   return;
      // }
      if (oppDate < createDate) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '跟进时间不能在增员时间之前！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
      if (!this.trackStatusId) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '请选择跟进状态！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
      if (!this.trackTime) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '跟进时间不能为空！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
      param = {
        potentialId: this.potentialId,
        practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],
        notice: this.notice,
        trackStatusId: this.trackStatusId,
        trackTime: this.trackTime
      }
    } else {
      param = recruitTrackInfoItem;
      param.potentialId = this.potentialId;
      param.practitionerId = JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'];
    }
    this.myService.addRecruitTrack(param).subscribe((res) => {
      if (res['success']) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: recruitTrackInfoItem ? '修改成功！' : '添加成功！',
          timeout: 3000,
          align: 'center'
        };
        this.recruitTrackQuery();
        this.remarkId = '';
      } else {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: res['message'],
          timeout: 3000,
          align: 'center'
        };
      }
    })
  }

  //查询基本信息
  recruitListQuery() {
    const listParam = {
      status: null,
      practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo')).practitionerId
    }
    this.myService.recruitListQuery(listParam).subscribe((res) => {
      if (res['success']) {
        if (res['data']['practitionerPotentialInfoList']) {
          const list = res['data']['practitionerPotentialInfoList'];
          for (let i = 0; i < list.length; i++) {
            if (this.potentialId == list[i]['potentialId']) {
              this.editRecruiting = list[i];
              if (!this.editRecruiting.gender) {
                this.sexFlag = false;
              } else {
                this.sexFlag = true;
                if (this.editRecruiting.gender == 1) {
                  this.maleFlag = true;
                  this.femaleFlag = false;
                } else {
                  this.femaleFlag = true;
                  this.maleFlag = false;
                }
              }
              if (!this.editRecruiting.resourceDropMasterId) {
                this.editRecruiting.resourceDropMasterId = '';
              }
            }
          }
        }
        if(this.hiringBasicInfoId){
          this.queryWholeInfo();
        }
        
      }
    })
  }

  editRemark(id) {
    this.remarkId = id
  }

  //查询经纪人职级
  practitionerTypeAndLevelQuery(){
    this.myService.practitionerTypeAndLevelQuery({}).subscribe((res)=>{
      this.practitionerLevelInfos = res['data']['practitionerTypeInfos'][1]['practitionerLevelInfos'];
    })
  }

  //经纪人列表查询
  practitionerListQuery(){
    this.myService.practitionerListQuery(null).subscribe((res)=>{
      this.practitionerList = res['data']['practitionerListInfoList'];
      this.practitionerListShow = res['data']['practitionerListInfoList']
    });
  }

  getPractitionerDetails(practitionerId){
    if(practitionerId){
      this.myService.practitionerDetailsQuery({practitionerId:practitionerId}).subscribe((res)=>{
        if(res['data']['praLabelItem']){
          this.employQuery.subsystemId  = res['data']['praLabelItem']['s2Id'];
          this.employQuery.subsystem = res['data']['praLabelItem']['s2SubordinateSystemName'];
          this.employQuery.subsystemOwnerId  = res['data']['praLabelItem']['s2TeamLeaderId'];
          this.employQuery.subsystemOwner = res['data']['praLabelItem']['s2TeamLeaderName'];
          this.employQuery.branchId  = res['data']['praLabelItem']['insurerBranchId'];
          this.employQuery.branch = res['data']['praLabelItem']['insurerBranchName'];
          this.employQuery.s3SubordinateSystemName = res['data']['praLabelItem']['s3SubordinateSystemName'];
          this.employQuery.s3TeamLeaderName = res['data']['praLabelItem']['s3TeamLeaderName'];
          this.employQuery.s2SubordinateSystemName = res['data']['praLabelItem']['s2SubordinateSystemName'];
          this.employQuery.s2TeamLeaderName = res['data']['praLabelItem']['s2TeamLeaderName'];
          this.employQuery.s1SubordinateSystemName = res['data']['praLabelItem']['s1SubordinateSystemName'];
          this.employQuery.s1TeamLeaderName = res['data']['praLabelItem']['s1TeamLeaderName'];
        }  
      });
    }
  }

  saveMembership(){
    if(!this.employQuery.mdDropOptionId || this.employQuery.mdDropOptionId == null){
      this.openPopInfo('报聘职级不能为空！');
      return;
    }
    if(this.employQuery.mdDropOptionId != 30){
      // if(!this.employQuery.mentorPractitionerId || !this.employQuery.mentor){
      //   this.openPopInfo('S2级别以下,辅导人不可以为空!')
      //   return;
      // }
      if(this.employQuery.mentorPractitionerId || this.employQuery.mentor){
        if(!this.employQuery.s3SubordinateSystemName && !this.employQuery.s2SubordinateSystemName && !this.employQuery.s1SubordinateSystemName){
          this.openPopInfo('该辅导人在系统里还没有归属到某一个分部、体系或纵队，请重新选择辅导人！')
          return;
        }
      }
      
    }else{
      if(!this.employQuery.branch || !this.employQuery.branchId){
        this.openPopInfo('报聘职级为S2级别时，请您自己选择分公司！')
        return;
      }
      if(this.employQuery.mentorPractitionerId || this.employQuery.mentor){
        this.openPopInfo('S2级别不需要选择辅导人！')
        return;
      }
    }
    
    this.employQuery = {
      ...this.employQuery,
      hiringBasicInfoId:this.hiringBasicInfoId?this.hiringBasicInfoId:null,
      loginId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId']
    }
    this.myService.saveMembership(this.employQuery).subscribe((res)=>{
      if(res['success']){
        this.hiringBasicInfoId = res['data']['hiringBasicInfoId']
        this.invite();
      }else{
        alert(res['message']);
      }
    });
  }

  invite(){
    this.router.navigate(['/inviter'], { queryParams: { inviteeName: this.employQuery.name ,hiringBasicInfoId:this.hiringBasicInfoId,invitatorName:this.practitionerName} });
  }

 /**
   * 下拉框选择事件
   * @param e
   * @param type
   * 1.职级
   * 2.分公司
   */
  getName(type,e){
    if(e == 'null'){
      e = null;
    }
    switch (type) {
      case 1:
        this.employQuery.mdDropOptionId = e;
        if(e){
          for(const level of this.practitionerLevelInfos){
            if(e == level.id){
              this.employQuery.mdDropOptionName = level.dropOptionCode + '-' + level.dropOptionName;
            }
          }
          //如果报聘职级是s2,清空辅导人、体系、体系负责人
          if(e == 30){
            this.employQuery.mentorPractitionerId =
            this.employQuery.mentor = 
            this.employQuery.subsystemId  = 
            this.employQuery.subsystem = 
            this.employQuery.subsystemOwnerId  =
            this.employQuery.subsystemOwner = 
            this.employQuery.branchId  = 
            this.employQuery.branch = null;
            this.defalutMentor = '/';
          }else{
            this.defalutMentor = '请选择辅导人';
          }
        }else{
          this.employQuery.mdDropOptionName = null;
        }
        return;
      case 2:
        this.employQuery.branchId = e;
        if(e){
          for(const branchItem of this.branchList){
            if(e == branchItem.insurerBranchId){
              this.employQuery.branch = branchItem.name;
            }
          }
        }else{
          this.employQuery.branchId  = 
          this.employQuery.branch = null;
        }
        return;
    }
  }

/**
 * 辅导人介绍人模糊查询
 * 1.辅导人
 * 2.介绍人
 * @param e 
 */
  getNameParam(type,e){
    switch (type) {
      case 1:
        if(e){
          this.employQuery.mentorPractitionerId = e.id;
          for (const mentorInfo of this.practitionerList) {
            if (e.id == mentorInfo.id) {
              this.employQuery.mentor = mentorInfo.name;
              this.defalutMentor =  mentorInfo.name;
            }
          }
          this.getPractitionerDetails(this.employQuery.mentorPractitionerId);
        }else{
          this.employQuery.mentorPractitionerId =
          this.employQuery.mentor = 
          this.employQuery.subsystemId  = 
          this.employQuery.subsystem = 
          this.employQuery.subsystemOwnerId  =
          this.employQuery.subsystemOwner = 
          this.employQuery.branchId  = 
          this.employQuery.branch = null;
          this.defalutMentor = '/';
        }
        this.toastFlag = false;
        return;
      case 2:
        if(e){
          this.employQuery.introducerPractitionerId = e.id;
          for (const introducer of this.practitionerList) {
            if (e.id == introducer.id) {
              this.employQuery.introducer = introducer.name;
              this.defalutIntroducer =  introducer.name;
            }
          }
        }else{
          this.employQuery.introducer = null;
          this.defalutIntroducer = '/';
        }
        this.toastFlag = false;
      return;
    }
  }

  queryWholeInfo(){
    this.myService.queryWholeInfo({hiringBasicInfoId:this.hiringBasicInfoId}).subscribe((res)=>{
      if(res['success']){
        const membership = res['data']['hiringMemberShip'];
        this.employQuery = membership;
        this.employQuery.name = this.editRecruiting.name;
        this.employQuery.practitionerPotentialId = this.potentialId;
        this.approveStatus = res['data']['hiringBasicInfo']['approveStatus'];
        if(membership.mentor){
          this.defalutMentor = membership.mentor;
        }else{
          if(this.approveStatus == null){
            if(membership.mdDropOptionId != '30'){
              this.defalutMentor = '请选择辅导人';
            }else{
              this.defalutMentor = '/';
            }
           
          }else{
            this.defalutMentor = '/';
          }
        }
        if(membership.introducer){
          this.defalutIntroducer = membership.introducer;
        }else{
          if(this.approveStatus == null){
            this.defalutIntroducer = '请选择介绍人';
          }else{
            this.defalutIntroducer = '/';
          }
        }
      }else{
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: res['message'],
          timeout: 3000,
          align: 'center'
        };
        this.employQuery = new EmployQuery(this.employQuery.name,null,null,this.potentialId,null,null,null,null,null,null,null,null,null,null,null,null)
      }
    })
  }

  /**param
   * 辅导人：1
   * 介绍人：2
   * **/
  vagueSearch(type){
    this.totastType = type;
    if(type ==1 && this.employQuery.mdDropOptionId == 30){
      this.openPopInfo('S2级别不需要选择辅导人！')
      return;
    }
    this.toastFlag = true;
    this.practitionerListShow = this.practitionerList;
  }

  change(event){
    this.practitionerListShow = this.practitionerList.filter((item)=>{
      if(item.name){
        return item.name.indexOf(event) !==-1;
      }
    })
  }

  // 打开弹窗
  openPopInfo(message) {
    this.isNeedAlert = true;
    this.dialogInfo = {
      title: null,
      content: { value: message, align: 'center' },
      footer: [{ value: '我知道了', routerLink: '', className: 'weui-dialog__btn_primary' }],
    };
  }

  // 关闭弹窗
  getPopInfo() {
    this.isNeedAlert = false;
  }

  organizationQuery(){
    this.myService.organizationQuery({insurerId: 888}).subscribe((res)=>{
      if(res['success']){
        const reponse = res['data']['insurerInfoList']
        this.branchList = reponse[0]['insurerBranchInfoList'].filter((item)=>{
          return item.systemFlag == 1;
        });
      }
    })
  }
}
