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/initial-review-reject/initial-review-reject.component';
import { FrameService } from 'src/app/core/service/frame.service';
import {InitialReviewDetailComponent} from "../../initial-review/initial-review-detail/initial-review-detail.component";

@Component({
  selector: 'app-initial-notice-page',
  templateUrl: './initial-notice-page.component.html',
  styleUrls: ['./initial-notice-page.component.scss']
})
export class InitialNoticePageComponent extends FramePageComponent implements OnInit {
  @ViewChild('approvPager', {static: false}) approvPager: FramePager;
  @ViewChild('rejectPager', {static: false}) rejectPager: FramePager;
  @ViewChild('stdPager', {static: false}) stdPager: FramePager;

  uploadList = [];
  schoolArray = [];
  batchArray = [];
  majorArray = [];
  optrArray = [];
  curStep = "main";
  stdMain : any;//考生主记录
  tagArray = [];
  query = {
    school_id : '',
    batch_id : '',
    major_ids : '',
    optr_ids: '',
    main_id : '',
    main_status : '',
    detail_type : ''
  };
  constructor(private modalService: BsModalService, private detectRef: ChangeDetectorRef) {
    super(modalService);
  }

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

  //检查批次模式对应的功能按钮
  //****************批次模式对应的功能按钮*******************start*************************************
  authDtlDurSubmit = false;//提交期间-是否明细审核按钮
  authMainDurSubmit = false;//提交期间-是否显示审核主记录按钮
  authDtlDurAuth = false;//是否审核期间能审核明细
  authMainDurAuth = false;//是否审核期间能审核主记录
  msgDurSubmit = false;//提交期间-审核主记录是否发送消息通知
  msgDurAuth = false;//资格审核期间-审核主记录是否发送消息通知
  enableAuthLable = false;//资格审核期间-是否开启标签
  //****************批次模式对应的功能按钮********************end*************************************
  checkPattern() {
    //获取当前服务器时间
    AjaxService.requestEntity("cf/pattern/now/get.htm",{},(data)=>{
      let now_time = Date.parse(data);
      debugger;
      if (this.FrameService.PatternMap) {
        let batch = this.FrameService.BatchMap[this.query.batch_id];
        let pattern = this.FrameService.PatternMap[batch.pattern_id];
        let uploadStartTime = Date.parse(batch.upload_start_time);
        let uploadEndTime = Date.parse(batch.upload_end_time);
        let intialReviewStart = Date.parse(batch.intial_review_start);
        let 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;
        }
        //******
      }

    });
  }

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

  queryAspectAndOptr() {
    let param = {school_id: this.query.school_id, batch_id: this.query.batch_id};
    this.AjaxService.requestArray('./cf/major/list.htm', param, (array) => {
      //debugger;
      this.majorArray = array;
    });
    this.AjaxService.requestArray('./review/initial/optr/list.htm', param, (array) => {
      this.optrArray = array;
    });
  }

  selectMajor() {
    this.approvPager.pagerParams["major_ids"] = this.query.major_ids;
    this.approvPager.reload();

    this.rejectPager.pagerParams["major_ids"] = this.query.major_ids;
    this.rejectPager.reload();
  }

  selectOptr() {
    console.log("optrIds--->" + this.query.optr_ids + "," + this.approvPager.pagerParams["optr_ids"]);

    this.approvPager.pagerParams["optr_ids"] = this.query.optr_ids;
    this.approvPager.reload();

    this.rejectPager.pagerParams["optr_ids"] = this.query.optr_ids;
    this.rejectPager.reload();
  }

  requestData() {
    //debugger;

    this.approvPager.pagerParams["batch_id"] = this.query.batch_id;
    this.approvPager.pagerParams["major_ids"] = this.query.major_ids;
    this.approvPager.pagerParams["optr_ids"] = this.query.optr_ids;
    this.approvPager.reload();

    this.rejectPager.pagerParams["batch_id"] = this.query.batch_id;
    this.rejectPager.pagerParams["major_ids"] = this.query.major_ids;
    this.rejectPager.pagerParams["optr_ids"] = this.query.optr_ids;
    this.rejectPager.reload();
  }


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

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

  }

  sendApprovNotice() {
    let param = {
      school_id: this.query.school_id,
      batch_id: this.query.batch_id,
      major_ids: this.query.major_ids,
      optr_ids: this.query.optr_ids,
      detail_type: "approv",
      initial_remark: ""
    };
    MsgService.confirmAlert('确定发微信通知吗！', () => {
      MsgService.showLoading();
      AjaxService.requestEntity("review/initial/main/approve/batch.htm",param,(entity)=>{
        MsgService.hideLoading();
        MsgService.successToastr("发送成功!");
        this.approvPager.reload();
      });
    });
  }

  sendRejectNotice() {
    let param = {
      school_id: this.query.school_id,
      batch_id: this.query.batch_id,
      major_ids: this.query.major_ids,
      optr_ids: this.query.optr_ids,
      detail_type: "reject",
      initial_remark: "资格审核暂未通过。请考生至材料上传页面查看具体原因，并将修改后的材料于2024年1月2日15点至1月5日12点期间重交至平台。截止2024年1月5日12点，未修改重交材料或材料经重审仍未通过的考生，无法进入学术审核。"
    };
    MsgService.confirmAlert('确定发微信通知吗！', () => {
      MsgService.showLoading();
      AjaxService.requestEntity("review/initial/main/reject/batch.htm",param,(entity)=>{
        MsgService.hideLoading();
        MsgService.successToastr("发送成功!");
        this.rejectPager.reload();
      });
    });
  }

  specialList = [];
  goStdDetail(v, detail_type) {
    //debugger;
    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.query.detail_type = detail_type;//区分审核通过、还是退回
    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;
        }
      }
    });
  }

  goBack() {
    this.curStep = "main";
    // this.pager.reload();
    // this.rejectPager.reload();
    this.requestData()
  }

  //反馈考生
  doApproveMain() {
    if (!this.authMainDurAuth) {
      MsgService.errorAlert("不在资格审核范围内，无法通过");
      return;
    }

    debugger;
    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;
    }
    let _this = this;
    let 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";
        /*$("#approvBtn").attr("disabled", "disabled");//禁用
        $("#rejectBtn").attr("disabled", "disabled");*/
       /*if (!this.pager) {
          this.detectRef.detectChanges();
        }*/
        this.stdPager.reload();
      });
    });
  }

  //退回
  doRejectMain() {
    if (!this.authMainDurAuth) {
      MsgService.errorAlert("不在资格审核范围内，无法退回");
      return;
    }
    debugger;
    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";
      AjaxService.requestEntity("std/apply/main/reject/find.htm", {main_id: this.query.main_id}, (entity)=>{
        debugger;
        if (entity && entity.status == 'Reject') {
          $("#approvBtn").attr("disabled", "disabled");//禁用
          $("#rejectBtn").attr("disabled", "disabled");
        }
      });
    };*/
    this.showComponentModal(InitialReviewRejectComponent, { 'ResponseEntity': this.query }, {class: 'modal-7p'});
  }

  exportApprov() {
    let entity = {
      school_id: this.query.school_id,
      batch_id: this.query.batch_id,
      report_name:'ApprovExport',
      report_title :'审核通过考生名单'
    };
    this.FuncService.ajaxDownload('frame/report/download.htm', entity);
  }

  exportRejct() {
    let entity = {
      school_id: this.query.school_id,
      batch_id: this.query.batch_id,
      report_name:'RejectExport',
      report_title :'审核退回考生名单'
    };
    this.FuncService.ajaxDownload('frame/report/download.htm', entity);
  }

  //下一个考生
  getNextStdMain() {
    let param = {
      batch_id: this.query.batch_id,
      main_id: this.query.main_id,
      detail_type: this.query.detail_type,
      detail_review_time: this.stdMain.detail_review_time
    }
    AjaxService.requestMap("std/apply/main/next.htm", param, (entity)=>{
      //debugger;
      if (entity) {
        this.goStdDetail(entity, this.query.detail_type);
        this.stdPager.pagerParams["main_id"] = this.query.main_id;
        console.log(this.stdPager.pagerParams)
        this.stdPager.reload();
        //debugger;
        MsgService.successToastr("已加载下一个考生");
      } else {
        MsgService.warningAlert("当前考生已审核，无下一待审考生");
      }
    });
  }

}
