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

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


    param: any;
    agent: any;
    searchText: any;
    std: any;
    change: boolean = false;
    subjectArray = [];
    judgeArray = [];
    chooseSubject = [];
    drArray = [];
    judgeIdsArray = [];
    stdArray = [];
    scoreArray= [];
    currentStep:any;
    subject_ids = [];
    
    @ViewChild('ticketNum', {static: false}) ticketNum;


  constructor(private router: Router, private cookies: CookieService,modalService: BsModalService) { 
    super(modalService);
    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']);
    }
  }

  ngOnInit() {
  }

  goInit() {
    this.param = {};
    this.std = {};
    this.subjectArray = [];
    this.judgeArray = [];
    this.chooseSubject = [];
    this.drArray = [];
    this.judgeIdsArray = [];
    this.param.prefix = 5;
    this.getSubject();
    this.getJudge();
  }

  getSubject() {
    AjaxService.requestArray('conf/subject/list.htm', {subject_type: 'Written'}, (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';
    });
  }

  //评委
  getJudge() {
    AjaxService.requestArray('exam/judge/list.htm', {agent_id : this.agent.ly_agent_id}, (array) => {
      if(array) {
        this.judgeArray = array;
        for(const judge of this.judgeArray) {
          judge.full_judge_name = judge.judge_mobile + '|'+ judge.judge_name;
        }
      }
    });
  }


  //增加科目
  addSubject() {
    //判断是否已经添加
    for(const choose of this.chooseSubject) {
      if(choose.subject_id === this.param.subject_id) {
        MsgService.warningToastr('该科目已经添加，请不要重复添加！');
        return ;
      }
    }
    for(const subject of this.subjectArray) {
      if(subject.subject_id === this.param.subject_id) {
        this.chooseSubject.push(subject);
      }
    }
  }

  //删除科目
  removeSubject(subject: any) {
    for(const choose of this.chooseSubject) {
      if(choose.subject_id === subject.subject_id) {
        this.chooseSubject.splice(subject,1);
        break;
      }
    }
  }

  setJudge(judge_num: any) {
    const array = [];
    if(judge_num) {
      for(let i = 0; i<judge_num; i++) {
        array.push({i: i});
      }
      this.param.judgeIds = array;
    } else {
      this.param.judgeIds =[];
    }
  }

 

  //开始录入分数
  startInput() {
    this.checkNull();
    this.getInputSum();    
    this.setData();
    setTimeout(() => {
      this.ticketNum.nativeElement.focus();
    },500);
  }

  getInputSum() {
    const array = [];
    this.subject_ids = [];
    for(const choose of this.chooseSubject) {
      array.push(choose.subject_id);
    }
    this.subject_ids = array;
    AjaxService.requestArray('score/input/subject/stat/ago.htm' , {subject_ids : array}, (array) => {
      this.drArray = array;
      if(this.drArray && this.drArray.length === 0) {
        this.drArray.push({i05: 0, i06: 0});
      }
      this.currentStep = 'Input';
    });
  }

  setData() {
    let subject_names = '';
    for(const subject of this.chooseSubject) {
      subject_names = subject_names+subject.subject_name+',';
    }
    this.param.subject_names = subject_names.substr(0, subject_names.length-1);
    for(const judgeId of this.param.judgeIds) {
      for(const judge of this.judgeArray) {
        if(judgeId.judge === judge.judge_id) {
          judgeId.judge_name = judge.judge_name;
          judgeId.s29 = judge.judge_name;
          judgeId.i29 = judge.judge_id;
          break;
        }
      }
    }
  }

  checkNull() {
    if(this.param.input_score_type === 'One') {
      if(!this.param.tag) {
        MsgService.errorToastr('请填写袋号！');
        return;
      }

      for(const arr of this.param.judgeIds) {
        if(!arr.judge) {
          MsgService.errorToastr('请选择评委！');
          return;
        }
      } 
    }
  }


  searchStd($event,query_type? : any) {
    if(this.param.ticket_num) {
        AjaxService.requestMap('score/input/query/ago.htm', {
          ticket_num: this.param.ticket_num,
          query_type: query_type
        }, (map) => {
          this.std = map['std'];
          this.scoreArray = map['scoreArray'];
          this.nextInput($event);
        });
    }
  }

  chooseSubjectAgain() {
    this.currentStep = 'Init';
    this.param = {};
    this.chooseSubject = [];
    this.drArray = [];
    this.judgeIdsArray = [];
    this.param.prefix = 5;
  }

  saveScore() {
    AjaxService.request('score/input/save/ago.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.chooseSubject),
      json: JSON.stringify(this.param.judgeIds)
    }, () => {
      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;
      for(const judge of this.param.judgeIds) {
        array.push(judge.s01);
      }
      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.getInputSum();
      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);
			// 提交
			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 = {};
    for(let i =0;i<this.param.judge_num;i++) {
      for(let j=0;j<this.chooseSubject.length;j++) {
        this.param.judgeIds[i]['s0'+(j+1)] = undefined;
      } 
    }
  }

  deleteScore(std: any) {
    if(this.param.input_score_type === 'Two') {
      return;
    }
    MsgService.confirmAlert('确定要删除一录分数吗？', () => {
      AjaxService.request('score/input/delete/ago.htm', {
        std_id : std.std_id,
        agent_id: this.agent.ly_agent_id,
        subject_json: JSON.stringify(this.chooseSubject)
      }, () => {
        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;
    AjaxService.requestMap('score/input/query/ago.htm', {
      ticket_num: std.aspect_ticket_num,
      query_type : 'view'
    }, (map) => {
      let arr = [];
      this.std = map['std'];
      arr = map['scoreArray'];
      this.param.ticket_num = std.aspect_ticket_num;
      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.change = true;
    });
  }

  //一录修改分数
  editScore() {
    MsgService.confirmAlert('确定要修改一录的分数吗？', () => {
      AjaxService.request('score/input/edit/ago.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.chooseSubject),
        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;
        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() {
    if(this.searchText) {
      if(this.param.input_score_type === 'One') return;
      AjaxService.requestMap('score/input/query/ago.htm', {
        ticket_num: this.searchText,
        query_type : 'view'
      }, (map) => {
        let arr = [];
        this.std = map['std'];
        arr = 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();
      });
    }
  }

}
