import {ChangeDetectorRef, Component, OnInit, ViewChild} from '@angular/core';
import {FramePageComponent} from '../../../frame/core/page/frame.page';
import {BsModalService} from 'ngx-bootstrap/modal';
import { AjaxService } from '../../../../core/service/ajax.service';
import { MsgService } from '../../../../core/service/msg.service';
import { FramePager } from '../../../../core/frame/pager/frame-pager/frame-pager';
import { InitialReviewRejectComponent } from '../initial-review-reject/initial-review-reject.component';
import { ReviewPromiseComponent } from '../../final-review/review-promise/review-promise.component';
import {InitialReviewDetailComponent} from '../initial-review-detail/initial-review-detail.component';

@Component({
  selector: 'app-cf-initial-review-page',
  templateUrl: './initial-review-page.component.html',
  styleUrls: ['./initial-review-page.component.scss']
})
export class InitialReviewPageComponent extends FramePageComponent implements OnInit {

  constructor(private modalService: BsModalService, private detectRef: ChangeDetectorRef) {
    super(modalService);
    this.modalComponent = InitialReviewDetailComponent;
  }
;
  @ViewChild('stdPager', {static: false}) stdPager: FramePager;
  schoolArray = [];
  batchArray = [];
  stdMain : any;// 考生主记录
  query = {
    school_id : '',
    batch_id : '',
    main_id : '',
    main_status : '',
    now_time: ''
  };
  totalArray={
    Apply: 0,
    SecondApply: 0,
    Reject: 0,
    InitialAppr: 0
  };
  curStep = 'main';
  tagArray = [];
  specialList = [];
  specialWarn = false;

  // 检查批次模式对应的功能按钮
  // ****************批次模式对应的功能按钮*******************start*************************************
  authDtlDurSubmit = false;// 提交期间-是否明细审核按钮
  authMainDurSubmit = false;// 提交期间-是否显示审核主记录按钮
  authDtlDurAuth = false;// 是否审核期间能审核明细
  authMainDurAuth = false;// 是否审核期间能审核主记录
  msgDurSubmit = false;// 提交期间-审核主记录是否发送消息通知
  msgDurAuth = false;// 资格审核期间-审核主记录是否发送消息通知
  enableAuthLable = false;// 资格审核期间-是否开启标签

  ngOnInit() {
    // ;
    this.AjaxService.requestArray('./cf/school/list.htm', {}, (array) => {
      this.schoolArray = array;
      if (this.schoolArray.length === 1) {
        this.query.school_id = this.schoolArray[0].school_id;
        this.queryBatchArray();
        this.queryAuthTagArray();
      }
    });
    AjaxService.requestEntity('cf/batch/current/get.htm',{},(batch)=>{

      // 是否需要承诺书
      if (batch.need_promise === 1) {
        const parm = {batch_id: batch.batch_id, biz_type: 'initial'};
        AjaxService.requestMap('review/promise/find.htm',parm ,(map)=>{

          if (map && !map.sgin) {
            // 没有签
            map.promise.batch_id = batch.batch_id;
            this.showComponentModal(ReviewPromiseComponent, { ResponseEntity: map.promise }, {class: 'modal-7p'});
          }
        });
      }
    });
  }


queryAuthTagArray() {
  this.AjaxService.requestArray('./cf/authtag/list.htm', {school_id: this.query.school_id}, (array) => {
    this.tagArray = array;
  });
}
  //设置标签
  setTag() {
    AjaxService.requestEntity("review/std/auth/tag/set.htm",{apply_id: this.stdMain.apply_id, tag_id: this.stdMain.tag_id},(entity)=>{
      debugger;
      this.stdMain.tag_id = entity.tag_id;
      this.stdMain.tag_name = entity.tag_name;
      this.stdMain.tag_desc = entity.tag_desc;
      //$("#tagSpanId").css("background-color", entity.tag_color);
      $("#tagSpanId").css("color", entity.tag_color);
      MsgService.successToastr("设置成功!");
    });
  }

  //清除标签
  clearTag() {
    AjaxService.requestEntity("review/std/auth/tag/clear.htm",{apply_id: this.stdMain.apply_id},(entity)=>{
      debugger;
      this.stdMain.tag_id = "";
      this.stdMain.tag_name = "";
      this.stdMain.tag_desc = "";
      MsgService.successToastr("清除成功!");
    });
  }

  queryBatchArray() {
    AjaxService.requestArray('cf/batch/list.htm',{school_id: this.query.school_id},(array)=>{
      this.batchArray = array;
      if (this.batchArray.length >= 1) {
        this.query.batch_id = this.batchArray[0].batch_id;
      }
    });
  }
  goStdDetail(v) {

    this.curStep = 'std';
    this.stdMain = v;
    this.query.main_id = v.apply_id;
    this.query.school_id = v.school_id;
    this.query.batch_id = v.batch_id;
    this.query.main_status = v.status;
    this.stdMain.showSpecialColor = false;
    // 检查批次对应模式功能按钮
    this.checkPattern();

    // 查询限制、特殊处理考生列表
    AjaxService.requestArray('std/specila/list.htm',{school_id: this.query.school_id},(array)=>{
      this.specialList = array;
      for (const s of this.specialList) {
        if (s.exam_id === this.stdMain.exam_id && s.std_name === this.stdMain.std_name) {
          this.stdMain.showSpecialColor = true;
          break;
        }
      }
    });
  }
  // ****************批次模式对应的功能按钮********************end*************************************
  checkPattern() {
    // 获取当前服务器时间
    AjaxService.requestEntity('cf/pattern/now/get.htm',{},(data)=>{
      const nowTime = Date.parse(data);
      if (this.FrameService.PatternMap) {
        const batch = this.FrameService.BatchMap[this.query.batch_id];
        const pattern = this.FrameService.PatternMap[batch.pattern_id];
        const uploadStartTime = Date.parse(batch.upload_start_time);
        const uploadEndTime = Date.parse(batch.upload_end_time);
        const intialReviewStart = Date.parse(batch.intial_review_start);
        const intialReviewEnd = Date.parse(batch.intial_review_end);
        // ******是在提交期间
        console.log('nowTime: ' + nowTime + ',uploadStartTime: ' + uploadStartTime + ',uploadEndTime: ' + uploadEndTime);
        if (nowTime >= uploadStartTime && nowTime <= uploadEndTime) {
          if (pattern.is_auth_dtl_dur_submit) {// 提交期间-审核明细 开启
            this.authDtlDurSubmit = true;
          }
          if (pattern.is_auth_main_dur_submit) {// 提交期间-审核主记录 开启
            this.authMainDurSubmit = true;
          }
          if (pattern.is_msg_dur_submit) {// 提交期间-审核主记录是否实时发送消息通知
            this.msgDurSubmit = true;
          }
        }
        // ******是在审核期间
        if (nowTime >= intialReviewStart && nowTime <= intialReviewEnd) {
          if (pattern.is_msg_dur_auth) {// 资格审核期间-审核主记录是否实时发送消息通知
            this.msgDurAuth = true;
          }
          if (pattern.is_enable_auth_lable) {// 资格审核期间-是否开启主记录标签
            this.enableAuthLable = true;
          }
          this.authDtlDurAuth = true;// 审核期间可以审核明细和主
          this.authMainDurAuth = true;
        }
        // ******
      }

    });
  }

  goBack() {
    this.curStep = 'main';
    this.pager.reload();
  }

  requestData() {
    this.pager.reload();
  }

  // 材料查看
  showMaterilModal(v) {

    this.onModalClose = () => {
      if (!this.stdPager) {
        this.detectRef.detectChanges();
      }
      this.stdPager.reload();// 刷新详情列表
    };
    v.std_name=this.stdMain.std_name;
    const imageList = [];
    // 查询当前考生材料要展示的
    AjaxService.requestMap('std/apply/upload/list.htm',{detail_id: v.detail_id},(map)=>{
      // ;

      v.textAttrs=map.textAttrs;
      v.uploadList=map.uploadList;
      this.showComponentModal(InitialReviewDetailComponent, { ResponseEntity: v }, {class: 'modal-8p'});
    });

  }

  // 反馈考生
  doApproveMain() {

    if (!this.stdPager) {
      this.detectRef.detectChanges();
    }
    let notReview = false;
    for (const d of this.stdPager.getRecords()) {
      if (d.back_status !== 'InitialAppr') {
        notReview = true;
      }
    }
    if (notReview) {
      MsgService.errorAlert('明细列表存在退回或待审核状态材料，请检查。');
      return;
    }
    const _this = this;
    const param = {apply_id: this.query.main_id, initial_remark: ''};
    MsgService.confirmAlert('确定通过吗，该操作会反馈考生！', () => {
      MsgService.showLoading();
      AjaxService.request('review/initial/main/approve.htm', param, (entity) => {
        MsgService.hideLoading();
        MsgService.successToastr('初审通过!');
        this.curStep = 'main';
        if (!this.pager) {
          this.detectRef.detectChanges();
        }
        this.pager.reload();
      });
    });
  }

  total(page, status: string){
      this.totalArray[status]=page.total;
  }  // 退回

  doRejectMain() {
    if (!this.stdPager) {
      this.detectRef.detectChanges();
    }
    let hasReject = false;
    let notReview = false;
    for (const d of this.stdPager.getRecords()) {
      if (d.back_status === 'Reject') {
        hasReject = true;
      }
      if (d.back_status === 'New' || d.back_status === 'Apply' || d.back_status === 'SecondApply') {
        notReview = true;
      }
    }
    if (notReview) {
      MsgService.errorAlert('明细列表存在待审核状态材料，请检查。');
      return;
    }
    if (!hasReject) {
      MsgService.errorAlert('明细列表没有退回状态材料，请检查。');
      return;
    }
    this.onModalClose = () => {
      this.curStep = 'main';
    };
    this.showComponentModal(InitialReviewRejectComponent, { ResponseEntity: this.query }, {class: 'modal-7p'});
  }

}
