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 { Router,ActivatedRoute } from '@angular/router';
import { InitialReviewPageComponent } from '../../initial-review/initial-review-page/initial-review-page.component';

import { InitialReviewRejectComponent } from '../../initial-review/initial-review-reject/initial-review-reject.component';
import {InitialReviewDetailComponent} from '../../initial-review/initial-review-detail/initial-review-detail.component';

declare var $: any;

@Component({
  selector: 'app-initial-progress-page',
  templateUrl: './initial-progress-page.component.html',
  styleUrls: ['./initial-progress-page.component.scss']
})
export class InitialProgressPageComponent extends FramePageComponent implements OnInit {
  constructor(private modalService: BsModalService, private router: Router, private detectRef: ChangeDetectorRef) {
    super(modalService);
  }
  @ViewChild('summeryPager', {static: false}) summeryPager: FramePager;
  @ViewChild('mainPager', {static: false}) mainPager: FramePager;
  @ViewChild('stdPager', {static: false}) stdPager: FramePager;

  uploadList = [];
  schoolArray = [];
  batchArray = [];
  tagArray = [];
  curStep = 'summery';
  stdMain : any;// 考生主记录

  approvDisabled = false;
  rejectDisabled = false;

  query = {
    main_id : '',
    school_id : '',
    batch_id : '',
    optr_id : '',
    status : ''
  };

  specialList = [];

  // 检查批次模式对应的功能按钮
  // ****************批次模式对应的功能按钮*******************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();
      }
    });
  }

  queryAuthTagArray() {
    this.AjaxService.requestArray('./cf/authtag/list.htm', {school_id: this.query.school_id}, (array) => {
      this.tagArray = array;
    });
  }

  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;
        this.requestData();
      }
    });
  }

  requestData() {
    //
    this.summeryPager.pagerParams["school_id"] = this.query.school_id;
    this.summeryPager.pagerParams["batch_id"] = this.query.batch_id;
    this.summeryPager.reload();
  }

  // 总人数
  goMain(v, status) {
    //
    this.curStep = 'main';
    this.query.status = status;
    this.query.optr_id = v.optr_id;
    this.mainPager.pageStart=1
    this.mainPager.reload({school_id: this.query.school_id,batch_id: this.query.batch_id, optr_id: this.query.optr_id,status: this.query.status});
  }

  goMainAll(status) {
    this.curStep = 'main';
    this.query.optr_id = '';
    this.query.status = status;// 总计查询所有
    this.mainPager.pageStart=1
    this.mainPager.reload({school_id: this.query.school_id,batch_id: this.query.batch_id, optr_id: this.query.optr_id,status: this.query.status});
  }
  goStdDetail(v) {

    this.curStep = 'std';
    this.stdMain = v;
    this.query.main_id = v.apply_id;
    this.stdMain.showSpecialColor = false;
    if (this.stdMain.status === 'Reject' || this.stdMain.status === 'InitialAppr') {
      this.approvDisabled = true;
      this.rejectDisabled = true;
    } else {
      this.approvDisabled = false;
      this.rejectDisabled = 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;
        }
      }
    });

    const _this = this;
    setTimeout(() =>{
      $('#tagSpanId').css('color', _this.stdMain.tag_color);
    }, 500);
  }
  // ****************批次模式对应的功能按钮********************end*************************************
  checkPattern() {
    // 获取当前服务器时间
    AjaxService.requestEntity('cf/pattern/now/get.htm',{},(data)=>{
      const now_time = 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('now_time: ' + now_time + ',uploadStartTime: ' + uploadStartTime + ',uploadEndTime: ' + uploadEndTime);
        if (now_time >= uploadStartTime && now_time <= 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 (now_time >= intialReviewStart && now_time <= 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(step) {

    this.curStep = step;
    if(this.curStep==='summery')this.requestData();
    if(this.curStep==='main')this.mainPager.reload();
  }

   // 材料查看
   showMaterilModal(v) {
    //
    v.main_status = this.stdMain.status;
    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.mainPager) {
          this.detectRef.detectChanges();
        }
        this.mainPager.reload();
      });
    });
  }

  // 退回
  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'});
  }

  // 初审结束时间过后、审核不通过的发消息通知
  endTimeFailNotice() {
    const param = {
      batch_id: this.query.batch_id
    };
    MsgService.confirmAlert('确定发微信通知吗！', () => {
      MsgService.showLoading();
      AjaxService.requestEntity('review/initial/notice/fail.htm',param,(entity)=>{
        MsgService.hideLoading();
        MsgService.successToastr('发送成功!');
      });
    });
  }

  // 设置标签
  setTag() {
    AjaxService.requestEntity('review/std/auth/tag/set.htm',{apply_id: this.stdMain.apply_id, tag_id: this.stdMain.tag_id},(entity)=>{

      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)=>{

      this.stdMain.tag_id = '';
      this.stdMain.tag_name = '';
      this.stdMain.tag_desc = '';
      MsgService.successToastr('清除成功!');
    });
  }

  unSubmitNotice() {
    const param = {
      batch_id: this.query.batch_id
    };
    MsgService.confirmAlert('确定发微信通知吗！', () => {
      MsgService.showLoading();
      AjaxService.requestEntity('review/initial/notice2.htm',param,(entity)=>{
        MsgService.hideLoading();
        MsgService.successToastr('发送成功!');
      });
    });
  }

  export() {
    const entity = {
      school_id: this.query.school_id,
      batch_id: this.query.batch_id,
      optr_id: this.query.optr_id,
      status: this.query.status
    };
    this.FuncService.ajaxDownload('review/initial/page/export.htm', entity);
  }
}
