import { Component, OnInit, TemplateRef, ViewChild, ViewContainerRef } 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 {FrameUploaderComponent} from '../../../../core/uploader/uploader.component';
import { AppComponent } from "../../../../app.component";
import { FrameRequest } from "../../../../shared/frame/frame-request";
import { FramePagerComponent } from "../../../../core/pager/pager.component";
import { FrameVariable } from "../../../../shared/frame/frame-variable";
import { FrameFunction } from "../../../../shared/frame/frame_function";
import * as _ from 'lodash';

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

  @ViewChild('framePager')
  framePager:FramePagerComponent;
  
  @ViewChild('auditModal')
  auditModal:TemplateRef<any>;

  @ViewChild('uploader')
  uploader: FrameUploaderComponent;

/**
 * 机构类型.
 */
 OrgTypeEnum = {
   PROVINCE_EXAM:0,
   SCHOOL_EXAM:1,
   CITY_EXAM:2,
   ASSIST_EXAM:3,
   EXAM_AREA:4,
   STUDY_CENTER:5
  };

  applyTimeList = [];
  masterSchoolList = [];//主考学校
  majorList = [];//专业列表-列表查询
  filterMajorList = [];//
  curOrg = {id:"",org_code:"",org_name:"",contact_number:"",org_code_bz:""};//当前登录人的机构
  selectMajorMap = {};//申报界面选择的专业map
  selectJoinSchoolMap = {};//申报界面多选的衔接学校
  schoolIds = [];//提交选择的衔接学校、主考学校列表
  majorIds = [];//提交选择的专业数组
  auditFileList = [];
  yearCodeList = [];


  isHiddenMajorFlag = true;//默认不显示已添加专业列表
  isHiddenSchoolFlag = true;//默认不显示已添加衔接学校列表
  curApplyOpenType : any;

  applyMajorList = [];//已经申请的专业列表
  authList = [];//审核记录

  public auditFileFormModel: FormGroup;

  majorApplyStatus={
    NEW_0: 0,
    TO_AUDIT_1: 1,
    FINISH: 2,
    NO_PASS:3,
    WAIT_AUDIT: 4
  };

  isActive=0;

  public query = {
    yearCode: "",
    masterSchoolId:"",  //主考学校
    applyForm: "",  //申报形式
    majorId: "" ,
    status:"" 
  };

  public importQuery = {
    yearCode: "",
    applyForm: ""
  }
  

  QUERY_URL = "pl/plMajorApply/page.htm";
  DELETE_URL = "pl/plMajorApply/delete.htm";
  GET_URL = "pl/plMajorApply/get.htm";
  ADD_URL = "pl/plMajorApply/add.htm";
  EDIT_URL = "pl/plMajorApply/edit.htm";
  DOWNLOAD_URL = "pl/plMajorApply/download.htm";
  GET_APPLY_INFO = "pl/plMajorApply/applyinfo.htm";
  UPLOAD_URL = "pl/plMajorApplyAuditFile/upload.htm";

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

  ngOnInit() {
    this.query.status = "1";

    //基础数据(主考学校列表、专业列表、当前登录机构对象)
    FrameRequest.requestMap("pl/plMajorApply/basedata.htm", {org_type:[1]}, (map)=>{
      //this.masterSchoolList = map.schoolList;
     // this.majorList = map.majorList;
      this.curOrg = map.curOrg;
    });
    //年度码
    //FrameRequest.requestArray("pl/plYearCode/list.htm", {}, (array) => {
    //  this.yearCodeList = array;
    //});

    FrameRequest.requestArray("cf/cfOrganization/list.htm?org_type=1&status=1", {}, (array) => {
      this.masterSchoolList = array;
    });

   
  }

  search(param){
    if (!this.query.yearCode) {
      this.query.yearCode="";
    }
    if (!this.query.masterSchoolId) {
      this.query.masterSchoolId="";
    }
     if (!this.query.applyForm) {
       this.query.applyForm="";
     }
    if (!this.query.majorId) {
      this.query.majorId="";
    }
    param.yearCode=this.query.yearCode;
    param.masterSchoolId=this.query.masterSchoolId;
    param.applyForm=this.query.applyForm;
    param.majorId=this.query.majorId;
    param.status=this.query.status;
  }

  resetQuery(){
    this.query.yearCode="";
    this.query.masterSchoolId="";
    this.query.applyForm="";
    this.query.majorId="";
  }
  
  getKeys(item) {
    return Object.keys(item);
  }

  //工具栏审批-弹出明细
  doAudit(){
    let checkedArray = this.framePager.getCheckedArray();
    if (checkedArray.length == 0) {
      AppComponent.alert({title:"信息提示",text:"请选择待审批记录!"});
      return;
    }
    if (checkedArray[0].status != this.majorApplyStatus.TO_AUDIT_1) {
              AppComponent.alert({title:"信息提示",text:"只能审核待审核状态记录!"});
              return;
    }
    //查询该审核列表
    this.proxyGoEdit(checkedArray[0]);
  }

  //进入详情代理
  proxyGoEdit(item) {
    
    // 如果状态是待审批，则修改成审批中
    if(item.status==1){
      item.status = '4';
      let repParam =  _.cloneDeep(item);

      delete repParam.masterSchool;

      FrameRequest.request("pl/plMajorApply/edit.htm", repParam, (ret)=>{
      
      });
    }

    
    
    this.getApplyBaseInfo(item.id);
    this.goEdit(this.auditModal,'only','modal-lg',item);
  }

  //工具栏审批--保存
  async save() {
    if (!FrameFunction.validForm(this.formModel)) {
      return;
    }
    this.auditLogic();
  }

  //提交审核
  auditFunc() {
    if (!FrameFunction.validForm(this.formModel)) {
      return;
    }
    this.auditLogic();
  }

  //审核通过就完成2-，审核驳回就到新建-0
  auditLogic() {
    //待审核
    if (this.item.status == 1 || this.item.status == 4) {//原始状态为1-待审核
      if (this.item.auth_type == 1) {//审核通过
        this.item.status = this.majorApplyStatus.FINISH;
      } else if (this.item.auth_type == 0) {
       
        this.item.status = this.majorApplyStatus.NO_PASS;//审核不通过
      } 
      this.item.audit_remark = this.item.audit_remark;
    }/* else if (this.item.status == 2) {//待归档
      if (this.item.auth_type == 1) {//审核通过
        this.item.status = this.majorApplyStatus.ARCHIVED_3;
      } else if (this.item.auth_type == 0) {
        this.item.status = this.majorApplyStatus.TO_ARCHIVE_2;
      }
    }*/

    let repParam =  _.cloneDeep(this.item);

    delete repParam.masterSchool;
    repParam.RequestLoading = true;

    FrameRequest.request("pl/plMajorApply/audit.htm", repParam, (ret)=>{
      if (ret.errorCode == 0) {
        this.hideModal();
        this.framePager.reload();
        AppComponent.GobalComponent.successMsg("提交成功");
      }
    });
  }

  //获取申报审核基础数据
  getApplyBaseInfo(applyId) {
    FrameRequest.requestMap(this.GET_APPLY_INFO, {id: applyId}, async (map) => {
      this.authList = map.authList;
      this.applyMajorList = map.applyMajorList;
    });
  }

  //下载申报资料
  downloadApplyFile(applyId) {
    FrameRequest.download(this.DOWNLOAD_URL,  { id: applyId });
  }

  //导入
  importFunc() {
    if (!this.importQuery.yearCode) {
      AppComponent.alert({title: "信息提示", text: "请选年度码!"});
      return;
    }
    if (!this.importQuery.applyForm) {
      AppComponent.alert({title: "信息提示", text: "请选申报形式!"});
      return;
    }
    let param = {
      yearCode: this.importQuery.yearCode, 
      applyForm: this.importQuery.applyForm,
      RequestLoading: true
    };
    this.uploader.choooseFileAndUpload(param, ((ret) => {
      if (ret.errorCode > 0) {
        AppComponent.alert({title:"信息提示", text: ret.errorMsg});
      } else if (ret.errorCode == -1) {
        /*this.hideModal();
        this.editShowType = "showMainList";*/
        AppComponent.GobalComponent.successMsg("上报失败!");
      } else if (ret.errorCode == 0) {
        /*this.hideModal();
        this.framePager.reload();
        this.editShowType = "showMainList";*/
        AppComponent.GobalComponent.successMsg("上报成功!");
        let param = {
          start: 0,
          limit: 9999,
          yearCode: this.importQuery.yearCode, 
          applyForm: this.importQuery.applyForm,
        };
        FrameRequest.requestPage("pl/plMajorApplyAuditFile/page.htm", param, (page)=>{
          this.auditFileList = page.records;
        });
      }
    }));
  }

  freshAuditFile(obj) {
    this.auditFileList = [];
    let param = {
      start: 0,
      limit: 9999,
      yearCode: this.importQuery.yearCode, 
      applyForm: this.importQuery.applyForm
    };
    FrameRequest.requestPage("pl/plMajorApplyAuditFile/page.htm", param, (page)=>{
      this.auditFileList = page.records;
    });
  }

  //下载审批批文
  downloadAuditFile(id) {
    FrameRequest.download("pl/plMajorApplyAuditFile/download.htm",  { id: id });
  }

  
  changeLi(event,index,status){
    //点击时，将索引值赋值给变量isActive可以实现点击切换样式
    this.isActive = index;
    
    this.query.status = status;
    this.framePager.reload();

  }

}