import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { BsModalService } from "ngx-bootstrap/modal";
import { FlexTableComponent } from '../../../../shared/common/FlexTable.component';
import { FrameRequest } from '../../../../shared/frame/frame-request';
import { AppComponent } from '../../../../app.component';
import { FramePagerComponent } from '../../../../core/pager/pager.component';
import { CustomValidators } from 'ng2-validation';
import * as _ from 'lodash';
import { Router } from '@angular/router';

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

  public query = {
    "query": "",
    "nation_exam": "",
    "course_id": "",
    "exam_time_id": "",
    "special_flag": "",
    "course_filter" : "",
    "status" : "",
    "is_net_mark":""
  };
  QUERY_URL = "pl/plCoursePre/page.htm";
  DELETE_URL = "pl/plCoursePre/delete.htm";
  GET_URL = "pl/plCoursePre/get.htm";
  ADD_URL = "pl/plCoursePre/add.htm";
  EDIT_URL = "pl/plCoursePre/edit.htm";
  OPEN_URL = "pl/plCoursePre/status.htm";
  DETAIL_URL = "pl/plCoursePre/detail.htm";
  EXAM_TIME_URL = "pl/plExamTime/listtime.htm";
  EXAM_AREA_URL = "cf/cfOrganization/list.htm?org_type=4&status=1";//考区
  SCHOOL_FIND_URL = "cf/cfOrganization/get.htm";
  EXAM_QUERY_URL = "pl/plExamAreaCourse/page.htm";
  EXAM_ADD_URL = "pl/plExamAreaCourse/add.htm";
  EXAM_DELETE_URL = "pl/plExamAreaCourse/delete.htm";
  TEXTBOOK_LOG_URL = "pl/plCourse/ctbookLog.htm";

  EXAM_LIMIT_QUERY_URL = "pl/plExamAreaCourseLimit/page.htm"; //课程限制考区列表
  EXAM_LIMIT_ADD_URL = "pl/plExamAreaCourseLimit/add.htm"; //课程限制保存
  EXAM_LIMIT_DELETE_URL = "pl/plExamAreaCourseLimit/delete.htm"; //删除课程限制
  SOCIAL_ENROL_URL = "pl/plCoursePre/editsocial.htm"; //社会考生限制
  FEE_LIST_URL = "cf/cfFeeScale/list.htm";


  course = [];
  examAreaIds = [];
  courseIds = [];
  items: any;
  majorList: any;
  examAreaList = [];//已选择考区
  examAreaFlag = true;//考区是否显示
  examAreaChooseFlag = true;//已选择的考区
  ctBookLog = [];
  is_social_enrol;
  feeList = [];

  @ViewChild('framePager2')
  framePager2: FramePagerComponent; //课程指定分页
  @ViewChild('framePager3')
  framePager3: FramePagerComponent; //课程限制分页

  constructor(
    public bsModalService: BsModalService,
    private router: Router,
    fb: FormBuilder
  ) {
    super();
    this.formModel = fb.group({
      id: [null],
      'course_code': [null, Validators.compose([Validators.required, Validators.pattern("^[a-zA-Z0-9]+$")])],
      'course_name': [null, Validators.compose([Validators.required])],
      //'course_standard_code': [null, Validators.pattern("^[a-zA-Z0-9 ]+$")],
      'course_score': [null, Validators.compose([Validators.required])],
      'course_exam_type': [null, null],
      'is_nation_exam': [null, Validators.compose([Validators.required])],
      'status': [null],
      'special_flag': [null, Validators.compose([Validators.required])],
      'remark': [null, null],
      'is_net_mark': [null, Validators.required],
      'course_type': [null],
      'fee_code': [null, Validators.required]
    });
  }

  ngOnInit() {
    this.items = {};
    FrameRequest.requestArray(this.FEE_LIST_URL, {}, (array) => {
      this.feeList = array;
    });
  }

  /**
   * 开考和停考
   */
  open(flag) {
    let checkedArray = this.framePager.getCheckedArray((item) => item.id);
    if (checkedArray.length === 0) {
      AppComponent.alert({ title: "信息提示", text: "请选择数据!" });
      return;
    }
    FrameRequest.request(this.OPEN_URL, { ids: checkedArray.join(), flag: flag }, () => {
      if (flag === 0) {
        AppComponent.GobalComponent.successMsg('课程停考成功');
      } else {
        AppComponent.GobalComponent.successMsg('课程开考成功');
      }
      this.framePager.reload();
    });
  }

  /**
   * 课程详情
   */
  goDetail(template: TemplateRef<any>, modalClass, item?) {
    this.bsModalWin = this.bsModalService.show(template, { class: modalClass });
    FrameRequest.requestMap(this.DETAIL_URL, { id: item.id }, (map) => {
      this.course = map['course'];
      this.majorList = map['majorList'];
    });
  }

  //课程考区指定界面
  goCourseExamArea() {
    this.courseIds = [];
    this.courseIds = this.framePager.getCheckedArray(item => item.id);
    if (!this.courseIds || this.courseIds.length === 0 || this.courseIds.length > 1) {
      AppComponent.alert({ title: "信息提示", text: "请选择一门课程!" });
      return;
    }
    this.query.query = "";
    this.editShowType = 'examArea';
  }

  //分页查询考区课程信息
  search(param) {
    if (this.query.exam_time_id === null) {
      this.query.exam_time_id = '';
    }
    if (this.query.nation_exam === null) {
      this.query.nation_exam = '';
    }
    if (this.query.special_flag === null) {
      this.query.special_flag = '';
    }
    if (this.query.course_filter === null) {
      this.query.course_filter = '';
    }
    if (this.query.status === null) {
      this.query.status = '';
    }
    if (this.query.is_net_mark === null) {
      this.query.is_net_mark = '';
    }

    let searchCondition = this.query;
    _.assignIn(param, searchCondition);
    param.course_id = this.courseIds.join();
  }


  //将考区增加到列表中
  addExamArea() {
    FrameRequest.requestEntity(this.SCHOOL_FIND_URL, { id: this.items.exam_area_id }, (entity) => {
      this.examAreaIds = this.examAreaList.map((examArea) => examArea.id);
      if (!this.contains(this.examAreaIds, entity.id)) {
        this.examAreaList.push(entity);
      }
      this.examAreaChooseFlag = false;
    });
  }
  //从考区列表中移除考区
  deleteElement(id: number, flag?: string) {
    this.examAreaList.splice(this.examAreaList.findIndex(examArea => examArea.id === id), 1);
  }


  //保存考区课程关系
  saveExamArea() {
    if (!this.nullJudge()) return;
    let exam_ids = this.examAreaList.map(item => item.id);
    FrameRequest.request(this.EXAM_ADD_URL, {
      course_id: this.courseIds.join(), exam_time_id: this.items.exam_time_id, exam_ids: exam_ids.join()
    }, () => {
      AppComponent.GobalComponent.successMsg("考区设置成功");
      this.framePager2.reload();
      this.examAreaList = [];
      this.examAreaChooseFlag = true;
      this.items.exam_time_id = "";
      this.items.exam_area_id = "";
    });
    // if (this.examArea) {//全部考区
    //   AppComponent.GobalComponent.successMsg("考区设置成功");
    // } else { //部分考区
    // }
  }

  //删除考区课程关系
  deleteExamArea(id: number) {
    FrameRequest.request(this.EXAM_DELETE_URL, { ids: id }, () => {
      AppComponent.GobalComponent.successMsg("删除成功");
      this.framePager2.reload();
    })
  }


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

  nullJudge() {
    if (!this.items.exam_time_id) {
      AppComponent.alert({ 'title': '提示', text: '请选择考试时间' });
      return false;
    }
    if (this.examAreaList.length === 0) {
      AppComponent.alert({ 'title': '提示', text: '请选择考区' });
      return false;
    }
    return true;
  }

  //跳转到专业模块
  navigateMajor(major_code: any, year_code: any) {
    this.hideModal();
    this.router.navigate(['/hmsoft/pl/major'], {
      queryParams: {
        major_code: major_code,
        year_code: year_code
      }
    });
  }


  /**
   * 课程详情
   */
  goTextbookLog(template: TemplateRef<any>, modalClass, item?) {
    this.bsModalWin = this.bsModalService.show(template, { class: modalClass });
    FrameRequest.requestArray(this.TEXTBOOK_LOG_URL, { course_id: item.id }, (array) => {
      this.ctBookLog = array;
    });
  }

  //课程限制
  goCourseExamAreaLimit() {
    this.courseIds = [];
    this.courseIds = this.framePager.getCheckedArray(item => item.id);
    if (!this.courseIds || this.courseIds.length === 0 || this.courseIds.length > 1) {
      AppComponent.alert({ title: "信息提示", text: "请选择一门课程!" });
      return;
    }
    this.query.query = "";
    this.editShowType = 'examAreaLimit';
  }

  //保存课程限制
  saveExamAreaLimit() {
    if (!this.nullJudge()) return;
    let exam_ids = this.examAreaList.map(item => item.id);
    FrameRequest.request(this.EXAM_LIMIT_ADD_URL, {
      course_id: this.courseIds.join(), exam_time_id: this.items.exam_time_id, exam_ids: exam_ids.join()
    }, () => {
      AppComponent.GobalComponent.successMsg("考区限制设置成功");
      this.framePager3.reload();
      this.examAreaList = [];
      this.examAreaChooseFlag = true;
      this.items.exam_time_id = "";
      this.items.exam_area_id = "";
      this.query.exam_time_id = "";
    });
  }

  //删除考区课程限制
  deleteExamAreaLimit(id: number) {
    FrameRequest.request(this.EXAM_LIMIT_DELETE_URL, { ids: id }, () => {
      AppComponent.GobalComponent.successMsg("删除成功");
      this.framePager3.reload();
    })
  }

  //社会考生课程限制
  goSocialEnrol() {
    this.courseIds = [];
    this.courseIds = this.framePager.getCheckedArray(item => item.id);
    if (!this.courseIds || this.courseIds.length === 0 ) {
      AppComponent.alert({ title: "信息提示", text: "请选择至少一门课程!" });
      return;
    }
    FrameRequest.requestEntity(this.GET_URL, {id: this.courseIds[0]}, (entity) => {
        if(entity && entity.is_social_enrol != undefined) {
          this.is_social_enrol = entity.is_social_enrol;
        }
    });
    this.query.query = "";
    this.editShowType = 'socialEnrol';
  }

  // 保存社会考生课程限制
  saveSocialEnrol() {
    if(this.is_social_enrol === ' ' || this.is_social_enrol === undefined)  {
      AppComponent.alert({ title: "信息提示", text: "请选择是否允许社会考生报考!" });
      return;
    }
    FrameRequest.request(this.SOCIAL_ENROL_URL, {  
      course_ids: this.courseIds.join(), 
      is_social_enrol : this.is_social_enrol  }, () => {
      AppComponent.GobalComponent.successMsg("设置成功");
      this.hideModal();
      this.framePager.reload();
    });
  }

  downXls() {
    let param = {
      query: this.query.query,
      nation_exam: this.query.nation_exam,
      special_flag : this.query.special_flag,
      course_filter:this.query.course_filter,
      status:this.query.status,
      is_net_mark:this.query.is_net_mark
  };
  AppComponent.GobalComponent.setLoading(true);
  FrameRequest.download("pl/plCourse/downxls.htm", param, ()=>{
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("导出成功!");
  });
  }

  //考区(停用)
  // showExamArea() {
  //   if (!this.examArea) {
  //     this.examAreaFlag = false;
  //   } else {
  //     this.examAreaFlag = true;
  //     this.examAreaChooseFlag = true;
  //   }
  // }
}
