import { Component, OnInit } from '@angular/core';
import { MyService } from '../my.service';
import { ActivatedRoute, Router } from "@angular/router";
import { BusinessQuery } from '../../domain/businessQuery';
import { LifeCommonService } from '../../common/life-common.service';
@Component({
  selector: 'ydlife-my-business-detail',
  templateUrl: './my-business-detail.component.html',
  styleUrls: ['./my-business-detail.component.scss']
})

export class MyBusinessDetailComponent implements OnInit {

  titleList: Array<any>;
  selectedId: number;
  surveyAnswersList: Array<any>;
  readonlyFlag: boolean = true;
  orderId: number;
  opportunityId: string;
  opportunitySurveyAnswersList: Array<any>;
  tagList: Array<any>;
  editBusiness: BusinessQuery = new BusinessQuery();
  //商机状态
  businessStatusList: Array<any>;
  //经纪人输入商机来源类型
  businessSourceList: Array<any>;
  //商机星座类型
  businessZodiacList: Array<any>;
  //商机血型类型
  businessBloodList: Array<any>;
  cityFlag: boolean;
  provinceList: Array<any>;
  provinces: Array<any>;
  //返回的标签列表
  opportunityCustomerTags: Array<any>;
  opportunityRecordInfos: Array<any>;
  //是否可以跳转预览方案
  isCompletedQuestionnaire: any;
  //控制弹框
  toastDialog: boolean;
  toastInfo: any;
  // 增加还是保存
  addStatus: boolean;
  // 备注信息
  salesNotice: string;
  // 跟进时间
  opportunityRecordNoticeDate: Date;
  // 跟进状态
  opportunityRecordId: number;
  //性别显示
  sexFlag: boolean;
  //显示女
  femaleFlag: boolean;
  //显示男
  maleFlag: boolean;
  isShow: boolean;
  //线索id
  leadsAssignedId: any;
  //控制tab可不可点
  clickFlag: boolean;
  remarkId: any;
  status: any;
  isNeedAlert: boolean;
  dialogInfo: any;
  practitionerId:any;
  constructor(private activateRoute: ActivatedRoute, private myService: MyService,
    public lifeCommonService: LifeCommonService, private router: Router, ) {
    this.titleList = [
      { id: 1, name: '基本信息' },
      { id: 3, name: '商机跟进' },
      { id: 2, name: '咨询问卷' },
      { id: 4, name: '咨询报告' },
    ]
  }

  ngOnInit() {
    this.orderId = this.activateRoute.snapshot.queryParams['orderId'];
    //商机对应的客户id
    this.opportunityId = this.activateRoute.snapshot.paramMap.get('id');
    //商机id
    this.leadsAssignedId = this.activateRoute.snapshot.queryParams['leadsAssignedId'];
    this.opportunityRecordId = null;
    this.practitionerId = JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId']
    this.tagQuery();
    //商机状态
    this.dropOptionsQuery('bizchance_promotion_action');
    //经纪人输入商机来源类型
    this.dropOptionsQuery('leads_manual_source');
    //商机星座类型
    this.dropOptionsQuery('leads_manual_zodiac_type');
    //商机血型类型
    this.dropOptionsQuery('leads_manual_blood_type');
    //新增商机
    if (Number(this.opportunityId) === 0) {
      this.readonlyFlag = false;
      this.sexFlag = true;
      this.maleFlag = true;
      this.femaleFlag = true;
      this.clickFlag = false;
      let myCustomerInfo = JSON.parse(localStorage.getItem('myCustomerInfo'))
      if(myCustomerInfo){
        let birthDate,age;
        if(myCustomerInfo.birthDate){
          birthDate = myCustomerInfo.birthDate.split('-');
          age=this.lifeCommonService.ages(birthDate[0],birthDate[1],birthDate[2]).age;
        }else{
          age = null;
        }
        this.editBusiness = new BusinessQuery("",age, myCustomerInfo.name,  myCustomerInfo.gender=='女'?2:1, myCustomerInfo.mobileNo, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", null);
      }else{
        //初始化新增
        this.editBusiness = new BusinessQuery("", "", "", 1, "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", null);
      }
      this.selectTab(1);
    } else {
      this.clickFlag = true;
      this.selectTab(1);
      //查询商机
      setTimeout(() => {
        this.ownOpportunityDetailQuery();
      }, 300)
    }

  }

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

  selectTab(id) {
    if (this.clickFlag == true) {
      this.selectedId = id;
      if (id === 4) {
        if (this.isCompletedQuestionnaire == 3) {
          window.location.href = `https://${window.location.host}/customizedPlanList/3?orderId=${this.orderId}&customerId=${this.opportunityId}`
        }
      }
    } else {
      this.selectedId = 1;
    }
  }

  ownOpportunityDetailQuery() {
    const detailParam = {
      opportunityId: this.opportunityId ? Number(this.opportunityId) : null,
      orderId: this.orderId ? Number(this.orderId) : null,
      practitionerId: this.practitionerId
    }
    this.myService.ownOpportunityDetailQuery(detailParam).subscribe((res) => {
      if (res['success']) {
        this.opportunitySurveyAnswersList = res['data']['opportunityConsultationInfo']['opportunitySurveyAnswersList']
        this.editBusiness = res['data']['opportunityBasicInformationInfo'];
        this.opportunityCustomerTags = res['data']['opportunityBasicInformationInfo']['opportunityCustomerTags']
        this.opportunityRecordInfos = res['data']['opportunityRecordSituationInfo']['opportunityRecordInfos'];
        this.isCompletedQuestionnaire = res['data']['opportunityConsultationInfo']['isCompletedQuestionnaire'];
        this.status = res['data']['opportunityRecordSituationInfo']['status'];
        //如果没有性别显示暂无性别
        if (!res['data']['opportunityBasicInformationInfo']['gender']) {
          this.sexFlag = false;
        } else {
          this.sexFlag = true;
          if (res['data']['opportunityBasicInformationInfo']['gender'] == 1) {
            this.maleFlag = true;
            this.femaleFlag = false;
          } else {
            this.femaleFlag = true;
            this.maleFlag = false;
          }
        }
        if (!this.editBusiness.bloodTypeId) {
          this.editBusiness.bloodTypeId = '';
        }
        if (!this.editBusiness.zodiacTypeId) {
          this.editBusiness.zodiacTypeId = '';
        }
        if (!this.editBusiness.sourceFrom) {
          this.editBusiness.sourceFrom = '';
        }
        if (this.opportunityCustomerTags.length > 0) {
          for (let i = 0; i < this.opportunityCustomerTags.length; i++) {
            for (let j = 0; j < this.tagList.length; j++) {
              if (this.opportunityCustomerTags[i]['tagId'] == this.tagList[j]['id']) {
                this.tagList[j].selected = true;
              } else {
                this.tagList[j].selected = false;
              }
            }
          }
        }
      } else {
        this.opportunitySurveyAnswersList = [];
      }
    })
  }

  tagQuery() {
    this.myService.tagQuery({ tagType: 2, isActive: 1 }).subscribe((res) => {
      if (res['success']) {
        this.tagList = res['data']['tagVOs'];
      }
    })
  }

  //选标签
  selectTag(tagItem) {
    if (this.readonlyFlag) {
      return;
    }
    this.tagList.forEach((item, idx) => {
      if (tagItem.id == item.id) {
        this.tagList[idx].selected = !tagItem.selected
      }
    })
    this.editBusiness.opportunityCustomerTags = this.tagList.filter((item) => {
      return item.selected == true;
    })
  }

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

  // 获取下拉框列表
  dropOptionsQuery(dropCode) {
    this.myService.dropOptionsQuery({ code: dropCode }).subscribe((res) => {
      if (res['success']) {
        if (dropCode === 'bizchance_promotion_action') {
          this.businessStatusList = res['data']['dropMasterInfoList']['0']['dropOptionsInfoList'];
        } else if (dropCode === 'leads_manual_source') {
          this.businessSourceList = res['data']['dropMasterInfoList']['0']['dropOptionsInfoList'];
        } else if (dropCode === 'leads_manual_zodiac_type') {
          this.businessZodiacList = res['data']['dropMasterInfoList']['0']['dropOptionsInfoList'];
        } else if (dropCode === 'leads_manual_blood_type') {
          this.businessBloodList = res['data']['dropMasterInfoList']['0']['dropOptionsInfoList'];
        }
      }
    })
  }

  saveInfo() {
    // 如果是新增商机，不需要打标签
    let newTag;
    if (Number(this.opportunityId) != 0) {
      newTag = this.editBusiness.opportunityCustomerTags.map((item) => {
        return {
          tagId: item.id ? item.id : item.tagId,
          tagName: item.tagName
        }
      })
    }
    if (!this.editBusiness.name) {
      this.toastDialog = true;
      this.toastInfo = {
        status: 1,
        msg: '姓名不能为空！',
        timeout: 3000,
        align: 'center'
      };
      return;
    } else {
      this.editBusiness.name = this.editBusiness.name.trim();
      if (!this.lifeCommonService.nameValid(this.editBusiness.name)) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '不要乱输姓名哦！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }

    }
    if (!this.editBusiness.mobileNo) {
      this.toastDialog = true;
      this.toastInfo = {
        status: 1,
        msg: '手机号不能为空！',
        timeout: 3000,
        align: 'center'
      };
      return;
    } else {
      this.editBusiness.mobileNo = this.editBusiness.mobileNo.trim()
      if (!this.lifeCommonService.mobileNoValid(this.editBusiness.mobileNo)) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '输入手机号码错误',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
    }
    const OVERZERO_REG = /^[0-9]*[1-9][0-9]*$/;
    if (this.editBusiness.age) {
      if (OVERZERO_REG.test(this.editBusiness.age)) {
        if (parseInt(this.editBusiness.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.editBusiness.fyp) {
      const fypArr = this.editBusiness.fyp.toString().split('.');
      if (fypArr.length - 1 == 1) {
        if (fypArr[0].length > 10) {
          this.toastDialog = true;
          this.toastInfo = {
            status: 1,
            msg: '预计fyp只能输入最多10位整数！',
            timeout: 3000,
            align: 'center'
          };
          return;
        }
        if (fypArr[1].length > 3) {
          this.toastDialog = true;
          this.toastInfo = {
            status: 1,
            msg: '预计fyp只能输入最多2位小数！',
            timeout: 3000,
            align: 'center'
          };
          return;
        }
      } else if (fypArr.length - 1 > 1) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: 'fyp不能输入多个小数点！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
    }
    if (this.editBusiness.fyc) {
      const fycArr = this.editBusiness.fyc.toString().split('.');
      if (fycArr.length - 1 == 1) {
        if (fycArr[0].length > 10) {
          this.toastDialog = true;
          this.toastInfo = {
            status: 1,
            msg: '预计fyc只能输入最多10位整数！',
            timeout: 3000,
            align: 'center'
          };
          return;
        }
        if (fycArr[1].length > 3) {
          this.toastDialog = true;
          this.toastInfo = {
            status: 1,
            msg: '预计fyc只能输入最多2位小数！',
            timeout: 3000,
            align: 'center'
          };
          return;
        }
      } else if (fycArr.length - 1 > 1) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: 'fyc不能输入多个小数点！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
    }
    if (this.editBusiness.pieces) {
      if (!OVERZERO_REG.test(this.editBusiness.pieces)) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '预计件数只能输入正整数！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
    }
    this.editBusiness = {
      ...this.editBusiness,
      leadsAssignedId: this.leadsAssignedId ? Number(this.leadsAssignedId) : null,
      opportunityId: this.opportunityId ? Number(this.opportunityId) : null,
      opportunityCustomerTags: newTag ? newTag : [],
      assignedPractitionerId: this.practitionerId,
      fyp: this.editBusiness.fyp ? Number(this.editBusiness.fyp) : null,
      fyc: this.editBusiness.fyc ? Number(this.editBusiness.fyc) : null,
      sourceFrom: this.editBusiness.sourceFrom ? Number(this.editBusiness.sourceFrom) : null
    }
    this.myService.ownOpportunityBasicInformationSave(this.editBusiness).subscribe((res) => {
      if (res['success']) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: Number(this.opportunityId) == 0 ? '新增成功！' : '修改成功！',
          timeout: 3000,
          align: 'center'
        };
        this.readonlyFlag = true;
        if (this.editBusiness.gender) {
          this.sexFlag = true;
          if (this.editBusiness.gender == '1') {
            this.maleFlag = true;
            this.femaleFlag = false;
          } else {
            this.femaleFlag = true;
            this.maleFlag = false;
          }
        } else {
          this.sexFlag = false;
        }
        //新增的时候要刷新页面
        if (Number(this.opportunityId) == 0) {
          if (res['data']['opportunityId'] && res['data']['leadsAssignedId']) {
            this.opportunityId = res['data']['opportunityId'];
            this.leadsAssignedId = res['data']['leadsAssignedId'];
            this.router.navigate([`/business/${this.opportunityId}`], { queryParams: { leadsAssignedId: this.leadsAssignedId }, replaceUrl: true });
            this.clickFlag = true;
          }
        }
        this.ownOpportunityDetailQuery();
      }else{
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: res['message'],
          timeout: 3000,
          align: 'center'
        };
      }
    })
  }

  ownOpportunityRecordSave(opportunityRecordItem?: any) {
    let param;
    if (!opportunityRecordItem) {
      const oppDate = new Date(this.opportunityRecordNoticeDate + ' 23:59:59').getTime();
      const createDate = new Date(this.editBusiness.opportunityDate).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.opportunityRecordId) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '请选择跟进状态！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
      if (!this.salesNotice) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '备注不能为空！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
      if (!this.opportunityRecordNoticeDate) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '跟进时间不能为空！',
          timeout: 3000,
          align: 'center'
        };
        return;
      }
      param = {
        id: '',
        salesNotice: this.salesNotice,
        isActive: 1,
        practitionerId: this.practitionerId,
        opportunityId: this.opportunityId ? Number(this.opportunityId) : null,
        mdDropOptionId: this.opportunityRecordId ? Number(this.opportunityRecordId) : null,
        noticeDate: this.opportunityRecordNoticeDate,
        leadsAssignedId: this.leadsAssignedId ? Number(this.leadsAssignedId) : null
      }
    } else {
      param = opportunityRecordItem
    }
    this.myService.ownOpportunityRecordSave(param).subscribe(res => {
      if (res['success']) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: opportunityRecordItem ? '修改成功！' : '添加成功！',
          timeout: 3000,
          align: 'center'
        };
        this.opportunityRecordId = this.salesNotice = this.opportunityRecordNoticeDate = null;
        this.ownOpportunityDetailQuery();
        this.isShow = false;
        this.remarkId = '';
      } else {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: res['message'],
          timeout: 3000,
          align: 'center'
        };
      }

    })
  }

  //添加商机弹框
  showToast() {
    this.isShow = true;
  }

  closeToast() {
    this.isShow = false;
  }

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

  editRemark(id) {
    this.remarkId = id
  }

  openPopInfo(message) {
    this.myService.applyForExpertSupport({leadsAssignedId:this.leadsAssignedId,practitionerId:this.practitionerId,opportunityId:this.opportunityId}).subscribe((res)=>{
      if(res['success']){
        this.ownOpportunityDetailQuery();
        this.isNeedAlert = true;
        this.dialogInfo = {
          title: null,
          content: { value: message, align: 'center' },
          footer: [{ value: '确认离开', routerLink: '', className: 'weui-dialog__btn_primary' }],
        };
      }else{
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: res['message'],
          timeout: 3000,
          align: 'center'
        };
      }
    })
    
  }

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


