import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, ParamMap, Router} from '@angular/router';
import {FramePageComponent} from '../../../../frame/core/FramePageComponent';
import {AjaxService} from '../../../../../core/ajax/ajax.service';
import {MsgService} from '../../../../../core/msg/msg.service';
import {StdMaterialRefuseComponent} from '../../material/std-material-refuse/std-material-refuse.component';
import {BsModalService} from 'ngx-bootstrap';
import {StdRegModifyComponent} from '../std-reg-modify/std-reg-modify.component';
import {StdRegAgentComponent} from '../std-reg-agent/std-reg-agent.component';
import {AjaxComponent} from '../../../../../core/ajax/ajax.component';
import {StdRegAspectComponent} from '../std-reg-aspect/std-reg-aspect.component';
import {FrameService} from '../../../../../core/frame/frame.service';
import {StdInterviewModifyComponent} from '../std-interview-modify/std-interview-modify.component';

@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;

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

  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);
  }

  ngOnInit() {
  }

  queryStd() {
    this.std = undefined;
    this.materialArray = [];
    this.materialMap = {};
    debugger;
    AjaxService.requestMap('std/reg/info.htm', {std_id: this.std_id}, (map) => {
      debugger;
      if (map['StdReg'] === undefined) {
        MsgService.errorToaster('获取考生失败，数据同步错误！');
        this.router.navigate(['/art/std/reg/page']);
        return;
      }
      debugger;
      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.errorToaster('未找到符合条件的考生');
        return;
      }
      if (page.records.length > 1) {
        MsgService.errorToaster('有多个符合条件的考生，请从考生列表中查询后进行跳转！');
        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) {
    for (const t of map.TicketArray) {
      map['WrittenArray_' + t.ly_ticket_id] = new Array();
      map['InterviewArray_' + t.ly_ticket_id] = new Array();
      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 = FrameService.shortDateString(w.ly_exam_date);
      // 新的日期
      if (exam_date !== current_date) {
        for (let m of subjectArray) {
          const m_date = FrameService.shortDateString(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 = FrameService.shortMinuteString(w.exam_start_time) + ' - ' + FrameService.shortMinuteString(w.exam_end_time);
      if (exam_time !== current_time) {
        time_row_colspan = 0;
        // 新的日期
        for (let m of subjectArray) {
          const m_time = FrameService.shortMinuteString(m.exam_start_time) + ' - ' + FrameService.shortMinuteString(m.exam_end_time);
          if (m_time === exam_time) {
            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/zone/province/list.htm'});
  }

  /******************
   * 解除微信绑定
   */
  unbinding() {
    MsgService.confirm('确定要解除该考生的微信绑定关系吗？', () => {
      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.confirm('确定要删除该考生报考的专业吗？删除该报考不会触发退款，如需退款请从其他渠道进行退费！', () => {
      AjaxService.requestMap('std/reg/enrol/remove.htm', enrol, () => {
        MsgService.successToaster('考生专业已经删除！');
        this.ajaxEnrol.reload({std_id: this.std.std_id});
      });
    });

  }

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

  }
}
