import { Component, OnInit, AfterViewInit } from '@angular/core';
import { MyService } from '../my.service';
import { ActivatedRoute } from "@angular/router";
import { BusinessQuery } from '../../domain/businessQuery';
import { LifeCommonService } from '../../common/life-common.service';
declare var LCalendar: any;
@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>;
  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: string;
  constructor(private activateRoute: ActivatedRoute, private myService: MyService,
    public lifeCommonService: LifeCommonService) {
    this.titleList = [
      { id: 1, name: '基本信息' },
      { id: 2, name: '咨询问卷' },
      { id: 4, name: '咨询报告' },
      { id: 3, name: '商机跟进' }

    ]
  }

  ngOnInit() {
    this.orderId = this.activateRoute.snapshot.queryParams['orderId'];
    this.opportunityId = this.activateRoute.snapshot.paramMap.get('id');
    this.leadsAssignedId = this.activateRoute.snapshot.queryParams['leadsAssignedId'];
    this.opportunityRecordId = null;
    this.tagQuery();
    this.selectTab(1);
    this.dropOptionsQuery();
    setTimeout(() => {
      this.ownOpportunityDetailQuery();
    }, 300)
  }

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

  selectTab(id) {
    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}`
      }
    }
  }

  ownOpportunityDetailQuery() {
    const detailParam = {
      opportunityId: this.opportunityId,
      orderId: this.orderId,
      practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['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']['opportunityRecordInfos'];
        this.isCompletedQuestionnaire = res['data']['opportunityConsultationInfo']['isCompletedQuestionnaire'];
        //如果没有性别显示暂无性别
        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.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() {
    this.myService.dropOptionsQuery({ code: 'bizchance_promotion_action' }).subscribe((res) => {
      if (res['success']) {
        this.businessStatusList = res['data']['dropMasterInfoList']['0']['dropOptionsInfoList'];
      }
    })
  }

  saveInfo() {
    const newTag = this.editBusiness.opportunityCustomerTags.map((item) => {
      return {
        tagId: item.id ? item.id : item.tagId,
        tagName: item.tagName
      }
    })
    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;
        }

      }
    }
    this.editBusiness = {
      ...this.editBusiness,
      opportunityCustomerTags: newTag
    }
    this.myService.ownOpportunityBasicInformationSave(this.editBusiness).subscribe((res) => {
      if (res['success']) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '修改成功！',
          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;
        }
      }
    })
  }



  ownOpportunityRecordSave() {
    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;
    }
    const param = {
      id: '',
      salesNotice: this.salesNotice,
      isActive: 1,
      practitionerId: JSON.parse(localStorage.getItem('lifeCustomerInfo'))['practitionerId'],
      opportunityId: this.opportunityId,
      mdDropOptionId: this.opportunityRecordId,
      noticeDate: this.opportunityRecordNoticeDate,
      leadsAssignedId: this.leadsAssignedId
    }
    this.myService.ownOpportunityRecordSave(param).subscribe(res => {
      if (res['success']) {
        this.toastDialog = true;
        this.toastInfo = {
          status: 1,
          msg: '添加成功！',
          timeout: 3000,
          align: 'center'
        };
        this.opportunityRecordId = this.salesNotice = this.opportunityRecordNoticeDate = null;
        this.ownOpportunityDetailQuery();
        this.isShow = false;
      } 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)
  }
}


