import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, ParamMap, Router} from '@angular/router';
import {StdRegModifyComponent} from '../std-reg-modify/std-reg-modify.component';
import {StdRegAgentComponent} from '../std-reg-agent/std-reg-agent.component';
import {StdRegAspectComponent} from '../std-reg-aspect/std-reg-aspect.component';
import {StdRegTracksComponent} from '../std-reg-tracks/std-reg-tracks.component';
import {StdInterviewModifyComponent} from '../std-interview-modify/std-interview-modify.component';
import {StdLaterEnrolComponent} from '../std-later-enrol/std-later-enrol.component';
import { BsModalService } from 'ngx-bootstrap/modal';
import { FramePageComponent } from '../../../../frame/core/page/frame.page';
import { AjaxService } from '../../../../../core/service/ajax.service';
import { MsgService } from '../../../../../core/service/msg.service';
import { FuncService } from '../../../../../core/service/func.service';
import { FrameAjax } from '../../../../../core/frame/ajax/frame-ajax/frame-ajax';
import { StdMaterialRefuseComponent } from '../../material/std-material-refuse/std-material-refuse.component';

declare var aliPlayerUtil :any;

@Component({
  selector: 'app-std-reg-detail',
  templateUrl: './std-reg-detail.component.html',
  styleUrls: ['./std-reg-detail.component.scss']
})
export class StdRegDetailComponent extends FramePageComponent implements OnInit {

  std_id: any;
  searchText: any;
  std: any;
  materialArray: any;
  materialMap: any;

  videoModal: any;
  bsModalWin: any;
  aliPlayer: any;


  @ViewChild('ajaxEnrol', {static: false}) ajaxEnrol: FrameAjax;
  @ViewChild('ticketAjax', {static: false}) ticketAjax: FrameAjax;

  constructor(private activateInfo: ActivatedRoute, private router: Router, private modalService: BsModalService) {
    super(modalService);
    this.activateInfo.paramMap.subscribe((params: ParamMap) => {
      this.std_id = params.get('std_id');
      this.queryStd();
    });
    setTimeout(() => {
      if (this.std_id === undefined) {
        this.router.navigate(['/art/std/reg/page']);
        return;
      }
    }, 100);
    this.modalComponent = StdRegModifyComponent;
  }

  ngOnInit() {
  }

  queryStd() {
    this.std = undefined;
    this.materialArray = [];
    this.materialMap = {};
    AjaxService.requestMap('std/reg/info.htm', {std_id: this.std_id}, (map) => {
      if (map['StdReg'] === undefined) {
        MsgService.errorToastr('获取考生失败，数据同步错误！');
        this.router.navigate(['/art/std/reg/page']);
        return;
      }
      this.std = map['StdReg'];
      this.materialArray = map['MaterialArray'];
      for (const s of map['MaterialArray']) {
        this.materialMap[s.material_type] = s;
      }
    });
  }

  searchStd() {
    this.std = undefined;
    this.std_id = undefined;
    if (this.searchText === undefined || this.searchText.length < 2)
      return;
    AjaxService.requestPage('std/reg/page.htm', {query: this.searchText, start: 0, limit: 2}, (page) => {
      if (page.records.length == 0) {
        MsgService.errorToastr('未找到符合条件的考生');
        return;
      }
      if (page.records.length > 1) {
        MsgService.errorToastr('有多个符合条件的考生，请从考生列表中查询后进行跳转！');
        return;
      }
      this.std_id = page.records[0].std_id;
      // this.router.navigate(['/art/std/reg/detail',this.std_id] );
      this.queryStd();
    }, {RequestWithLoading: true});
  }

  /***************
   * 审核失败
   * @param material
   */
  refuseMaterial(material) {
    this.onModalClose = () => {
      this.queryStd();
    };
    this.showComponentModal(StdMaterialRefuseComponent, {ResponseEntity: material, 'arrayUrl': 'std/material/refuse/all.htm'});
  }

  /******************
   * 准备准考证上的科目
   */
  prepareTicketSubject(map) {
    if(map.TicketArray) {
      for (const t of map.TicketArray) {
        map['WrittenArray_' + t.ly_ticket_id] = [];
        map['InterviewArray_' + t.ly_ticket_id] = [];
        for (const sb of map['Ticket_' + t.ly_ticket_id]) {
          if (sb.ly_room_addr) {
            sb.ly_room_addr = sb.ly_room_addr + (sb.ly_room_seq === undefined ? '' : ('[序号：' + sb.ly_room_seq + ']'));
          }
          map[sb.subject_type + 'Array_' + t.ly_ticket_id].push(sb);
          if (sb.real_room_id === undefined && sb.subject_type === 'Interview') {
            t.allow_modify = true;
          }
        }

        this.prepareSubjectArray(map['WrittenArray_' + t.ly_ticket_id]);
        this.prepareSubjectArray(map['InterviewArray_' + t.ly_ticket_id]);
      }
    }

  }

  prepareSubjectArray(subjectArray) {
    let current_date = undefined, current_time = undefined, current_addr = undefined;
    let row_colspan = 0, time_row_colspan = 0, addr_row_colspan = 0;
    for (let w of subjectArray) {


      row_colspan = 0;
      time_row_colspan = 0;
      addr_row_colspan = 0;
      const exam_date = FuncService.dateToShortString(w.ly_exam_date);
      // 新的日期
      if (exam_date !== current_date) {
        for (let m of subjectArray) {
          const m_date = FuncService.dateToShortString(m.ly_exam_date);
          if (m_date === exam_date) {
            row_colspan++;
          }
        }
        current_date = exam_date;
        current_time = '';
        time_row_colspan = 0;
        w.row_colspan = row_colspan;
      } else {
        w.row_colspan = 0;
      }

      // 考试日期
      let exam_time = FuncService.dateToTimeString(w.exam_start_time) + ' - ' + FuncService.dateToTimeString(w.exam_end_time);
      if (exam_time !== current_time) {
        time_row_colspan = 0;
        // 新的日期
        for (let m of subjectArray) {
          const m_time = FuncService.dateToTimeString(m.exam_start_time) + ' - ' + FuncService.dateToTimeString(m.exam_end_time);
          if (m_time === exam_time && current_date === FuncService.dateToTimeString(m.ly_exam_date)) {
            time_row_colspan++;
          }
        }
        current_time = exam_time;
        w.time_row_colspan = time_row_colspan;
        w.ly_exam_time = current_time;
      } else {
        w.time_row_colspan = 0;

      }

      // 考试日期
      let room_addr = w.ly_room_addr;
      if (room_addr !== current_addr) {
        addr_row_colspan = 0;
        // 新的日期
        for (let m of subjectArray) {
          const m_addr = m.ly_room_addr;
          if (m_addr === room_addr) {
            addr_row_colspan++;
          }
        }
        current_addr = room_addr;
        w.addr_row_colspan = addr_row_colspan;
      } else {
        w.addr_row_colspan = 0;
      }
    }

  }

  /********************
   * 修改信息
   */
  changeCert() {
    this.onModalClose = () => {
      this.queryStd();
    };

    this.showComponentModal(StdRegModifyComponent, {ResponseEntity: this.std, 'arrayUrl': 'frame/region/province/list.htm'});
  }

  /******************
   * 解除微信绑定
   */
  unbinding() {
    MsgService.confirmAlert('确定要解除该考生的微信绑定关系吗？', () => {
      AjaxService.request('std/reg/unbinding.htm', this.std, () => {
        this.queryStd();
      });
    });
    return false;
  }

  /**********************
   * 更改考点信息
   */
  changeAgent(enrol) {
    this.onModalClose = () => {
      this.ajaxEnrol.reload({std_id: this.std.std_id});
    };
    AjaxService.requestMap('std/reg/enrol/agent/init.htm', enrol, (map) => {
      this.showComponentModal(StdRegAgentComponent, {ResponseMap: map}, {class: 'modal-7'});
    });
  }

  /**********************
   * 更改专业信息
   */
  changeAspect(enrol) {
    this.onModalClose = () => {
      this.ajaxEnrol.reload({std_id: this.std.std_id});
    };
    AjaxService.requestMap('std/reg/enrol/aspect/init.htm', enrol, (map) => {
      this.showComponentModal(StdRegAspectComponent, {ResponseMap: map},);
    });
  }

  deleteAspect(enrol) {
    MsgService.confirmAlert('确定要删除该考生报考的专业吗？删除该报考不会触发退款，如需退款请从其他渠道进行退费！', () => {
      AjaxService.requestMap('std/reg/enrol/remove.htm', enrol, () => {
        MsgService.successToastr('考生专业已经删除！');
        this.ajaxEnrol.reload({std_id: this.std.std_id});
      });
    });

  }

  /**********************
   * 更改曲目信息
   */
  changeTracks(enrol,batch_id) {
    enrol.batch_id = batch_id;
    this.onModalClose = () => {
      this.ajaxEnrol.reload({std_id: this.std.std_id});
    };
    AjaxService.requestMap('std/reg/enrol/tracks/init.htm', enrol, (map) => {
      this.showComponentModal(StdRegTracksComponent, {ResponseMap: map}, {class: 'modal-6'});
    });
  }

  /**********************
   * 更改考点信息
   */
  modifyInterview(group) {
    this.onModalClose = () => {
      this.ticketAjax.reload({std_id: this.std.std_id});
    };
    this.showComponentModal(StdInterviewModifyComponent, {ResponseEntity: group});

  }

  /**********************
   * 考生补报名
   */
  laterEnrol() {
    this.onModalClose = () => {
      this.ajaxEnrol.reload({std_id: this.std.std_id});
    };
    this.showComponentModal(StdLaterEnrolComponent, {
      arrayUrl: 'enrol/config/category/list.htm', arrayParam: {
        std_id: this.std.std_id
      }, currentEntity: this.std
    }, {class: 'modal-6p'});

  }

  /******************
   * 延期缴费，当前+1天时间
   */
  laterPay(v) {
    this.onModalClose = () => {
      this.ajaxEnrol.reload({std_id: this.std.std_id});
    };
    MsgService.confirmAlert('确定要允许该考生在1天内可以完成缴费吗？', () => {
      AjaxService.request('std/reg/enrol/delay.htm', {enrol_id: v.enrol_id, std_id: this.std_id}, () => {
        MsgService.successAlert('该专业1天内允许考生自主缴费，请通知考生尽快完成缴费！');
      }, {RequestWithLoading: true});
    });

  }

  /**
   *  下载准考证
   */
  downloadTicket(ticket_file_name) {
    window.open(this.FrameService.getParamValue('EnrolMaterialWebPath') + '/' + ticket_file_name);
  }
  makeStdTicket(ticket, flag) {
    let msg = '确定要生成该考生准考证吗！';
    if (flag) {
      msg = '确定要重新生成该考生的准考证码？';
    }
    MsgService.confirmAlert(msg, () => {
      this.FuncService.ajaxDownload('layout/material/ticket/make.htm', ticket);
    });
  }


  //播放视频
  startVideo(videoModal, video_file) {
    this.videoModal = videoModal;
    this.nextVideo(true, video_file);
  }

  nextVideo(firstLoad, video_file) {
    if (firstLoad) {
      this.initVideoPlayer();
    }
    aliPlayerUtil.changeSource(this.aliPlayer, video_file);
  }

   //视频初始化
   initVideoPlayer(url?) {
    this.bsModalWin = this.modalService.show(this.videoModal, { class: 'modal-9p' , backdrop: 'static', keyboard: false});
    this.aliPlayer = aliPlayerUtil.init('aliPlayer', url);
  }

  //隐藏视频窗口
  hideModal(){
    if(this.bsModalWin) this.bsModalWin.hide();
  }

  //视频暂停播放
  pauseVideo(){
    aliPlayerUtil.pause(this.aliPlayer);
  }

  //视频继续播放
  playVideo(){
    aliPlayerUtil.play(this.aliPlayer);
  }

  callbackToStdReg(v) {
    this.MsgService.successAlert('删除成功');
    this.router.navigate(['/art/std/reg/page']);
  }

}


