import { Component, OnInit, TemplateRef, ViewChild } from "@angular/core";
import { FormBuilder, Validators } from '@angular/forms';
import { CustomValidators } from 'ng2-validation';
import { BsModalService } from "ngx-bootstrap/modal";
import { FlexTableComponent } from "../../../../../shared/common/FlexTable.component";
import { AppComponent } from "../../../../../app.component";
import { FrameUploaderComponent } from '../../../../../core/uploader/uploader.component';
import { FrameRequest } from "../../../../../shared/frame/frame-request";
import { FramePagerComponent } from "../../../../../core/pager/pager.component";
import { FrameFunction } from "../../../../../shared/frame/frame_function";
import * as _ from 'lodash';

@Component({
  selector: "app-pl-joinschoolauth",
  templateUrl: "./school-auth.component.html",
  styleUrls: ["./school-auth.component.scss"]
})
export class JoinchoolAuthComponent extends FlexTableComponent implements OnInit {

  public batchQuery = {
    query: "",
    year_code: ""
  }

  public mainQuery = {
    query: "",
    year_code: "",
    school_id: "",
    batch_id: "",
    join_school_id: ""
  };
  
  public detailQuery = {
    school_id:"",
    course_id: "",
    major_id: "",
    query: ""
  }
 
  public impParam = {
    year_code: ""
  }

  @ViewChild('uploader')
  uploader: FrameUploaderComponent;
  @ViewChild('mainPager')
  mainPager:FramePagerComponent;
  @ViewChild('detailPager')
  detailPager:FramePagerComponent;

  @ViewChild('rejectModal')
  rejectModal: TemplateRef<any>;
  @ViewChild('joinSchoolUploadModal')
  joinSchoolUploadModal: TemplateRef<any>;

  filePath : String;
  yearCodeList = [];
  courseList = [];

  BATCH_QUERY_URL = "kj/kjCollegeBatchInfo/page.htm";//批次分页
  QUERY_MAIN_URL = "kj/kjCollegeScoreMain/page.htm";//申报主记录分页

  DELETE_URL = "kj/kjCollegeBatchInfo/delete.htm";
  GET_URL = "kj/kjCollegeBatchInfo/get.htm";
  ADD_URL = "kj/kjCollegeBatchInfo/add.htm";
  EDIT_URL = "kj/kjCollegeBatchInfo/edit.htm";

  UPLOAD_URL = "pl/kjCollegeScoreMain/join/upload.htm";
  ORG_LIST_URL = "cf/cfOrganization/list.htm";
  QUERY_DETAIL_URL = "kj/kjCollegeScoreDetail/page.htm";

  AUTH_PASS_URL = "kj/kjCollegeScoreMain/auditpass.htm";
  AUTH_REJECT_URL = "kj/kjCollegeScoreMain/auditreject.htm";

  JOIN_SCHOOL_URL = "pl/plMajorApplyJoinSchool/list.htm"; //衔接学校
  COLLEG_SCORE_SCHOOL_URL = "kj/kjCollegeScoreSchool/list.htm";

  main_id = "";
  school_id="";
  year_code="";
  pageLevel = "main";//标识 主列表 和 计划详情列表切换
  majorList = [];
  masterSchoolList = [];
  joinSchoolList = []; //衔接学校
  defaultBatchName = "";
  allJoinSchool = []; //衔接学校上报情况
  main_status = -1;//主记录状态
  GLOBAL_SCORE_TYPE = 2;//专本衔接成绩

  public rejectObject = {
    reject_remark:""
  }

  constructor(
    public bsModalService: BsModalService,
    fb: FormBuilder
  ) {
    super();
    // CustomValidators.rangeLength([1, 6])
    this.formModel = fb.group({
      id: [null],
      'year_code' : [null, Validators.compose([Validators.required])],
      'batch_name' : [null, Validators.compose([Validators.required])],
      'remark' : [null],
    });
  }

  ngOnInit() {
    this.pageLevel = "batch";
    this.editShowType = "showBatchList";
     //课程--course_exam_type=空查所有课程
     FrameRequest.requestArray("pl/plCourse/listCourseByType.htm", {course_exam_type:"",special_flag:""}, (arrary)=>{
       this.courseList = arrary;
     });
    //专业
    var parm = {ids:""};
    FrameRequest.requestArray("pl/plMajor/list.htm", parm, (arrary) => {
      this.majorList = arrary;
    });
    //衔接学校
    FrameRequest.requestArray(this.JOIN_SCHOOL_URL, {}, (arrary) => {
      this.joinSchoolList = arrary;
    });
    //年度码
    FrameRequest.requestArray("pl/plYearCode/list.htm", {}, (array) => {
      this.yearCodeList = array;
    });
  }

  batchSearch(param) {
    param.query = this.batchQuery.query;
    param.yearCode = this.batchQuery.year_code;
    param.scoreType = this.GLOBAL_SCORE_TYPE;//专本衔接
  }

  mainSearch(param) {
    param.query = this.mainQuery.query;
    param.yearCode = this.mainQuery.year_code;
    param.schoolId = this.mainQuery.school_id;
    param.batchId = this.mainQuery.batch_id;
    param.scoreType = this.GLOBAL_SCORE_TYPE;//专本衔接
    param.joinSchoolId = this.mainQuery.join_school_id;
  }

  detailSearch(paramDetail) {
    if (!this.detailQuery.course_id) {
      this.detailQuery.course_id = "";
    }
    if (!this.detailQuery.major_id) {
      this.detailQuery.major_id = "";
    }
    paramDetail.query = this.detailQuery.query;
    paramDetail.courseId = this.detailQuery.course_id;
    paramDetail.majorId = this.detailQuery.major_id;
    paramDetail.schoolId = this.school_id;
    paramDetail.yearCode = this.year_code;
    paramDetail.scoreType = this.GLOBAL_SCORE_TYPE;//专本衔接
    paramDetail.main_id = this.main_id;
  }

  //年度码选择
  yearCodeChange(year_code) {

  }

  //审核通过
  doAudit() {
    let checkedArray = this.mainPager.getCheckedArray();
    if (checkedArray.length == 0) {
      AppComponent.alert({title:"信息提示",text:"请选待审核记录!"});
      return;
    }
    let forbiden = false;
    for (let obj of checkedArray) {
      if (obj.status != 1) {//主考学校只能审核状态为1的
        forbiden = true;
        AppComponent.alert({title:"信息提示",text:"只能审核待主考学校审核记录!"});
        break;
      }
    }
    if (forbiden) {
      return false;
    }
    AppComponent.confirm("确定审核通过",()=>{
      let idArr = checkedArray.map((obj) => obj.id);
      FrameRequest.request(this.AUTH_PASS_URL, {ids: idArr,toStatus: 2}, (ret)=>{
        if (ret.errorCode == 0) {
          this.mainPager.reload();
          AppComponent.GobalComponent.successMsg('成功审核通过!');
        }
      });
    });
  }
  
  popUpRejectWind() {
    let exist = false;
    let checkedArray = this.mainPager.getCheckedArray();
    if (checkedArray.length == 0) {
      AppComponent.alert({title:"信息提示",text:"请选待审核记录!"});
      return;
    }
    for (let obj of checkedArray) {
      if (obj.status != 1) {
        AppComponent.alert({title:"信息提示",text:"只能驳回待审批记录!"});
        exist = true;
        break;
      }
    }
    if (!exist) {
      this.shouModalWin(this.rejectModal,'modal-md');
    }
  }
  //查看衔接学校上报情况
  showJoinSchool() {
    FrameRequest.requestArray(this.COLLEG_SCORE_SCHOOL_URL, {batch_id: this.mainQuery.batch_id} ,(array) => {
        this.allJoinSchool = array;
        this.shouModalWin(this.joinSchoolUploadModal,'modal-lg');
    });
  }

  doReject() {
    let checkedArray = this.mainPager.getCheckedArray();
    AppComponent.confirm("确定驳回",()=>{
      let idArr = checkedArray.map((obj) => obj.id);
      let rejectParam = {
        id: idArr, 
        toStatus: 0, 
        scoreType: this.GLOBAL_SCORE_TYPE, //专本衔接
        msg: this.rejectObject.reject_remark
      }
      FrameRequest.request(this.AUTH_REJECT_URL, rejectParam, (ret)=>{
        if (ret.errorCode == 0) {
          this.hideModal();
          this.mainPager.reload();
          this.editShowType = "showMainList";
          AppComponent.GobalComponent.successMsg('成功驳回!');
        }
      });
    });

  }

  //打开申报主记录列表
  goMainList(batch_id,year_code) {
    this.mainQuery.batch_id = batch_id;
    this.mainQuery.year_code = year_code;
    this.editShowType = "showMainList";
    this.pageLevel = "main";
    this.mainPager.reload();
  }

  //打开批次对应的计划详情
  goDetailList(id,year_code, school_id, status) {
    this.editShowType = "practicalDetailList";
    this.pageLevel = "detail";
    this.year_code = year_code;
    this.school_id = school_id;
    this.main_status = status;
    this.main_id = id;
    this.detailPager.reload();
  }

  //返回主列表
  backMain() {
    this.editShowType = "showMainList";
    this.pageLevel = "main";
  }

  //返回批次列表
  backBatch() {
    this.editShowType = "showBatchList";
    this.pageLevel = "batch";
  }

  //从主表删除
  deletePlanMain(item) {
    let checkedArray = this.mainPager.getCheckedArray();
    if(checkedArray.length === 0 && !item) {
      AppComponent.alert({title:"信息提示",text:"请选择数据!"})
      return;
    }
    if (item.status != 0&&item.status != 1) {
      AppComponent.alert({ 'title': '提示', text: '只能删除新建状态记录！' });
      return false;
    }
    AppComponent.confirm("确定删除",()=>{
      let checkedArray = [];
      item ? checkedArray[0] = item.id: 
             checkedArray = this.mainPager.getCheckedArray((item)=>item.id);
      
      FrameRequest.requestMap("kj/kjCollegeScoreMain/delete.htm", {ids:checkedArray.join()}, () => {
        AppComponent.GobalComponent.successMsg('数据删除成功!');
        this.aftDeleteEvent();
        this.mainPager.reload();
      });
    });
  }


  deletePlanDetail(item) {
    let checkedArray = this.detailPager.getCheckedArray();
    if(checkedArray.length === 0 && !item) {
      AppComponent.alert({title:"信息提示",text:"请选择数据!"})
      return;
    }
    if (this.main_status != 0&&this.main_status != 1) {
      AppComponent.alert({ 'title': '提示', text: '只能删除新建状态记录！' });
      return false;
    }
    AppComponent.confirm("确定删除",()=>{
      let checkedArray = [];
      item ? checkedArray[0] = item.id: 
             checkedArray = this.detailPager.getCheckedArray((item)=>item.id)
      
      FrameRequest.requestMap("kj/kjCollegeScoreDetail/delete.htm", {ids:checkedArray.join()}, () => {
        AppComponent.GobalComponent.successMsg('数据删除成功');
        this.aftDeleteEvent();
        this.detailPager.reload();
      });
    });
  }
}