import {
  Component,
  OnInit,
  ViewChild,
  ElementRef,
  HostListener,
  OnDestroy,
} from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { MyService } from "../../my.service";
import { LifeCommonService } from "../../../common/life-common.service";
declare var rrwebRecord:any;

@Component({
  selector: "ydlife-personal-statement",
  templateUrl: "./personal-statement.component.html",
  styleUrls: ["./personal-statement.component.scss"],
})
export class PersonalStatementComponent implements OnInit,OnDestroy {
  @ViewChild("autofocusFlag") elementView: ElementRef;
  @ViewChild("contract") toastContent: ElementRef;
  //判断是个人声明还是合同确认
  type: any;
  hiringBasicInfoId: any;
  dropOptionsInfoList: Array<any>;
  isNeedAlert: boolean;
  dialogInfo: any;
  autofocusFlag: boolean;
  dropOptionsInfoListParam: Array<any> = [];
  contractTermsList: Array<any>;
  everWork: string;
  //判断曾经报聘是否可点
  everWorkFlag: boolean = false;
  isShow: boolean;
  curTitle: any;
  curContract: any;
  curContractId: number;
  isAllAgree: boolean = false;
  contractTermsConfirmsListParm: Array<any>;
  approveStatus: any;
  agreeBtnShow: boolean = false;
  timeCount: number = 5;
  timerId:any;
  events:Array<any>;
  pageInfo = {
    type:8,
    name:'报聘个人声明确认页'
  }
  constructor(
    private myService: MyService,
    private activatedRoute: ActivatedRoute,
    public lifeCommonService: LifeCommonService,
    private router: Router
  ) {}

  ngOnInit() {
    this.type = this.activatedRoute.snapshot.data[0]["type"];
    const title = this.activatedRoute.snapshot.data[0]["title"];
    this.lifeCommonService.setTitle(title);
    this.hiringBasicInfoId = this.activatedRoute.snapshot.queryParams
      .hiringBasicInfoId
      ? this.activatedRoute.snapshot.queryParams.hiringBasicInfoId
      : null;
    if (this.type == "personal_statement") {
      this.dropOptionsQuery();
    }
    if (this.type == "contract") {
      this.queryContractTerms();
      this.pageInfo = {
        type:9,
        name:'报聘合同文档确认页'
      }
    }
    let _this = this;
    _this.events = [];
    rrwebRecord({
      emit(event){
        // 将evene存入events数组中
        _this.events.push(event);
      },
      recordCanvas: true
    });
    this.timerId = setInterval(()=>{ this.saveRecord()},10 * 1000);
  }

  ngOnChanges() {}
  ngOnDestroy(): void {
    clearInterval(this.timerId)
}

  saveRecord(){
    this.myService.rrwebInfo(this.events,this.pageInfo).subscribe(res=>{
      // console.log(res);
    })
  }
  next() {
    if (this.type == "personal_statement") {
      this.savePersonalStatements();
    } else if (this.type == "contract") {
      if (!this.isAllAgree) {
        this.openPopInfo("请详细阅读全部条款！");
        return;
      }
      this.saveContractTermsConfirms();
      this.router.navigate(["/signature"], {
        queryParams: { hiringBasicInfoId: this.hiringBasicInfoId },
      });
    }
  }

  dropOptionsQuery() {
    this.myService
      .dropOptionsQuery({ code: "EHiring_Personal_Statements" })
      .subscribe((res) => {
        if (res["success"]) {
          this.dropOptionsInfoList =
            res["data"]["dropMasterInfoList"][0]["dropOptionsInfoList"];
          this.dropOptionsInfoList.forEach((item) => {
            item.status = 0;
            item.userInput = null;
          });
          this.queryWholeInfo(this.hiringBasicInfoId);
        } else {
          this.openPopInfo(res["message"]);
        }
      });
  }

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

  //选择个人声明
  selectStatements(personalStatements) {
    if (this.approveStatus == null || this.approveStatus == "-1") {
      if (personalStatements.status == 1) {
        personalStatements.status = 0;
      } else {
        personalStatements.status = 1;
      }
      if (personalStatements.dropOptionCode == "NO_REGISTER_SAME_TRADE") {
        if (personalStatements.status == 1) {
          this.everWorkFlag = true;
          //点击曾经报聘输入报聘自动获取焦点
          setTimeout(() => {
            this.elementView.nativeElement.focus();
          }, 500);
        } else {
          this.everWork = null;
          this.everWorkFlag = false;
        }
      }
    }
  }

  savePersonalStatements() {
    this.dropOptionsInfoListParam = [];
    for (let i = 0; i < this.dropOptionsInfoList.length; i++) {
      this.dropOptionsInfoList[i][
        "mdDropOptionName"
      ] = this.dropOptionsInfoList[i]["dropOptionName"];
      this.dropOptionsInfoList[i]["mdDropOptionId"] = this.dropOptionsInfoList[
        i
      ]["id"];
      if (
        this.dropOptionsInfoList[i]["dropOptionCode"] ==
        "NO_REGISTER_SAME_TRADE"
      ) {
        this.dropOptionsInfoListParam.push({
          mdDropOptionName: this.dropOptionsInfoList[i]["dropOptionName"],
          mdDropOptionId: this.dropOptionsInfoList[i]["id"],
          status: this.dropOptionsInfoList[i]["status"],
          userInput: this.everWork ? this.everWork : null,
        });
      } else {
        this.dropOptionsInfoListParam.push({
          mdDropOptionName: this.dropOptionsInfoList[i]["dropOptionName"],
          mdDropOptionId: this.dropOptionsInfoList[i]["id"],
          status: this.dropOptionsInfoList[i]["status"],
          userInput: null,
        });
      }
    }
    for (let m = 0; m < this.dropOptionsInfoListParam.length; m++) {
      if (
        this.dropOptionsInfoList[m]["dropOptionCode"] ==
          "NO_REGISTER_SAME_TRADE" &&
        this.dropOptionsInfoList[m]["status"] == "1"
      ) {
        if (!this.everWork) {
          this.openPopInfo(
            "勾选曾经报聘后，您曾经报聘过的保险机构名称不可为空！"
          );
          return;
        }
      }
    }

    const isselectedPersonalStatement = this.dropOptionsInfoListParam.some(
      (item) => {
        return item.status == 1;
      }
    );
    if (isselectedPersonalStatement == false) {
      this.openPopInfo("请选择至少一项个人声明！");
      return;
    }
    const param = {
      hiringBasicInfoId: this.hiringBasicInfoId,
      personalStatementList: this.dropOptionsInfoListParam,
    };
    this.myService.savePersonalStatements(param).subscribe((res) => {
      if (res["success"]) {
        this.router.navigate(["/contract"], {
          queryParams: { hiringBasicInfoId: this.hiringBasicInfoId },
        });
      } else {
        this.openPopInfo(res["message"]);
      }
    });
  }

  queryContractTerms() {
    this.myService.queryContractTerms().subscribe((res) => {
      if (res["success"]) {
        this.contractTermsList = res["data"]["contractTermsList"];
        this.contractTermsList.forEach((item) => {
          item.confirmStatus = 0;
        });
        this.queryWholeInfo(this.hiringBasicInfoId);
      } else {
        this.openPopInfo(res["message"]);
      }
    });
  }

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

  readContract(contractItem) {
    if (this.approveStatus == null || this.approveStatus == "-1") {
      this.agreeBtnShow = false;
      if (contractItem.confirmStatus == 1) {
        contractItem.confirmStatus = 0;
      } else {
        this.isShow = true;
        setTimeout(() => {
          let scrollTop = this.toastContent.nativeElement.scrollTop;
          if (scrollTop >= 0) {
            // setTimeout(() => {
            this.agreeBtnShow = true;
            // }, 1000);
          }
        }, 500);
        this.curContract = contractItem.termNote;
        this.curTitle = contractItem.termName;
        this.curContractId = contractItem.id;
      }
      this.isAllAgree = this.contractTermsList.every((item) => {
        return item.confirmStatus == 1;
      });
    }
  }

  //同意合同条款
  agree() {
    if (this.agreeBtnShow == true) {
      this.isShow = false;
      for (let i = 0; i < this.contractTermsList.length; i++) {
        if (this.curContractId == this.contractTermsList[i]["id"]) {
          this.contractTermsList[i]["confirmStatus"] = 1;
        }
      }
      this.isAllAgree = this.contractTermsList.every((item) => {
        return item.confirmStatus == 1;
      });
    }
  }

  saveContractTermsConfirms() {
    this.contractTermsConfirmsListParm = [];
    for (let i = 0; i < this.contractTermsList.length; i++) {
      this.contractTermsConfirmsListParm.push({
        contractTermId: this.contractTermsList[i]["id"],
        confirmStatus: this.contractTermsList[i]["confirmStatus"],
      });
    }
    const param = {
      hiringBasicInfoId: this.hiringBasicInfoId,
      contractTermsConfirmsList: this.contractTermsConfirmsListParm,
    };
    this.myService.saveContractTermsConfirms(param).subscribe((res) => {
      if (res["success"]) {
      } else {
        this.openPopInfo(res["message"]);
      }
    });
  }

  queryWholeInfo(hiringBasicInfoId) {
    this.myService
      .queryWholeInfo({ hiringBasicInfoId: hiringBasicInfoId })
      .subscribe((res) => {
        if (res["success"]) {
          this.approveStatus = res["data"]["hiringBasicInfo"]["approveStatus"];
          if (this.type == "personal_statement") {
            if (res["data"]["hiringPersonalStatementsList"].length > 0) {
              this.dropOptionsInfoList =
                res["data"]["hiringPersonalStatementsList"];
              for (let i = 0; i < this.dropOptionsInfoList.length; i++) {
                this.dropOptionsInfoList[i][
                  "dropOptionName"
                ] = this.dropOptionsInfoList[i]["mdDropOptionName"];
                this.dropOptionsInfoList[i]["id"] = this.dropOptionsInfoList[i][
                  "mdDropOptionId"
                ];
                if (
                  this.dropOptionsInfoList[i]["status"] == 1 &&
                  this.dropOptionsInfoList[i]["dropOptionCode"] ==
                    "NO_REGISTER_SAME_TRADE"
                ) {
                  this.everWorkFlag = true;
                  this.everWork = this.dropOptionsInfoList[i]["userInput"];
                } else {
                  this.everWorkFlag = false;
                }
              }
            }
          }
          if (this.type == "contract") {
            let hiringContractTermsConfirmsList =
              res["data"]["hiringContractTermsConfirmsList"];
            for (let i = 0; i < hiringContractTermsConfirmsList.length; i++) {
              for (let j = 0; j < this.contractTermsList.length; j++) {
                if (
                  hiringContractTermsConfirmsList[i]["contractTermId"] ==
                  this.contractTermsList[j]["id"]
                ) {
                  this.contractTermsList[j]["confirmStatus"] =
                    hiringContractTermsConfirmsList[i]["confirmStatus"];
                }
              }
            }
            this.isAllAgree = this.contractTermsList.every((item) => {
              return item.confirmStatus == 1;
            });
          }
        }
      });
  }

  // onScroll(event){
  //   let scrollTop = this.toastContent.nativeElement.scrollTop;
  //   let clientHeight = this.toastContent.nativeElement.clientHeight;
  //   let scrollHeight = this.toastContent.nativeElement.scrollHeight ;
  //   if(scrollHeight > clientHeight && scrollTop + clientHeight === scrollHeight) {
  //    setTimeout(() => {
  //     this.agreeBtnShow = true;
  //    }, 5000);
  //   }
  // }

  viewNext() {
    if (this.type == "personal_statement") {
      this.saveRecord();
      this.router.navigate(["/contract"], {
        queryParams: { hiringBasicInfoId: this.hiringBasicInfoId },
      });
    }
    if (this.type == "contract") {
      this.saveRecord();
      this.router.navigate(["/signature"], {
        queryParams: { hiringBasicInfoId: this.hiringBasicInfoId },
      });
    }
  }

  goBack() {
    history.go(-1);
  }

  startCount() {
    // if(!this.timer){
    //     this.count = TIME_COUNT;
    //     this.timer = setInterval(()=>{
    //         if(this.count > 0 && this.count <= TIME_COUNT){
    //             this.count--;
    //         }else{
    //             clearInterval(this.timer);
    //             this.timer = null;
    //         }
    //     },1000)
    // }
  }
}
