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;
  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.isPC = this.lifeCommonService.checkDeviceType();
    //潜在增员id
    this.potentialId = Number(this.activateRoute.snapshot.paramMap.get('id'));
    //状态
    this.status = this.activateRoute.snapshot.queryParams['status'];
    this.dropOptionsQuery(1);
    this.educationLevelQuery();
    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();
    this.employQuery = new EmployQuery(this.employQuery.name,null,null,this.potentialId,null,null,null,null,null,null,null,null,null,null,null,null)

  }

  selectTab(id) {
    if (this.clickFlag == true) {
      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();
      }
    } 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 = '';
              }
            }
          }
        }
      }
    })
  }

  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'];
    })
  }

  getPractitionerDetails(practitionerId){
    if(practitionerId){
      this.myService.practitionerDetailsQuery({practitionerId:practitionerId}).subscribe((res)=>{
        if(res['data']['praLabelItem']){
          this.employQuery.subsystemId  = res['data']['praLabelItem']['subordinateSystemId'];
          this.employQuery.subsystem = res['data']['praLabelItem']['subordinateSystemName'];
          this.employQuery.subsystemOwnerId  = res['data']['praLabelItem']['teamLeaderId'];
          this.employQuery.subsystemOwner = res['data']['praLabelItem']['teamLeaderName'];
          this.employQuery.branchId  = res['data']['praLabelItem']['insurerBranchId'];
          this.employQuery.branch = res['data']['praLabelItem']['insurerBranchName'];
        }  
      });
    }
    
  }

  saveMembership(){
    if(this.employQuery.mdDropOptionId != 30){
      if(!this.employQuery.mentorPractitionerId || !this.employQuery.mentor){
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: 'S2级别一下,辅导人不可以为空!',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
    }
    this.employQuery = {
      ...this.employQuery,
      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: { name: this.employQuery.name ,hiringBasicInfoId:this.hiringBasicInfoId} });
  }

 /**
   * 下拉框选择事件
   * @param e
   * @param type
   * 1.职级
   * 2.辅导人
   * 3.介绍人
   */
  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.dropOptionName;
            }
          }
        }else{
          this.employQuery.mdDropOptionName = null;
        }
        return;
      case 2:
        this.employQuery.mentorPractitionerId = e;
        if(e){
          for (const mentorInfo of this.practitionerList) {
            if (e == mentorInfo.id) {
              this.employQuery.mentor = mentorInfo.name;
            }
          }
        }else{
          this.employQuery.mentor = 
          this.employQuery.subsystemId  = 
          this.employQuery.subsystem = 
          this.employQuery.subsystemOwnerId  =
          this.employQuery.subsystemOwner = 
          this.employQuery.branchId  = 
          this.employQuery.branch = null;
        }
        return;
      case 3:
        this.employQuery.introducerPractitionerId = e;
        if(e){
          for (const introducer of this.practitionerList) {
            if (e == introducer.id) {
              this.employQuery.introducer = introducer.name;
            }
          }
        }else{
          this.employQuery.introducer = null;
        }
        
        return;
    }
  }
}
