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

@Component({
  selector: 'app-by-course-repl-detail-pre',
  templateUrl: './by-course-repl-detail-pre.component.html',
  styleUrls: ['./by-course-repl-detail-pre.component.scss']
})
export class ByCourseReplDetailPreComponent extends FlexTableComponent implements OnInit {

  public query = {
    query: "",
    mcName: "",
    oldName: "",
    major_id : "",
    old_course_id: "",
    repl_course_id : ""
  };
  QUERY_URL = "by/byCourseReplDetailPre/page.htm";
  ADD_URL = "by/byCourseReplDetailPre/add.htm";
  DELETE_URL = "by/byCourseReplDetailPre/delete.htm";
  GET_URL = "by/byCourseReplDetailPre/get.htm";
  EDIT_URL = "by/byCourseReplDetailPre/edit.htm";
  DETAIL_URL = "by/byCourseReplDetailPre/detail.htm";
  MAJOR_URL = "pl/plMajorPre/list.htm";
  COURSE_MAJOR_URL = "pl/plMajorPre/listMajor.htm ";
  RULE_LIST_URL = "by/byCourseReplRule/list.htm";
  DOWN_LOAD_URL = "by/byCourseReplDetailPre/export.htm";
  COURSE_LIST_URL = "pl/plCoursePre/listAll.htm";

  private major_id: any;
  private hasList = []; //已关联的顶替规则
  private mcList = []; //专业课程
  private oldList = []; //老专业课程
  private major: any; //专业信息
  private mcArray = []; //选择的专业课程
  private oldArray = []; //选择的老课程
  private replDetail: any;
  private replyRuleList = []; //根据选择的课程过滤的规则
  private majorList = []; //使用的专业列表
  private majorChooseFlag = true;
  private mcTempList = [];//专业课程中间变量
  private oldTempList = []; //老课程中间变量
  allMajorList = [];
  allCourseList = []; //所有的课程

  constructor(public bsModalService: BsModalService, fb: FormBuilder) {
    super();
    this.formModel = fb.group({
      major_id: [null, Validators.required]
    });
  }

  ngOnInit() {
    this.major = {};
    this.replDetail = {};
    FrameRequest.requestArray(this.MAJOR_URL, {}, (array) => {
      this.allMajorList = array;
    });
    FrameRequest.requestArray(this.COURSE_LIST_URL, {}, (array) => {
      this.allCourseList = array;
    });

    this.loadOldCourseData(null);
  }


  showEdit(template: TemplateRef<any>, editShowType) {
    this.hideModal();
    this.loadData();
    if(this.replDetail){
      this.replDetail.is_all='0';
    }
    this.editShowType = editShowType;
  }

  //加载数据
  loadData() {
    FrameRequest.requestMap(this.DETAIL_URL, { major_id: this.major_id }, (map) => {
      this.major = map['major'];
      this.hasList = map['hasList'];
      this.mcList = map['mcList'];
      this.mcTempList = map['mcList'];
    });
  }

 //加载老课程数据
 loadOldCourseData(oldName) {
   if(null == oldName){
     oldName = '';
   }
   
  FrameRequest.requestMap("by/byCourseReplDetailPre/loadOldCourse.htm", {name:oldName}, (map) => {
    this.oldList = map['oldList'];
    this.oldTempList = map['oldList'];
  });
} 

  chooseMajor() {
    //根据选择的课程数目，查询适用的规则
    if (this.oldArray && this.oldArray.length > 0 && this.mcArray && this.mcArray.length > 0) {
      FrameRequest.requestArray(this.RULE_LIST_URL,
        { old_num: this.oldArray.length, repl_num: this.mcArray.length }, (array) => {
          this.replyRuleList = array;
          this.replDetail.rule_id=this.replyRuleList[0].id;
        });
    }
    //适用全部专业
    if (this.replDetail.is_all == 1) {
      if (this.mcArray && this.mcArray.length > 0) {
        this.majorChooseFlag = false;
        FrameRequest.requestArray(this.COURSE_MAJOR_URL,
          {
            course_ids: this.getIds(this.mcArray, 'mc').join(),
            major_id: this.major_id
          }, (array) => {
            this.majorList = array;
          });
      }

    } else {
      this.majorChooseFlag = true;
    }
  }

  //mc:专业课程
  getIds(array: any, flag: any) {
    let ids = [];
    for (let i = 0; i < array.length; i++) {
      if (flag === 'mc') {
        ids.push(array[i]['course_id']);
      } else {
        ids.push(array[i]['id']);
      }
    }
    return ids;
  }

  deleteMajor(major_id: number) {
    this.majorList.splice(this.majorList.findIndex(major => major.id === major_id), 1);
  }

  //保存
  saveReplyDetail() {
    if (!this.checkNull()) return;
    FrameRequest.request(this.ADD_URL, {
      major_id: this.major_id,
      rule_id: this.replDetail.rule_id,
      is_all: this.replDetail.is_all,
      remark: this.replDetail.remark,
      old_course_ids: this.getIds(this.oldArray, 'course').join(),
      repl_course_ids: this.getIds(this.mcArray, 'mc').join(),
      major_ids: this.getIds(this.majorList, 'major').join()
    }, () => {
      AppComponent.GobalComponent.successMsg("保存成功");
      //this.hideModal();
      //this.framePager.reload();
      this.loadData();
      this.mcArray = [];
      this.oldArray = [];
      this.replyRuleList = [];
      this.majorChooseFlag = true;
      if(this.replDetail){
        this.replDetail.is_all='0';
      }

    });
  }

  hideReplyDetailModal(){
    this.hideModal();
    this.framePager.reload();
  }

  //过滤课程
  getCourse(keyword: string, flag: number) {
    // 根据查询条件重新加载老课程信息
    this.loadOldCourseData(keyword);

    let tempArr = [];
    tempArr = (flag === 0) ? this.mcTempList : this.oldTempList;
    if (!keyword) {
      (flag === 0) ? (this.mcList = this.mcTempList) : (this.oldList = this.oldTempList);
    } else {
      let arr = [];
      for (let i = 0; i < tempArr.length; i++) {
        if (tempArr[i]["course_code"].indexOf(keyword) >= 0
          || tempArr[i]['course_name'].indexOf(keyword) >= 0) {
          arr.push(tempArr[i]);
        }
      }
      (flag === 0) ? (this.mcList = arr) : (this.oldList = arr);
    }
  }


  checkNull(): boolean {
    if (!this.mcArray || this.mcArray.length === 0) {
      AppComponent.alert({ title: '提示', text: '请选择专业课程！' });
      return false;
    }
    if (!this.oldArray || this.oldArray.length === 0) {
      AppComponent.alert({ title: '提示', text: '请选择顶替课程！' });
      return false;
    }
    if (this.replDetail.is_all === undefined || this.replDetail.is_all === '') {
      AppComponent.alert({ title: '提示', text: '请选择是否适用全部专业！' });
      return false;
    }
    if (!this.replDetail.rule_id) {
      AppComponent.alert({ title: '提示', text: '请选择顶替规则！' });
      return false;
    }
    return true;
  }

  moveRight(flag: number) {
    let selectedArray = [];
    let unselectedArray = [];
    let list = [];
    if (flag === 0) {
      list = this.mcList;
    } else {
      list = this.oldList;
    }
    for (let index = 0; index < list.length; index++) {
      let item = list[index];
      if (item.selected === true) {
        item.selected = false;
        selectedArray.push(item);
      } else {
        unselectedArray.push(item);
      }
    }
    if (flag == 0) {
      this.mcList = unselectedArray;
      this.mcTempList = this.remove(this.mcTempList, selectedArray);
      this.mcArray = this.mcArray.concat(selectedArray);
    } else {
      this.oldList = unselectedArray;
      this.oldTempList = this.remove(this.oldTempList, selectedArray);
      this.oldArray = this.oldArray.concat(selectedArray);
    }

    this.chooseMajor();

  }

  //数组中添加元素
  add(mcTempList: any[], selectedArray: any[]): any[] {
    for (let i = 0; i < selectedArray.length; i++) {
      mcTempList.push(selectedArray[i]);
    }
    return mcTempList;
  }

  //数组中移除元素
  remove(oldTempList: any[], selectedArray: any[]) {
    for (let i = 0; i < selectedArray.length; i++) {
      oldTempList.splice(oldTempList.findIndex(item => item.id === selectedArray[i]['id']), 1);
    }
    return oldTempList;
  }
  
  moveLeft(flag: number) {
    let selectedArray = [];
    let unselectedArray = [];
    let array = [];
    if (flag === 0) {
      array = this.mcArray;
    } else {
      array = this.oldArray;
    }
    for (let index = 0; index < array.length; index++) {
      let item = array[index];
      if (item.selected === true) {
        item.selected = false;
        selectedArray.push(item);
      } else {
        unselectedArray.push(item);
      }
    }
    if (flag === 0) {
      this.mcArray = unselectedArray;
      this.mcList = this.mcList.concat(selectedArray);
      this.mcTempList = this.add(this.mcTempList, selectedArray);
    } else {
      this.oldArray = unselectedArray;
      this.oldList = this.oldList.concat(selectedArray);
      this.oldTempList = this.add(this.oldTempList, selectedArray);
    }

    this.chooseMajor();
  }

  //导出
  export() {
    FrameRequest.download(this.DOWN_LOAD_URL, {RequestLoading: true});
  }

  keyChange(event,keyword: string, flag: number) {
    let keycode = window.event ? event.keyCode : event.which;
    if(keycode == 13){//回车键
      this.getCourse(keyword, flag);
    }
  }

}
