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 {FrameFunction} from '../../../../shared/frame/frame_function';
import { FrameRequest } from "../../../../shared/frame/frame-request";
import { FramePagerComponent } from "../../../../core/pager/pager.component";

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


  yearCodeList = [];
  schoolList = [];//下拉框数据源
  selectedSchoolMap = {};//已添加的学校MAP对象
  isAllSchool = true;//默认勾选
  isShowShoolAdd = true;//默认隐藏 添加学校框
  isHiddenSchoolFlag = true;
  schoolDetailList = [];
  applyTimeId : any;//弹框查看申报时间ID

  @ViewChild('framePager')
  framePager:FramePagerComponent;

  QUERY_URL="pl/majorApplyTime/page.htm";
  GET_URL = "pl/majorApplyTime/get.htm";  
  ADD_URL = "pl/majorApplyTime/add.htm";  
  EDIT_URL = "pl/majorApplyTime/edit.htm";
  DELETE_URL = "pl/majorApplyTime/delete.htm";
  SCHOOL_FIND_URL = "cf/cfOrganization/get.htm";
  SCHOOL_DETAIL_URL = "pl/majorApplyTime/detaillist.htm";
  DELETE_DETAIL_URL= "pl/plMajorApplyTimeDetail/delete.htm";

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

  ngOnInit() {
    this.initSchoolList();
  }

  public query = {
    applyForm: "",
    yearCode: "",
    query: ""
  };

  search(param){
    param.applyForm=this.query.applyForm;
    param.applyForm=this.query.applyForm;
    param.yearCode = this.query.yearCode;
    param.query=this.query.query;
  }

  initSchoolList(){
    FrameRequest.requestArray("cf/cfOrganization/list.htm",{org_type:1,status:1},(arr)=>{
      this.schoolList = arr;
    });
    //年度码
    FrameRequest.requestArray("pl/plYearCode/list.htm", {}, (array) => {
      this.yearCodeList = array;
    });
  }

  checkChange() {
    if (!this.isAllSchool) {
      this.isShowShoolAdd = false;
      this.isHiddenSchoolFlag = false;
    } else {
      this.isShowShoolAdd = true;
      this.isHiddenSchoolFlag = true;
    }
  }

  addSchool() {
    FrameRequest.requestEntity(this.SCHOOL_FIND_URL, { id: this.item.school_id }, (entity) => {
      this.selectedSchoolMap[entity.id]={org_name:entity.org_name,org_code:entity.org_code};
      this.isHiddenSchoolFlag = false;
    });

  }

  deleteElement(id: number) {
    delete this.selectedSchoolMap[id];
    if (this.getKeys(this.selectedSchoolMap).length == 0) {//删除完后隐藏
      this.isHiddenSchoolFlag = true;
    }
  }

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

  //覆盖父类保存方法
  async save() {
    if (!FrameFunction.validForm(this.formModel)) {
      return;
    }
    let schoolIdArr = [];
    if (this.isAllSchool) {
      this.item.school_scope = 0;//所有学校
      schoolIdArr = this.schoolList.map((school)=>school.id);
    } else {
      this.item.school_scope = 1;//部分学校
      schoolIdArr = this.getKeys(this.selectedSchoolMap);
    }
    let param = {
      school_scope:this.item.school_scope,
      apply_form: this.item.apply_form,
      year_code: this.item.year_code,
      apply_start_time: this.item.apply_start_time,
      apply_end_time: this.item.apply_end_time,
      schoolIds: schoolIdArr,
      RequestLoading:true
    };
    let url = "";
    if (!this.item.id) {
      url = this.ADD_URL;
    } else {
      url = this.EDIT_URL;
      param["id"] = this.item.id;
    }
    FrameRequest.request(url, param, (ret)=>{
      if (ret.errorCode == 0) {
        this.hideModal();
        this.framePager.reload();
        AppComponent.GobalComponent.successMsg('保存成功');
      }
    });
  }
  //查看明细学校
  goSchoolDetailList(applyTimeId) {
    this.editShowType = "schoolDetailList";
    this.applyTimeId = applyTimeId;
    FrameRequest.requestArray(this.SCHOOL_DETAIL_URL, { id: applyTimeId,  RequestLoading:true}, (arr) => {
      this.schoolDetailList = arr;
    });
  }

  //删除详情学校
  deleteSchool(detailId) {
    FrameRequest.request(this.DELETE_DETAIL_URL, {ids:detailId}, (ret)=>{
      if (ret.errorCode == 0) {
        AppComponent.GobalComponent.successMsg("删除成功");
        this.reloadDetail();
      }
    });
  }

  reloadDetail() {
    FrameRequest.requestArray(this.SCHOOL_DETAIL_URL, { id: this.applyTimeId,  RequestLoading:true}, (arr) => {
      this.schoolDetailList = arr;
    });
  }

}