import { Component, OnInit, TemplateRef } from '@angular/core';
import { FlexTableComponent } from '../../../../shared/common/FlexTable.component';
import { BsModalService } from 'ngx-bootstrap/modal';
import {  Validators, FormBuilder } from '@angular/forms';
import { CustomValidators } from 'ng2-validation';
import { FrameFunction } from '../../../../shared/frame/frame_function';
import { FrameRequest } from '../../../../shared/frame/frame-request';
import { AppComponent } from '../../../../app.component';
import { Router, ActivatedRoute } from '@angular/router';


declare var $: any;
@Component({
  selector: 'app-pl-majorquery',
  templateUrl: './pl-major.component.query.html',
  styleUrls: ['./pl-major.component.query.scss']
})
export class PlMajorComponentQuery extends FlexTableComponent implements OnInit {

  public query = {
    query: "",
    major_level: "",
    nation_exam: "",
    year: "",
    status: "",
    org_id: "",
    exam_time_id:""
  };
  yearArray: any;
  subjectArray: any;
  childSubjectArray: any;
  major: any;
  ctList = [];
  newMajor: any;
  flag = true; //控制新专业显示
  permFlag = false;

  curr_major_id: any;
  modalWin: any;

  QUERY_URL = "pl/plMajor/page.htm";
  DELETE_URL = "pl/plMajor/delete.htm";
  GET_URL = "pl/plMajor/find.htm";
  ADD_URL = "pl/plMajor/add.htm";
  EDIT_URL = "pl/plMajor/edit.htm";
  YEAR_URL = "pl/plExamTime/list.htm";
  SUBJECT_URL = "pl/plSubject/find.htm";
  DOWNLOAD_URL = "pl/plMajor/download.htm";
  DETAIL_URL = "pl/plMajorCourse/detail.htm";
  NEW_MAJOR_URL = "pl/plMajorOldNew/getNewMajor.htm";
  GET_DEPT_URL = "frame/optr/getDeptType.htm"; //登录用户所属机构类型
  SCHOOL_URL = "cf/cfOrganization/list.htm?org_type=1";


  public constructor(
    public bsModalService: BsModalService,
    private activatedRoute: ActivatedRoute
  ) {
    super();
    //编辑页面验证初始化
    const fb = new FormBuilder();
    this.formModel = fb.group({
      id: [],
      year: ["", Validators.required],
      major_code: ["", Validators.compose([Validators.required, CustomValidators.rangeLength([3, 8]), Validators.pattern("^[a-zA-Z0-9]+$")])],
      major_name: ["", Validators.compose([Validators.required])],
      // major_standard_code: ["", [Validators.required, CustomValidators.rangeLength([3, 8]), Validators.pattern("^[a-zA-Z0-9]+$")]],
      major_standard_code: ["", null],
      major_level: ["", Validators.required],
      // is_nation_exam: ["", Validators.required],
      subject_pid: ["", null],
      subject_id: ["", null],
      graduate_total_credits: ["", null],
      remark: ["", null],
      stop_certificate_time: ["", null],
      status: ["", Validators.required],
      new_major_code: ["" ,null],
      new_major_name: ["" ,null]
      // start_exam_type: ["", Validators.required]
    });
    
  }

   ngOnInit() {
     FrameRequest.requestArray(this.YEAR_URL, {}, (array) => {
       this.yearArray = array;
      });
      FrameRequest.requestArray(this.SUBJECT_URL, {}, (array) => {
        this.subjectArray = array;
      })
      FrameRequest.requestEntity(this.GET_DEPT_URL, {}, (entity) => {
        if(entity && entity === 1) {
           this.permFlag = true;
        } else {
          this.permFlag = false;
        }

      });

      FrameRequest.requestEntity("pl/plExamTime/getCurrentExamTimeId.htm", {}, (entity) => {
        if(entity) {
          this.query.exam_time_id = entity.id;
        }
        });

    //接收参数
    setTimeout(() => { 
      this.activatedRoute.queryParams.subscribe(queryParams => {
        this.query.query = queryParams.major_code;
        this.query.year = queryParams.year_code;
        this.framePager.reload();
      });
    }, 100);
    
  }

  async preGoEditEvent(map) {
    let pid=null;
    if(map) {
      let major = map['major'];
      if(major) {
        pid = major.subject_pid;
      }
    }
    await this.childSubject(pid);
    return true
  }

  // editShowType : modal模态弹出框 only只显示编辑界面 show 同时显示
  async goEdit(template: TemplateRef<any>, editShowType = "modal", modalcss: string, item?) {
    FrameFunction.UntouchedForm(this.formModel);
    //新增
    if (!item || item.id === undefined) {
      if (!this.preGoEditEvent({})) return;
      this.item = {};
      this.newMajor = {} ;
      this.formModel.reset();
      this.flag = true;
      this.showEdit(template, editShowType, modalcss);
    } else {
      this.flag = false;
      FrameRequest.requestEntity(this.NEW_MAJOR_URL, {old_major_id: item.id}, (entity) => {
        if(entity) {
          this.newMajor = entity;
        } else {
          this.newMajor = {} ;
          this.newMajor.new_major_code ="无对应新专业";
          this.newMajor.new_major_name ="无对应新专业";
        }
      });
      FrameRequest.requestMap(this.GET_URL, { id: item.id }, (map) => {
        if (!this.preGoEditEvent(map)) return;
        this.showEdit(template, editShowType, modalcss);
        setTimeout(() => { this.item = map['major']; }, 100)
      });
    }
  }
  async childSubject(pid) {
      if (pid) {
        FrameRequest.requestArray(this.SUBJECT_URL, {pid: pid}, (resp) => {
          this.childSubjectArray = resp;
        })
      }
  }

  downloadMajor() {
    let checkArray = this.framePager.getCheckedArray();
    let ids = [];
    if(!checkArray || checkArray.length == 0) {
      AppComponent.alert({title:'提示', text: '请选择要打印专业课程的专业'});
      return;
    }
    if(checkArray && checkArray.length > 0) {
      ids =  this.framePager.getCheckedArray((item) => item.id);
    }
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download(this.DOWNLOAD_URL, {ids: ids.join(), exam_time_id: this.query.exam_time_id}, () => {
      AppComponent.GobalComponent.setLoading(false);
    });
  }

  detail(show_type: string, major_id: number) {
    this.curr_major_id = major_id;
    FrameRequest.requestMap(this.DETAIL_URL, { major_id: major_id }, (map) => {
      setTimeout(() => {
        this.major = map['major'];
        this.ctList = map['ctList'];
        this.editShowType = show_type;
      },100);
    });
   
  }

  selectCourse(exam_time_id){
    if(!exam_time_id){
      exam_time_id = "";
    }
    
    FrameRequest.requestMap(this.DETAIL_URL, { major_id: this.curr_major_id,exam_time_id:exam_time_id }, (map) => {
      this.ctList = map['ctList'];
    });
  }

  getNewMajor(major_code: any) {
    FrameRequest.requestEntity(this.NEW_MAJOR_URL, {old_major_code: major_code}, (entity) => {
      this.newMajor = entity;
    });
  }


  export() {
    
    
    AppComponent.GobalComponent.setLoading(true);
    FrameRequest.download("pl/plMajorCourse/majorPlanExport.htm", { major_id: this.major.id,exam_time_id:this.query.exam_time_id }, () => {
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("导出成功");
    });
  }

  
  syncTask(template: TemplateRef<any>, modalcss?) {
    let checkArray = this.framePager.getCheckedArray();
    
    if(!checkArray || checkArray.length == 0 ) {
      AppComponent.alert({title:'提示', text: '请选择要打印专业课程的专业'});
      return;
    }

    let css = modalcss ? modalcss : "modal-lg";
    this.modalWin = this.bsModalService.show(template, { class: css });
  }

  hideModalWin() {
    if (this.modalWin) {
      this.modalWin.hide();
    }
  }

  downloadFile(id) {
    FrameRequest.download("pl/plTextbook/downloadFile.htm",  { id: id });
  }


}
