import { Component, OnInit, TemplateRef, ViewChild } from "@angular/core";
import { FormBuilder, Validators,FormGroup} 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 { FrameRequest } from "../../../../../shared/frame/frame-request";
import { FramePagerComponent } from "../../../../../core/pager/pager.component";
import { FrameFunction} from '../../../../../shared/frame/frame_function';
import * as _ from 'lodash';

@Component({
  selector: "app-pl-publishplan",
  templateUrl: "./publish-plan-main.component.html",
  styleUrls: ["./publish-plan-main.component.scss"]
})
export class PublishPlanMainComponent extends FlexTableComponent
  implements OnInit {
    
  @ViewChild('framePager')
  framePager:FramePagerComponent;

  @ViewChild('detailPager')
  detailPager:FramePagerComponent;

  @ViewChild('courseVfPager')
  courseVfPager:FramePagerComponent;

  @ViewChild('verifyModal')
  verifyModal: TemplateRef<any>

  s_vf_exam_time_id : any;//校验选择的当前源计划的时间ID
  mainId : number;//主记录ID
  mainStatus : number;//主记录状态
  mainExamTimeId : number;
  //courseList = [];
  yearList = [];
  examTimeList = [];
  pageLevel = "main";//标识 主列表 和 计划详情列表切换
  public courseFormModel: FormGroup;//自定义课程表单验证元素
  //showBtn = "pubfirst";
  //TODO
  QUERY_URL="pl/plPublishPlanMain/page.htm";
  PUBLISH_URL = "pl/plPublishPlanMain/publish.htm";
  GET_URL = "pl/plPublishPlanMain/get.htm";  //获取从省考表
  ADD_URL = "pl/plPublishPlanMain/add.htm";  //添加都是保存到省考
  EDIT_URL = "pl/plPublishPlanMain/edit.htm";//编辑都是保存到省考
  DELETE_URL = "pl/plPublishPlanMain/delete.htm";

  QUERY_DETAIL_URL = "pl/mergePublishPlan/page.htm";//同步查询指定批次对应的国考 省考课程结合集
  DETAIL_SYNCHRONIZE_URL = "pl/mergePublishPlan/synchronize.htm";//同步

  ADD_DETAIL_URL = "pl/mergePublishPlan/add.htm";
  EDIT_DETAIL_URL = "pl/mergePublishPlan/edit.htm";
  DELETE_DETAIL_URL = "pl/mergePublishPlan/delete.htm";

  COURSE_VERIFY_URL = "pl/mergePublishPlan/courseVfQuery.htm";//课程校验查询
  COURSE_VERIFY_ADD_URL = "pl/mergePublishPlan/addFromCompare.htm";//课程校验-调整-添加到当前计划
  COURSE_VERIFY_SYN_URL = "pl/mergePublishPlan/synFromCompare.htm";//课程校验-调整-同步
  COURSE_VERIFY_DEL_URL = "pl/mergePublishPlan/delFromCurPlan.htm";//课程校验-调整-从当前计划删除

  constructor(public bsModalService: BsModalService, fb: FormBuilder) {
    super();
    // CustomValidators.rangeLength([1, 6])
    //计划批次添加的
    this.formModel = fb.group({
      id: [null],
      'exam_time_id': [null, Validators.compose([Validators.required])],
      'pub_batch_name': [null, Validators.compose([Validators.required])]
    });
    //课程添加的
    this.courseFormModel = fb.group({
      id: [null],
      'exam_time': [null, Validators.compose([Validators.required])],
      'course_name': [null, Validators.compose([Validators.required])],
      'course_id': [null],
      'score': [null],
      'is_nation_exam': [null, Validators.compose([Validators.required])],
     // 'start_time': [null, Validators.compose([Validators.required])],
     // 'end_time': [null, Validators.compose([Validators.required])],
    });
  }

  ngOnInit() {
    this.editShowType = "showMainList";
    this.initYearList();
    FrameRequest.requestArray("pl/plExamTime/listtime.htm", {}, (array) => {
      this.examTimeList = array;
    });
  }

  public query = {
    examTimeId: "",
    query: "",
    score: "",
    status: "",
    pubYear: ""
  }

  public queryDetail = {
    mainId: "",
    examTimeId: "",
    query: "",
    score: "",
    status: "",
    isNationExam: ""
  }

  public queryCourseVf = {
    sExamTimeId : "",
    tExamTimeId : "",
    query: "",
    vfStatus: ""
  }

  //发布主记录分页
  search(param) {
    if (!this.query.examTimeId) {
      this.query.examTimeId="";
    }
    param.examTimeId=this.query.examTimeId;
    param.query=this.query.query;
    param.status=this.query.status;
  }

  //发布明细记录分页
  searchDetail(param) {
    param.mainId=this.queryDetail.mainId;
    if (!this.queryDetail.examTimeId) {
      this.queryDetail.examTimeId = "";
    }
    param.examTimeId=this.queryDetail.examTimeId;
    param.query=this.queryDetail.query;
    param.status=this.queryDetail.status;
    if (!this.queryDetail.isNationExam) {
      this.queryDetail.isNationExam = "";
    }
    param.isNationExam=this.queryDetail.isNationExam;
  }

  //课程校验分页
  searchCourseVf(param) {
    param.sExamTimeId = this.queryCourseVf.sExamTimeId;
    param.tExamTimeId = this.queryCourseVf.tExamTimeId;
    param.query = this.queryCourseVf.query;
    param.vfStatus = this.queryCourseVf.vfStatus;
  }

  //删除批次 前限制
  async preDeleteEvent() {
    let checkArray = this.framePager.getCheckedArray();
    if (checkArray) {
      for (let i = 0; i < checkArray.length; i++) {
        if(checkArray[i].status != 0 && checkArray[i].status != 1) {//只能删除0-新建 状态
          AppComponent.alert({ 'title': '提示', text: '只能删除新建状态记录！' });
          return false;
        }
      }
    }
    if (this.mainStatus && this.mainStatus != 0 && this.mainStatus != 1) {
      AppComponent.alert({ 'title': '提示', text: '只能删除新建状态记录！' });
      return false;
    }
    return true;
  }

  publish() {
    let checkedArray = this.framePager.getCheckedArray((item)=>item.id);
    if(checkedArray.length === 0) {
      AppComponent.alert({title:"信息提示",text:"请选择数据!"});
      return;
    }
    AppComponent.confirm("确定发布?",()=>{
      let reqParam = {year:this.query.pubYear,RequestLoading:true};
      FrameRequest.requestMap(this.PUBLISH_URL, {ids:checkedArray.join()}, () => {
        AppComponent.GobalComponent.successMsg("发布成功");
        this.framePager.reload();
        return;
      });
    });
  }

  initYearList() {
    let dateNow = new Date();
    this.yearList.push({key:dateNow.getFullYear() + 1,val:dateNow.getFullYear() + 1});
    this.yearList.push({key:dateNow.getFullYear(),val:dateNow.getFullYear()});
    for (let i=1;i<=8;i++) {
      let yearN = dateNow.getFullYear() - i;
      this.yearList.push({key:yearN,val:yearN});
    }
  }

  examTimeChange(examTimeId) {
    if (examTimeId) {
      for (let examTime of this.examTimeList) {
        if (examTime.id == examTimeId) {
          this.item.pub_batch_name = examTime.exam_year_month +  "批次";
          break;
        }
      }
    }
  }

  //打开批次对应的计划详情
  goDetailList(main_id,exam_time_id,status) {
    this.editShowType = "planDetailList";
    this.pageLevel = "detail";
    this.mainId = main_id;
    this.mainStatus = status;
    this.queryDetail.mainId=main_id;
    this.mainExamTimeId = exam_time_id;
    this.queryDetail.examTimeId = exam_time_id;
    this.detailPager.reload();
  }

  //同步--
  synchronizeCourse() {
    if (this.mainStatus == 1) {
      AppComponent.alert({title:"信息提示",text:"考试计划已发布,不能重复同步!"});
      return;
    }
    let param = {
      main_id: this.mainId,
      exam_time_id: this.mainExamTimeId,RequestLoading:true
    }
    FrameRequest.request(this.DETAIL_SYNCHRONIZE_URL, param, (ret) => {
      if (ret.errorCode == 0) {
        AppComponent.GobalComponent.successMsg("同步成功!");
        this.detailPager.reload();
        return;
      }
    });
  }

  //添加修改课程界面关闭
  courseWinClose() {
    this.hideModal();
    this.editShowType = "planDetailList";
    this.pageLevel = "detail";
  }

  backMain() {
    this.editShowType = "showMainList";
    this.pageLevel = "main";
    //this.pageStart = 1;
  }

  //考试批次关闭窗口
  planMainWinClose() {
    this.hideModal();
    this.editShowType = "showMainList";
    this.pageLevel = "main";
  }

  //保存考试批次
  planMainSave() {
    if (!FrameFunction.validForm(this.formModel)) {
      return;
    }
    let url = this.item.id ? this.EDIT_URL: this.ADD_URL;
    if(_.isUndefined(this.item.id)) delete this.item.id;
    //循环判断元素是否undefined
    for (const key in this.item) {
      if(this.item[key] === undefined) {
        this.item[key] = "";
      }
    }
    FrameRequest.requestEntity(url, this.item, async () => {
      AppComponent.GobalComponent.successMsg('考试批次保存成功');
      this.framePager.reload();
      if(this.bsModalWin) {
        this.bsModalWin.hide();
      }
      this.item = null;
      this.editShowType = "showMainList";
    });
  }

  //添加课程
  planDetailSave() {
    if (!FrameFunction.validForm(this.courseFormModel)) {
      return;
    }
    let url = this.item.id ? this.EDIT_DETAIL_URL: this.ADD_DETAIL_URL;
    if(_.isUndefined(this.item.id)) delete this.item.id;
    //循环判断元素是否undefined
    for (const key in this.item) {
      if(this.item[key] === undefined) {
        this.item[key] = "";
      }
    }
    this.item.main_id=this.mainId;//关联主ID
    this.item.exam_time_id=this.mainExamTimeId;
    FrameRequest.requestEntity(url, this.item, async () => {
      AppComponent.GobalComponent.successMsg('添加课程成功');
      this.detailPager.reload();
      if(this.bsModalWin) {
        this.bsModalWin.hide();
      }
      this.item = null;
      this.editShowType = "planDetailList";
    });
  }

  /*selectCourse(courseId) {
    for (let i=0;i<this.courseList.length;i++) {
      if (this.courseList[i].id == courseId) {
        let codeStr = this.courseList[i].code_course_name.split(")")[0];
        let nameStr = this.courseList[i].code_course_name.split(")")[1];
        let courseCode = codeStr.substring(1, codeStr.length);
        this.item.course_code=courseCode;
        this.item.course_name=nameStr;
        if (this.courseList[i].is_nation_exam != undefined && this.courseList[i].is_nation_exam == 1) {
          this.item.is_nation_exam=this.courseList[i].is_nation_exam;
        } else {
          this.item.is_nation_exam=0;
        }
        this.item.score=this.courseList[i].course_score;//学分仅仅显示，不提交后台
        break;
      }
    }
  }*/

  deletePlanDetail(item?) {
    //批量操作
    if(!item) {
      let checkedArray = this.detailPager.getCheckedArray();
      if(checkedArray.length === 0){
        AppComponent.alert({title:"信息提示",text:"请选择数据!"});
        return;
      }
    }
    if (this.mainStatus == 1) {
      AppComponent.alert({title:"信息提示",text:"考试计划已发布,不能删除明细计划!"});
      return;
    }
    AppComponent.confirm("确定删除",()=>{
      let checkedArray = [];
      item ? checkedArray[0] = item.id: 
             checkedArray = this.detailPager.getCheckedArray((item)=>item.id);
      FrameRequest.requestMap(this.DELETE_DETAIL_URL, {ids:checkedArray.join()}, () => {
        AppComponent.GobalComponent.successMsg('数据删除成功');
        this.detailPager.reload();
      });
    });
  }

  verifyPopUp() {
    this.shouModalWin(this.verifyModal, 'modal-md');
    this.queryCourseVf.sExamTimeId="";
    this.queryCourseVf.tExamTimeId="";
  }

  //校验查询
  verifyQuery() {
    this.courseVfPager.reload();
    this.hideModal();
    this.editShowType = "verifyDetailList";
    this.pageLevel = "verify";

    //清空变量
    this.s_vf_exam_time_id = this.queryCourseVf.sExamTimeId;
  }

  //关闭校验窗口
  hideVerifyModal() {
    this.hideModal();
    this.editShowType = "showMainList";
    this.pageLevel = "main";
  }

  //--课程校验-同步
  synFromCompare(item) {
    AppComponent.confirm("确定同步",()=>{
      let param = {
        s_id: item.s_id,
        t_id: item.t_id,
        RequestLoading:true
      }
      FrameRequest.request(this.COURSE_VERIFY_SYN_URL, param, (ret) => {
        if (ret.errorCode == 0) {
          AppComponent.GobalComponent.successMsg("同步成功!");
          this.courseVfPager.reload();
          return;
        }
      });
    });
  }

  //--课程校验-添加到计划
  addFromCompare(item) {
    AppComponent.confirm("确定添加",()=>{
      let param = {
        year_code: item.year_code,
        exam_time_id: this.s_vf_exam_time_id,
        t_id: item.t_id,
        RequestLoading: true
      }
      FrameRequest.request(this.COURSE_VERIFY_ADD_URL, param, (ret) => {
        if (ret.errorCode == 0) {
          AppComponent.GobalComponent.successMsg("添加成功!");
          this.courseVfPager.reload();
          return;
        }
      });
    });
  }

  //从当前计划删除
  deleteFromCurPlan(item) {
    AppComponent.confirm("确定删除",()=>{
      let param = {
        s_id: item.s_id,
        RequestLoading:true
      }
      FrameRequest.request(this.COURSE_VERIFY_DEL_URL, param, (ret) => {
        if (ret.errorCode == 0) {
          AppComponent.GobalComponent.successMsg("删除成功!");
          this.courseVfPager.reload();
          return;
        }
      });
    });
  }

  //编辑课程
  async goCourseEdit(template: TemplateRef<any>,editShowType,modalcss:string,item?){
    FrameFunction.UntouchedForm(this.courseFormModel);
    //新增
    if(!item || item.id === undefined) {
      if (this.mainStatus == 1) {
        AppComponent.alert({title:"信息提示",text:"考试计划已发布,不能添加课程!"});
        return;
      }
       if(! await this.preGoEditEvent()) return ;
       if(!this.item) {
         this.item = {};
       } 
       this.courseFormModel.reset();
       this.showEdit(template, editShowType, modalcss);
       this.aftGoEditEvent();
     } else {
       FrameRequest.requestEntity("pl/mergePublishPlan/get.htm",{id: item.id}, async (entity) => {
         if(! await this.preGoEditEvent(entity)) return ;
         this.showEdit(template, editShowType, modalcss);
         setTimeout(async ()=>{
           this.item = entity;
           this.aftGoEditEvent();
         },100)
       });
     }
   }

   freshStartEndTime(examBatch) {
    if (examBatch == "A") {
      this.item.start_time="09:30";
      this.item.end_time="11:00";
    } else if (examBatch == "B") {
      this.item.start_time="14:30";
      this.item.end_time="17:00";
    } else if (examBatch == "C") {
      this.item.start_time="09:30";
      this.item.end_time="11:00";
    } else if (examBatch == "D") {
      this.item.start_time="14:30";
      this.item.end_time="17:00";
    } else if (examBatch == "X") {
      this.item.start_time="09:30";
      this.item.end_time="11:00";
    } else if (examBatch == "Y") {
      this.item.start_time="14:30";
      this.item.end_time="17:00";
    }
  }

  /**
   * 课程选择
   */
  flexCourseModalConfirm(modal) {
    let checkedArray = modal.framePager.getCheckedArray();
    if (checkedArray.length > 0) {
      this.item.course_name = checkedArray[0].course_name;
      this.item.course_id = checkedArray[0].id;
      this.item.score = checkedArray[0].course_score;
      modal.hideModal();
    }
  }

  //回退---发布改为新建状态
  regression() {
    let checkedArray = this.framePager.getCheckedArray();
    if(checkedArray.length === 0){
      AppComponent.alert({title:"信息提示",text:"请选择数据!"})
      return;
    }
    let forbit = false;
    for (let obj of checkedArray) {
      if (obj.status != 1) {
        forbit = true;
        return;
      }
    }
    if (forbit) {
      AppComponent.alert({title:"信息提示",text:"只能回退已发布记录!"});
      return;
    }
    AppComponent.confirm("确定回退",()=>{
      checkedArray = this.framePager.getCheckedArray((item)=>item.id);
      FrameRequest.request("pl/plPublishPlanMain/regression.htm", {ids:checkedArray.join()}, (ret) => {
        if (ret.errorCode == 0) {
          AppComponent.GobalComponent.successMsg("回退成功!");
          this.framePager.reload();
          return;
        }
      });
    });
  }

  exportExamPlain() {
    if (!this.queryDetail.examTimeId) {
      AppComponent.alert({title:"信息提示",text:"请选择考试批次!"})
      return;
    }
    AppComponent.GobalComponent.setLoading(true);
    let param = {
      exam_time_id: this.queryDetail.examTimeId,
      is_nation_exam: this.queryDetail.isNationExam
    }
    FrameRequest.download("pl/mergePublishPlan/exportxls.htm", param, ()=>{
      AppComponent.GobalComponent.setLoading(false);
      AppComponent.GobalComponent.successMsg("导出成功!");
    });
  }
}