import {Component, OnInit, ViewChild} from '@angular/core';
import {FramePageComponent} from "../../../frame/core/page/frame.page";
import {Router} from "@angular/router";
import {CookieService} from "ngx-cookie-service";
import {BsModalService} from "ngx-bootstrap/modal";
import {AjaxService} from "../../../../core/service/ajax.service";
import {MsgService} from "../../../../core/service/msg.service";

@Component({
  selector: 'app-score-input-gobal',
  templateUrl: './score-input-gobal.component.html',
  styleUrls: ['./score-input-gobal.component.scss']
})
export class ScoreInputGobalComponent extends FramePageComponent implements OnInit {


  param: any;
  agent: any;
  searchText: any;
  std: any;
  change: boolean = false;
  stdArray = [];
  scoreArray = [];
  subjectArray = [];
  chooseSubject = [];
  currentStep: any;

  // 考点列表
  agentArray = [];
  //专业
  aspectArray = [];
  subject_ids = [];

  @ViewChild('ticketNum', {static: false}) ticketNum;


  constructor(private router: Router, private cookies: CookieService, modalService: BsModalService) {
    super(modalService);
    this.param = {};
    this.std = {};
  }

  ngOnInit() {
    const agent_id = this.cookies.get('CurrentAgentId');
    if (agent_id !== undefined && agent_id.length > 0) {
      // 去获取
      AjaxService.requestEntity('layout/agent/find.htm', {ly_agent_id: agent_id}, (entity) => {
        this.agent = entity;
        setTimeout(() => {
            if (this.ajax) {
              this.ajax.reload();
            }
          }, 1);
          this.goInit();
      });
    } else {
      this.router.navigate(['/art/layout/agent/page']);
    }
    // AjaxService.requestArray('conf/agent/all.htm', {}, (array) => {
    //   this.agentArray = array;
    //   if (this.agentArray.length == 1) {
    //     this.agent = this.agentArray[0];
    //     setTimeout(() => {
    //       if (this.ajax) {
    //         this.ajax.reload();
    //       }
    //     }, 1);
    //     this.goInit();

    //   } else {
    //     this.router.navigate(['/art/layout/agent/page']);
    //   }
    // });
  }

  goInit() {
    this.param = {};
    this.std = {};
    this.param.layout_type = 'Active';
    this.param.examticket_type='Aspect';
    this.param.judge_num=1;
    this.getAspect();
    this.getSubject();
    this.scoreArray=[];
  }

  getAspect() {
    AjaxService.requestArray('conf/aspect/all.htm', {}, (array) => {
      this.aspectArray = array;
      for(const aspect of this.aspectArray) {
        aspect.aspect_name = aspect.aspect_code + '|' + aspect.aspect_name;
      }
      this.aspectArray.unshift({aspect_id:'', aspect_code: '', aspect_name:'请选择'});
    });
  }

  getSubject(aspect_id?:any) {
    
    if(aspect_id) {
      AjaxService.requestArray('conf/aspect/subject/score/list.htm', {aspect_id: aspect_id}, (array) => {
        if (array) {
          this.subjectArray = array;
          for (const subject of this.subjectArray) {
            subject.subject_full_name = subject.subject_code + '|' + subject.subject_name + '|' + subject.subject_type;
          }
        }
        this.currentStep = 'Init';
      });
    } else {
      AjaxService.requestArray('conf/subject/list.htm', {}, (array) => {
        if (array) {
          this.subjectArray = array;
          for (const subject of this.subjectArray) {
            subject.subject_full_name = subject.subject_code + '|' + subject.subject_name;
          }
        }
        this.currentStep = 'Init';
      });
    }
    
  }

  //开始录入分数
  startInput() {
    this.currentStep = 'Input';
    setTimeout(() => {
      this.ticketNum.nativeElement.focus();
    }, 500);
  }

  searchStd($event, query_type?: any) {
    if (this.param.ticket_num) {
      AjaxService.requestMap('score/input/query.htm', {
        ticket_num: this.param.ticket_num,
        'subject_ids[]': this.param.subjectArray,
        input_score_type:this.param.input_score_type,
        examticket_type:this.param.examticket_type,
        query_type: query_type
      }, (map) => {
        this.std = map['std'];
        this.scoreArray = map['scoreArray'];
        if (this.scoreArray === undefined || this.scoreArray.length === 0) {
          MsgService.errorAlert('该考生没有对应的考试科目！');
          this.ticketNum.nativeElement.selectAll();
          this.ticketNum.nativeElement.focus();
        } else {
          setTimeout(function () {
            this.nextInput($event);
          }.bind(this), 300);
        }
      });
    }
  }

  chooseSubjectAgain() {
    this.currentStep = 'Init';
    this.goInit();
  }

  saveScore() {
    AjaxService.request('score/input/save.htm', {
      std_id: this.std.std_id,
      ticket_num: this.param.ticket_num,
      agent_id: this.agent.ly_agent_id,
      judge_count: this.param.judge_num,
      score_type: this.param.input_score_type,
      tag: this.param.tag,
      subject_json: JSON.stringify(this.scoreArray)
    }, () => {
      if (this.param.input_score_type === 'One') {
        MsgService.successToastr('考生【' + this.param.ticket_num + '】分数录入成功！');
      } else {
        MsgService.successToastr('考生【' + this.param.ticket_num + '】分数二次确认成功！');
      }
      let array = [];
      let entity = this.std;
      if(this.scoreArray && this.scoreArray.length>0) {
        let result = this.scoreArray[0];
        if(result.js01 !== undefined)   array.push(result.js01);
        if(result.js02 !== undefined)   array.push(result.js02);
        if(result.js03 !== undefined)   array.push(result.js03);
        if(result.js04 !== undefined)   array.push(result.js04);
        if(result.js05 !== undefined)   array.push(result.js05);
        if(result.js06 !== undefined)   array.push(result.js06);
        if(result.js07 !== undefined)   array.push(result.js07);
        
      }
      entity.score = array;
      this.stdArray.splice(0, 0, entity);
      this.clean();
      setTimeout(() => {
        this.param.ticket_num = this.param.ticket_num.substr(0, this.param.prefix);
        this.ticketNum.nativeElement.focus();
      }, 100);
      this.pager.reload();
    })
  }

  checkValue = function ($event) {
    var key = $event.keyCode;
    if (key == 8 || key == 13 || key == 9)
      return;
    if ((key > 47 && key < 58) || (key > 94 && key < 106) || key == 110 || key == 190) {

    } else {
      $event.preventDefault();
      return;
    }
  }

  nextInput($event) {
    var inputs = $("form[name='subjectForm']").find(":text");

    if ($event) {
      var idx = inputs.index($event.target);
     // console.log(idx);
      // 提交
      if (idx == inputs.length - 1 - 3) {
        if ($event.keyCode == 13) {
          this.saveScore();
        }
      } else
        inputs[idx + 1].focus();
    } else
      inputs[1].focus();

  }

  changScore($event) {
    if (($event.keyCode == 13 || $event.keyCode == 9) && $event.target.value != '') {
      this.nextInput($event);
      return;
    }
  }

  //清除分数
  clean() {
    this.std = {};
    $("form[name='subjectForm']").find(":text").val('');
    // this.param.ticket_num = '';
    setTimeout(function(){ this.subjectArray = [];}.bind(this),100);

  }

  deleteScore(std: any) {
    if (this.param.input_score_type === 'Two') {
      return;
    }
    MsgService.confirmAlert('确定要删除一录分数吗？', () => {
      AjaxService.request('score/input/delete.htm', {
        std_id: std.std_id,
        agent_id: this.agent.ly_agent_id,
        'subject_ids[]': this.param.subjectArray
      }, () => {
        MsgService.successToastr('删除成功！');
        for (let i = 0; i < this.stdArray.length; i++) {
          if (this.stdArray[i].std_id === std.std_id) {
            this.stdArray.splice(i, 1);
          }
        }
        this.pager.reload();
      });
    });
  }

  //查看分数
  viewScore(std: any) {
    if (this.param.input_score_type === 'Two') return;
    var ticket_num = std.ticket_num;
    if(this.param.examticket_type==='Aspect')
      ticket_num = std.aspect_num;
    AjaxService.requestMap('score/input/query.htm', {
      examticket_type:this.param.examticket_type,
      ticket_num: ticket_num,
      query_type: 'view',
      'subject_ids[]': this.param.subjectArray,
      input_score_type: this.param.input_score_type
    }, (map) => {
      // let arr = [];
      this.std = map['std'];
      this.scoreArray = map['scoreArray'];
      this.param.ticket_num = std.aspect_ticket_num;

      this.change = true;
    });
  }

  //一录修改分数
  editScore() {
    MsgService.confirmAlert('确定要修改一录的分数吗？', () => {
      AjaxService.request('score/input/edit.htm', {
        std_id: this.std.std_id,
        ticket_num: this.param.ticket_num,
        agent_id: this.agent.ly_agent_id,
        judge_count: this.param.judge_num,
        score_type: this.param.input_score_type,
        tag: this.param.tag,
        subject_json: JSON.stringify(this.scoreArray)
        // json: JSON.stringify(this.param.judgeIds)
      }, () => {
        MsgService.successToastr('考生【' + this.param.ticket_num + '】分数修改成功！');
        let array = [];
        // for (const judge of this.param.judgeIds) {
        //   array.push(judge.s01);
        // }
        let entity = this.std;
        if(this.scoreArray && this.scoreArray.length>0) {
          let result = this.scoreArray[0];
          if(result.js01 !== undefined)   array.push(result.js01);
          if(result.js02 !== undefined)   array.push(result.js02);
          if(result.js03 !== undefined)   array.push(result.js03);
          if(result.js04 !== undefined)   array.push(result.js04);
          if(result.js05 !== undefined)   array.push(result.js05);
          if(result.js06 !== undefined)   array.push(result.js06);
          if(result.js07 !== undefined)   array.push(result.js07);
        }
        for (const std of this.stdArray) {
          if (std.std_id === entity.std_id) {
            std.score = array;
          }
        }
        this.clean();
        this.change = false;
        this.param.ticket_num = entity.aspect_ticket_num.substr(0, this.param.prefix);
        this.ticketNum.nativeElement.focus();
        this.pager.reload();
      });
    });
  }

  //一录分数查询
  searchStdScore() {
    var arr = [];
    if (this.searchText) {
      if (this.param.input_score_type === 'One') return;
      AjaxService.requestMap('score/input/query.htm', {
        ticket_num: this.searchText,
        query_type: 'view',
        'subject_ids[]': this.param.subjectArray
      }, (map) => {
        let arr = [];
        this.std = map['std'];
        arr = map['scoreArray'];
        this.scoreArray = map['scoreArray'];
        this.param.ticket_num = this.searchText;
        for (let k = 0; k < arr.length; k++) {
          for (let j = 0; j < this.chooseSubject.length; j++) {
            if (arr[k].subject_id === this.chooseSubject[j].subject_id) {
              for (let i = 0; i < this.param.judgeIds.length; i++) {
                this.param.judgeIds[i]['s0' + (j + 1)] = arr[k]['js0' + (i + 1)];
              }
            }
          }
        }
        this.ticketNum.nativeElement.focus();
      });
    }
  }

}
