import { Component, OnInit, TemplateRef, ViewChild, ViewContainerRef } 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 { FrameUploaderComponent} from '../../../../core/uploader/uploader.component';
import { AppComponent } from "../../../../app.component";
import { FrameRequest } from "../../../../shared/frame/frame-request";
import { FramePagerComponent } from "../../../../core/pager/pager.component";
import { FrameVariable } from "../../../../shared/frame/frame-variable";
import { FrameFunction } from "../../../../shared/frame/frame_function";

declare var $: any;

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

  @ViewChild('framePager')
  framePager:FramePagerComponent;
  
  @ViewChild('editTemplateModal')
  editTemplateModal:TemplateRef<any>;

  @ViewChild('uploader')
  uploader: FrameUploaderComponent;

  joinSchoolWin: any;

/**
 * 机构类型.
 */
 OrgTypeEnum = {
    PROVINCE_EXAM:0,
    SCHOOL_EXAM:1,
    CITY_EXAM:2,
    ASSIST_EXAM:3,
    EXAM_AREA:4,
    STUDY_CENTER:5
  };          
  
  applyTimeList = [];
  masterSchoolList = [];//主考学校
  joinSchoolList = []; //所有衔接学校
  currJoinSchoolMap = {};//专业对应的衔接学校
  currSelectMajorId="";//当前选择的专业--衔接学校添加到该专业下
  majorList = [];//专业列表-列表查询
  filterMajorList = [];//
  curOrg = {id:"",org_code:"",org_name:"",contact_number:"",org_type:"",org_code_bz:""};//当前登录人的机构
  selectMajorMap = {};//申报界面选择的专业map
  //schoolIds = [];//提交选择的衔接学校、主考学校列表
  majorIds = [];//提交选择的专业数组
  joinSchoolIds = []; //衔接学校ID数组
  //applyMasterShoolId : any;//申报选择主考学校
  eduLevel : any;
  isHiddenMajorFlag = true;//默认不显示已添加专业列表
  isHiddenSchoolFlag = true;//默认不显示已添加衔接学校列表
  isHiddenJoinSchoolFlag = true; //衔接学校是否显示
  curApplyForm : any;
  curYearCode : any;//申报界面使用的年度码
  curYear : any;//申报界面使用的年度码

  yearCodeList = [];

  authList = [];//已审核记录
  appledMajorList = [];//之前申请的专业列表
  appledJoinSchoolMap = {};//之前申请的专本衔接,majorId--List<专本衔接学校>

  isActive=0;

  public query = {
    year: "",
    school_id:"",  //主考学校
    join_school_id: "",  //申报学校
    major_id: "",
    status:"" 
  };

  public joinQuery = {
    orgId:""  //专本衔接学校维护界面 选择的衔接学校ID
  }

  QUERY_URL = "pl/plMajorApplyPro/page.htm";
  DELETE_URL = "pl/plMajorApplyPro/delete.htm";
  GET_URL = "pl/plMajorApplyPro/get.htm";
  ADD_URL = "pl/plMajorApplyPro/add.htm";
  EDIT_URL = "pl/plMajorApplyPro/edit.htm";

  YEARCODE_URL = "pl/plYearCode/listYear.htm";

  UPLOAD_URL = "pl/plMajorApplyPro/upload.htm";
  DOWNLOAD_URL = "pl/plMajorApplyPro/download.htm";
  GET_APPLY_INFO = "pl/plMajorApplyPro/applyinfo.htm";

  constructor(public bsModalService: BsModalService, fb: FormBuilder) {
    super();
    // CustomValidators.rangeLength([1, 6])
    this.formModel = fb.group({
      id: [null],
       'year': [null, Validators.compose([Validators.required])],
       //'file_path': [null],
       'major_id': [null],
      // 'apply_form': [null, Validators.compose([Validators.required])],
      // 'apply_no': [null, Validators.compose([Validators.required])],
      'school_id': [null, Validators.compose([Validators.required])],
      'join_school_id': [null, Validators.compose([Validators.required])],
      
       'apply_remark' : [null]
    });
  }

  ngOnInit() {
    this.query.status = "1";
    //基础数据(主考学校列表、专业列表、当前登录机构对象)
    FrameRequest.requestMap("pl/plMajorApply/basedata.htm", {org_type:[1]}, (map)=>{
      this.curOrg = map.curOrg;
     // this.masterSchoolList = map.schoolList;
     // this.majorList = map.majorList;
    //  this.joinSchoolList = map.joinSchoolList;
      this.curYearCode = map.year_code;
      this.curYear = map.year;
    });
    FrameRequest.requestArray(this.YEARCODE_URL, {}, (array)=>{
      this.yearCodeList = array;
    });

    FrameRequest.requestArray("cf/cfOrganization/list.htm", {org_type:5,status:1}, (array)=>{
      this.joinSchoolList = array;
    });

    FrameRequest.requestArray("pl/plMajor/queryMajorByStatus.htm", {status:1,major_level:1}, (arrary) => {
      this.majorList = arrary;
    });

    this.preShowModalWin();

    FrameRequest.requestArray("cf/cfOrganization/list.htm?org_type=1&status=1", {}, (array)=>{
      this.masterSchoolList = array;
    });
  }

  search(param) {
    if (this.query.year == null) {
      this.query.year="";
    }
    if (this.query.join_school_id == null) {
      this.query.join_school_id="";
    }
    if (this.query.school_id == null) {
      this.query.school_id="";
    }
    if (this.query.major_id == null) {
      this.query.major_id="";
    }
    
    param.year=this.query.year;
    param.join_school_id=this.query.join_school_id;
    param.school_id=this.query.school_id;
    param.major_id=this.query.major_id;
    param.status=this.query.status;
  }

  resetQuery(){
    this.query.year="";
    this.query.school_id="";
    this.query.join_school_id="";
    this.query.major_id="";
  }
  

  //删除代理
  proxyDelete(item?) {
    AppComponent.confirm("确定删除吗？",()=>{
      FrameRequest.request(this.DELETE_URL, {id:item.id,detail_id:item.detail_id}, (ret)=>{
        if (ret.errorCode == 0) {
          this.hideModal();
          this.framePager.reload();
          AppComponent.GobalComponent.successMsg("删除成功");
          
        }
      });
    });

    
    
   
  }

  async preShowModalWin(){
    FrameRequest.requestArray("pl/majorApplyTime/applytimelist.htm", {}, (arr)=>{
      this.applyTimeList = arr;
    });
    return true
  }

  //进入申报界面
  enterApply(apply_form, year_code) {
    this.hideModal();
    this.item = {};
    this.appledMajorList = [];
    this.selectMajorMap = {};
    //this.shouModalWin(this.editTemplateModal,'modal-lg');
    this.goEdit(this.editTemplateModal,'only','modal-lg',this.item);
    this.curApplyForm = apply_form;
    this.curYearCode = year_code;
    this.selectMajorMap = {};//清空专业选择
    this.appledJoinSchoolMap = {};
    //init
    this.item.year_code = year_code;
   // FrameRequest.requestArray("pl/plMajorApplyDir/dirmajorlist.htm", {year: String(year_code).substring(0,4),applyForm: apply_form}, (arr)=>{
   //   this.majorList = arr;
   // });
  }

  async toApply() {
    
    this.item = {};
    this.item.year = this.curYear;
    this.appledMajorList = [];
    this.selectMajorMap = {};//清空专业选择
    //this.appledJoinSchoolMap = {};
    this.goEdit(this.editTemplateModal,'only','modal-lg',this.item);

  }

  
  //申报时间列表界面
  addMultiMajor() {
    if (this.item.major_id) {
      let major = this.getMajor(this.item.major_id);
      this.selectMajorMap[this.item.major_id] = {
        major_code:major.major_code,
        major_name:major.major_name,
        major_score:major.major_score
      };
      this.isHiddenMajorFlag = false;
    }
  }
  
  getMajor(majorId) {
    for (let major of this.majorList) {
      if (major.id == majorId) {
        return major;
      }
    }
    return null;
  }

  //列表删除专业
  deleteMajor(key) {
    delete this.selectMajorMap[key];
    if (this.getKeys(this.selectMajorMap).length == 0) {//删除完后隐藏
      this.isHiddenSchoolFlag = true;
    }
  }

  getKeys(item) {
    return Object.keys(item);
  }

  //上传申报资料
  uploadFile() {
    let obj = this.item;
    
      //上传文书
      let param = {yearCode: this.item.year_code};
      this.uploader.choooseFileAndUpload(param, ((ret) => {
        if (ret.errorCode == 0) {
          obj.file_path = ret.map.file_path;
          obj.file_name = ret.map.file_name;
          AppComponent.GobalComponent.successMsg("上传成功!");
        }else if (ret.errorCode == -1) {
         
          AppComponent.GobalComponent.errorMsg(ret.errorMsg);
        }
      }));
  }

  //下载申报资料
  downloadFile(id) {
    FrameRequest.download(this.DOWNLOAD_URL,  { id: id });
  }
  
  //代理打开 详情审批界面
  proxyGoEdit(item) {
    //先清空以前的数据
    this.authList = [];
    this.appledMajorList = [];
    this.selectMajorMap = {};
    this.curApplyForm = item.apply_form;
    this.curYear = item.year;
    //获取申请详情
    FrameRequest.requestMap(this.GET_APPLY_INFO, {id: item.id}, async (map) => {
      this.authList = map.authList;
      this.appledMajorList = map.applyMajorList;

      if (!item.id) {//新建
        this.appledJoinSchoolMap={};
      } else {//修改
        let arr = map.joinSchoolMap;//java的map返回到前端后是数组
        let mIds = Object.keys(arr);
        for (let mId of mIds) {
          let joinShools = arr[mId];
          this.appledJoinSchoolMap[mId] = {};
          for (let join of joinShools) {
            this.appledJoinSchoolMap[mId][join.id] = {
              id: join.id,
              org_code: join.org_code,
              org_name: join.org_name
            }
          }
        }
      }

      for(let major of this.appledMajorList) {
        this.selectMajorMap[major.id] = {
          major_code:major.major_code,
          major_name:major.major_name,
          major_score:major.major_score,
          major_level:major.major_level
        };
      }
      this.isHiddenMajorFlag=false;
    //  FrameRequest.requestArray("pl/plMajorApplyDir/dirmajorlist.htm", {year: String(item.year_code).substring(0,4),applyForm: item.apply_form}, (arr)=>{
    //    this.majorList = arr;
    //  });


      //打开编辑
      this.goEdit(this.editTemplateModal,'only','modal-lg',item);
    });
  }

  //进入修改界面，带出最后一个专业显示，避免提交报专业不存在
  async aftGoEditEvent(entity?){
    if (this.appledMajorList.length > 0) {
      this.item.major_id = this.appledMajorList[this.appledMajorList.length - 1].id;
    }
  }

  //覆盖父类
  async save() {
    
    if (!FrameFunction.validForm(this.formModel)) {
      return;
    }

   

    this.majorIds = this.getKeys(this.selectMajorMap);
   //this.majorIds = this.item.major_id;

    if (this.majorIds.length == 0) {
      AppComponent.alert({title:"信息提示",text:"请添加专业!"});
      return;
    }

    if(!this.item.apply_remark){
      this.item.apply_remark = "";
    }
    
    let submitUrl = "";
    this.item.major_id_arr = this.majorIds;
    this.item.RequestLoading = true;
    //this.item.org_id = this.curOrg.id;
   // this.item.school_id = this.curOrg.id;
    //this.item.status = 0;//新建状态
    delete this.item.masterSchool;
    if (!this.item.id) {
      submitUrl = this.ADD_URL;
      delete this.item.id;
      this.item.is_auth_back = 0;//默认没有退回
     // this.item.apply_form = this.curApplyForm;
     // this.item.status=1;
    } else {
      submitUrl = this.EDIT_URL;
    }

    if(!this.item.apply_no){
      this.item.apply_no = "";
    }

    FrameRequest.request(submitUrl, this.item, (ret)=>{
      if (ret.errorCode == 0) {
        this.hideModal();
        this.framePager.reload();
        AppComponent.GobalComponent.successMsg("提交成功");
        //清空
        //this.schoolIds = [];
        this.majorIds = [];
        this.joinSchoolIds = [];
      }
    });
  }

  //获取申报审核基础数据
  getApplyBaseInfo(applyId) {
    FrameRequest.requestMap(this.GET_APPLY_INFO, {id: applyId}, async (map) => {
      this.authList = map.authList;
      this.appledMajorList = map.applyMajorList;
      for(let major of this.appledMajorList) {
        this.selectMajorMap[major.id] = {
          major_code:major.major_code,
          major_name:major.major_name,
          major_score:major.major_score,
          major_level:major.major_level
        };
      }
      this.isHiddenMajorFlag=false;
    });
  }

  //提交申请备案
  submitApply() {
    let arr = this.framePager.getCheckedArray();
    if (arr.length > 0) {
      for (let i=0; i<arr.length; i++) {
        if (arr[i].status != 0) {
          AppComponent.alert({title:"信息提示",text:"只能提交新建状态申请!"});
          return false;
        }
      }
    }
    AppComponent.confirm("确定提交",()=>{
      let checkedArray = [];
      checkedArray = this.framePager.getCheckedArray((item)=>item.id);
      FrameRequest.request("pl/plMajorApply/batchsubmit.htm", {ids:checkedArray.join()}, (ret)=>{
        if (ret.errorCode == 0) {
          this.framePager.reload();
          AppComponent.GobalComponent.successMsg("提交成功!");
        }
      });
    });
  }

  //维护指定专业的专本衔接学校
  showJoinSchoolDialog(templateModal, majorId) {
    this.joinSchoolWin = this.bsModalService.show(templateModal, { class: "modal-lg" });
    //appledJoinSchoolMap--查询当前专业对应的衔接学校列表
    this.currSelectMajorId = majorId;
    let arr = this.appledJoinSchoolMap[majorId];
    if (arr) {//不是数组对象
      /*for (let jo of arr) {
        this.currJoinSchoolMap[jo.id] = {
          id: jo.id,
          org_code: jo.org_code,
          org_name: jo.org_name
        }
      }*/
      this.currJoinSchoolMap = arr;
    } else {
      this.currJoinSchoolMap={};//新选的专业时清空.
    }
  }

  //添加衔接学校
  addMultiJoinSchool() {
    let org = this.getJoinSchool(this.joinQuery.orgId);
    if (!this.appledJoinSchoolMap[this.currSelectMajorId]) {
      this.appledJoinSchoolMap[this.currSelectMajorId] = {};
    }
    this.appledJoinSchoolMap[this.currSelectMajorId][org.id] = {
      id: org.id,
      org_code: org.org_code,
      org_name: org.org_name
    };
    this.currJoinSchoolMap[org.id] = {
      id: org.id,
      org_code: org.org_code,
      org_name: org.org_name
    };
  }

  //列表删除衔接学校
  deleteJoinSchool(orgId) {
    delete this.appledJoinSchoolMap[orgId];
    delete this.currJoinSchoolMap[orgId];
  }

  getJoinSchool(schoolId) {
    for (let school of this.joinSchoolList) {
      if (school.id == schoolId) {
        return school;
      }
    }
    return null;
  }

  hiderJoinModal() {
    this.joinSchoolWin.hide();
    this.joinQuery.orgId = "";//关闭衔接学校维护窗口后清空!
  }

  //下载申报资料
  downloadApplyFile(applyId) {
    FrameRequest.download(this.DOWNLOAD_URL,  { id: applyId });
  }

  
}