import { Component, OnInit, TemplateRef } from '@angular/core';
import { FlexTableComponent } from '../../../../shared/common/FlexTable.component';
import { FormBuilder, Validators } from '@angular/forms';
import { FrameRequest } from '../../../../shared/frame/frame-request';
import { AppComponent } from '../../../../app.component';
import { BsModalService } from 'ngx-bootstrap/modal';
import { t } from '@angular/core/src/render3';

@Component({
  selector: 'app-pl-major-apply-dir',
  templateUrl: './pl-major-apply-dir.component.html',
  styleUrls: ['./pl-major-apply-dir.component.scss']
})
export class PlMajorApplyDirComponent extends FlexTableComponent implements OnInit {
  public query = {
    query: "",
    status: "",
    start_exam_type: "",
    year: "",
    apply_form: ""
  };
  majorList = [];
  schoolList = [];
  majorIds = [];
  schoolIds = [];
  schoolOther = [];
  yearArray = [];
  chooseMajorList = [];//根据开考类型选择专业
  dirId: number;
  year_code: number;
  major_year: number;//专业同步年度
  allMajorList = []; //所有的开考专业·
  schoolId;

  school = true;
  majorFlag = true;
  schoolFlag = true;
  schoolChooseFlag = true;

  schoolModalWin: any;

  QUERY_URL = "pl/plMajorApplyDir/page.htm";
  MAJOR_URL = "pl/plMajor/listNewOld.htm?is_new_major=1";
  MAJOR_FIND_URL = "pl/plMajor/findMajor.htm";
  SCHOOL_URL = "cf/cfOrganization/list.htm?org_type=1";
  SCHOOL_FIND_URL = "cf/cfOrganization/get.htm";
  SCHOOL_LIST_URL = "pl/plMajorApplyDir/getSchool.htm";
  DELETE_SCHOOL_URL = "pl/plMajorApplyDir/deleteSchool.htm";
  ADD_URL = "pl/plMajorApplyDir/add.htm";
  DELETE_URL = "pl/plMajorApplyDir/delete.htm";
  YEAR_URL = "pl/plYearCode/listYear.htm";
  PUBLISH_URL = "pl/plMajorApplyDir/publish.htm";
  MAJOR_TYPE_URL = "pl/plMajor/listMajorByType.htm";
  MAJOR_SYNC_URL = "pl/plMajorApplyDir/majorSync.htm";
  APPLY_DIR_DETAIL_URL = "pl/plMajorApplyDir/addDetail.htm";
  CURRENT_YEAR_URL = "pl/plYearCode/getCurrentYear.htm";


  constructor(public bsModalService: BsModalService) {
    super();
    const fb = new FormBuilder();
    this.formModel = fb.group({
      start_exam_type: ["", Validators.required],
      year_code: ["", Validators.required]
    });
  }

  ngOnInit() {
    FrameRequest.requestArray(this.YEAR_URL, {}, (array) => {
      this.yearArray = array;
    });
    FrameRequest.requestArray(this.MAJOR_URL, {}, (array) => {
      this.allMajorList = array;
    });
    FrameRequest.requestEntity(this.CURRENT_YEAR_URL, {}, (entity) => {
     if(entity) {
       this.query.year = entity;
       this.framePager.reload();
     }
    });
  }

  search(param) {
    param.query = this.query.query;
    param.status = this.query.status;
    param.start_exam_type = this.query.start_exam_type;
    param.year = this.query.year;
    param.apply_form = this.query.apply_form;
  }

  addMajor() {
    if (this.item.major_id) {
      FrameRequest.requestEntity(this.MAJOR_FIND_URL, { id: this.item.major_id }, (entity) => {
        this.majorIds = this.majorList.map((major) => major.id);
        if (!this.contains(this.majorIds, entity.id)) {
          this.majorList.push(entity);
        }
        this.majorFlag = false;
      });
    }
  }

  showSchool() {
    if (!this.school) {
      this.schoolFlag = false;
    } else {
      this.schoolFlag = true;
      this.schoolChooseFlag = true;
    }
  }

  addSchool() {
    FrameRequest.requestEntity(this.SCHOOL_FIND_URL, { id: this.item.school_id }, (entity) => {
      this.schoolIds = this.schoolList.map((school) => school.id);
      if (!this.contains(this.schoolIds, entity.id)) {
        this.schoolList.push(entity);
      }
      this.schoolChooseFlag = false;
    });
  }

  deleteElement(id: number, flag: string) {
    if (flag === 'major') {
      this.majorList.splice(this.majorList.findIndex(major => major.id === id), 1);
    } else {
      this.schoolList.splice(this.schoolList.findIndex(school => school.id === id), 1);
    }
  }

  async save() {
    this.schoolIds = [];
    this.majorIds = [];
    if (!this.nullJudge()) return;
    if (this.school) {//全部学校
      this.item.school_scope = 0;
    } else {//部分学校
      this.item.school_scope = 1;
      this.schoolIds = this.schoolList.map((school) => school.id);
    }
    this.majorIds = this.majorList.map((major) => major.id);
    // AppComponent.GobalComponent.setLoading(true);
    FrameRequest.request(this.ADD_URL, {
      major_ids: this.majorIds.join(),
      apply_form: this.item.apply_form,
      school_scope: this.item.school_scope,
      school_ids: this.schoolIds.join(),
      year: this.query.year
    }, () => {
      // AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("保存成功");
      this.hideModal();
      this.majorList = [];
      this.schoolList = [];
      this.majorFlag = true;
      this.schoolFlag = true;
      this.schoolChooseFlag = true;
      this.school = true;
      this.framePager.reload();

    })

  }

  deleteDir() {
    if (!this.deleteJudge()) return;
    let ids = this.framePager.getCheckedArray(item => item.id);
    AppComponent.confirm("确定删除", () => {
      FrameRequest.request(this.DELETE_URL, { ids: ids.join() }, () => {
        AppComponent.GobalComponent.successMsg("删除成功");
        this.framePager.reload();
      });
    });
  }

  goSchool(showType: string, dirId: number) {
    this.editShowType = showType;
    this.dirId = dirId;
    this.reloadSchool(dirId);
  }

  deleteSchool(schoolId: number) {
    FrameRequest.request(this.DELETE_SCHOOL_URL, { dir_id: this.dirId, school_id: schoolId }, () => {
      AppComponent.GobalComponent.successMsg("删除成功");
      this.reloadSchool(this.dirId);
    });
  }

  reloadSchool(dirId: number) {
    FrameRequest.requestArray(this.SCHOOL_LIST_URL, { dir_id: dirId }, (arrary) => {
      this.schoolOther = arrary;
    });
  }

  //去发布页面
  goPublish(template: TemplateRef<any>, modalcss?) {
    let css = modalcss ? modalcss : "modal-lg";
    this.bsModalWin = this.bsModalService.show(template, { class: css });
  }

  //发布
  publish() {
    FrameRequest.request(this.PUBLISH_URL, { year_code: this.year_code }, () => {
      AppComponent.GobalComponent.successMsg("发布成功");
      this.hideModal();
      this.framePager.reload();
    });
  }

  //根据开考类型-选择专业
  chooseMajor(exam_start_type: any) {
    FrameRequest.requestArray(this.MAJOR_TYPE_URL, { exam_start_type: exam_start_type }, (array) => {
      this.chooseMajorList = array;
    });
  }

  //专业同步
  majorSync() {
    // if (!this.major_year) {
    //   AppComponent.alert({ 'title': '提示', text: '请选择同步专业的年度码' });
    //   return;
    // }
    if(!this.query.apply_form) {
      AppComponent.alert({ 'title': '提示', text: '请选择申报形式' });
      return;
    }

    if(!this.query.year) {
      AppComponent.alert({ 'title': '提示', text: '请选择申报批次' });
      return;
    }

    AppComponent.confirm("确定将开考的专业同步到"+this.query.year+"专业申报目录吗?",()=>{

      AppComponent.GobalComponent.setLoading(true);
      FrameRequest.request(this.MAJOR_SYNC_URL, { apply_form: this.query.apply_form,year:this.query.year }, () => {
        AppComponent.GobalComponent.setLoading(false);
        AppComponent.GobalComponent.successMsg("同步成功");
        this.framePager.reload();
      });

    });

   
  }

  deleteJudge() {
    let checkArray = this.framePager.getCheckedArray(item => item.id);
    if (!checkArray || checkArray.length === 0) {
      AppComponent.alert({ 'title': '提示', text: '请选择至少一条记录' });
      return false;
    }
    let arrary = this.framePager.getCheckedArray();
    for (let i = 0; i < arrary.length; i++) {
      if (arrary[i].status === 1) {
        AppComponent.alert({ 'title': '提示', text: '已发布的专业不能删除' });
        return false;
      }
    }
    return true;
  }

  nullJudge() {
    if (!this.item.apply_form) {
      AppComponent.alert({ 'title': '提示', text: '请选择开考类型' });
      return false;
    }
    if (this.majorList.length === 0) {
      AppComponent.alert({ 'title': '提示', text: '请选择专业' });
      return false;
    }
    if (!this.school && this.schoolList.length === 0) {
      AppComponent.alert({ 'title': '提示', text: '请选择主考学校' });
      return false;
    }
    return true;
  }

  contains(ids: any, id: number) {
    for (let i = 0; i < ids.length; i++) {
      if (ids[i] == id) return true;
    }
    return false;
  }

  // 新增专业对应院校
  saveApplySchool() {
    FrameRequest.request(this.APPLY_DIR_DETAIL_URL, {dir_id: this.dirId, school_id: this.schoolId} ,() => {
      AppComponent.GobalComponent.successMsg('新增成功');
      this.hideSchoolModal();
      this.reloadSchool(this.dirId);
    });
  }

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

  hideSchoolModal() {
    if(this.schoolModalWin) this.schoolModalWin.hide();
  }

}
