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-major-pre',
  templateUrl: './pl-major-pre.component.html',
  styleUrls: ['./pl-major-pre.component.scss']
})
export class PlMajorPreComponent extends FlexTableComponent implements OnInit {

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

  QUERY_URL = "pl/plMajorPre/page.htm";
  DELETE_URL = "pl/plMajorPre/delete.htm";
  GET_URL = "pl/plMajorPre/find.htm";
  ADD_URL = "pl/plMajorPre/add.htm";
  EDIT_URL = "pl/plMajorPre/edit.htm";
  YEAR_URL = "pl/plExamTime/list.htm";
  SUBJECT_URL = "pl/plSubject/find.htm";
  DOWNLOAD_URL = "pl/plMajorPre/download.htm";
  DETAIL_URL = "pl/plMajorCoursePre/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&status=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: ["", Validators.required],
      remark: ["", null],
      stop_certificate_time: ["", null],
      status: ["", Validators.required],
      new_major_code: ["" ,null],
      new_major_name: ["" ,null],
      is_new_major: ["" ,null],
      org_id: ["", Validators.required],
      is_allow_social: ["" ,null]
      // start_exam_type: ["", Validators.required]
    });
    
  }

   ngOnInit() {
     this.query.status='1';
     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;
        }

      });
    //接收参数
    setTimeout(() => { 
      this.activatedRoute.queryParams.subscribe(queryParams => {
        this.query.query = queryParams.major_code;
        this.query.year = queryParams.year_code;
      });
    }, 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 ="无对应新专业";
        }
      });
      let org_id = item.org_id;
      FrameRequest.requestMap(this.GET_URL, { id: item.id }, (map) => {
        if (!this.preGoEditEvent(map)) return;
        this.showEdit(template, editShowType, modalcss);
        setTimeout(() => { this.item = map['major']; this.item.org_id=org_id;}, 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(), year: this.query.year}, () => {
      AppComponent.GobalComponent.setLoading(false);
    });
  }

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

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

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


}
