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';

@Component({
  selector: 'ydlife-recruiting-detail',
  templateUrl: './recruiting-detail.component.html',
  styleUrls: ['./recruiting-detail.component.scss']
})
export class RecruitingDetailComponent implements OnInit {
  editRecruiting: RecruitingQuery = new RecruitingQuery();
  //潜在增员的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;
  constructor(
    private activateRoute: ActivatedRoute,
    public lifeCommonService: LifeCommonService,
    private myService: MyService,
    private router: Router) {
    this.titleList = [
      { id: 1, name: '基本信息' },
      { id: 2, name: '简历' },
      { id: 3, 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()
  }

  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()
      }
    } 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
  }
}
