import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { FormBuilder, Validators, FormGroup, FormControl } from '@angular/forms';

import { MainService } from "../../services/main.service"
import { OverlayScrollbarsComponent } from 'overlayscrollbars-ngx';
import { ToolService } from '../../services/tool.service';
import { NzMessageService } from 'ng-zorro-antd';
@Component({
  selector: 'app-classes-management',
  templateUrl: './classes-management.component.html',
  styleUrls: ['./classes-management.component.less']
})
export class ClassesManagementComponent implements OnInit {
  @ViewChild('osComponentRef1', { read: OverlayScrollbarsComponent, static: false })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private tool: ToolService,
    private msg: NzMessageService
  ) { }

  userInfo: any = JSON.parse(localStorage.getItem('user')) || {};//登录用户信息

  hospital: any = null;//院区搜索框
  listOfData: any[] = [];//表格数据
  pageIndex: number = 1;//表格当前页码
  pageSize: number = 10;//表格每页展示条数
  listLength: number = 10;//表格总数据量
  modal: boolean = false;//新增/编辑模态框
  add: boolean;//true:新增；false:编辑
  validateForm: FormGroup;//新增/编辑表单
  coopId: number;//当前操作列id
  oneOption: any;//适用日期类型
  btnLoading: boolean = false;//提交按钮loading状态

  promptContent: string;//操作提示框提示信息
  ifSuccess: boolean;//操作成功/失败
  promptInfo: string;//操作结果提示信息
  promptModalShow: boolean;//操作提示框是否展示
  demoValue: number = 0;

  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getAllHospital()
    this.initForm();
  }

  // 初始化增删改按钮
  coopBtns: any = {};
  // 修改适用日期类型
  logDateType(value: object[]): void {
    console.log(value);
  }


  // 获取当前院区
  getAllHospital() {
    this.hospital = this.tool.getCurrentHospital().id + "";
    this.getList();
  }


  // 表格数据
  loading1 = false;
  getList(num?: number) {
    if (num !== undefined) {
      this.pageIndex = num;
    }
    var data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      scheduleClass: { hospital: { id: this.hospital || '' } }
    }
    this.loading1 = true;
    this.mainService.getFetchDataList('configuration', 'scheduleClass', data).subscribe(data => {
      this.loading1 = false;
      this.listOfData = data.list;
      this.listLength = data.totalNum;
    })
  }

  // 新增/编辑弹框
  addModal() {
    this.add = true;
    this.modal = true;
    this.initForm();
  }
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }
  // 初始化新增form表单
  initForm() {
    this.oneOption = [
      { label: '工作日', value: '工作日', checked: false },
      { label: '节假日', value: '节假日', checked: false },
    ]
    this.validateForm = this.fb.group({
      classesName: [null, [Validators.required]],
      description: [null, [Validators.required]],
      bindCall: [0, [Validators.required]],
      bindPriority: [0, [Validators.required]],
      datesType: [null, [this.dateValidator]],
      // 时间段1
      timerF1: [null, [Validators.required]],
      timerT1: [null, [Validators.required]],
      // 时间段2
      timerF2: [null, []],
      timerT2: [null, []],
      // 时间段3
      timerF3: [null, []],
      timerT3: [null, []],
    });
  }

  //创建自定义校验规则dateValidator，用于复选框组校验时调用。
  selectedDate: any = [];
  dateValidator = (control: FormControl): { [s: string]: boolean } => {
    this.selectedDate = [];
    for (const i in control.value) {
      if (control.value[i].checked) {
        this.selectedDate.push(control.value[i]);
      }
    }
    if (this.selectedDate.length == 0) {
      return { required: true };
    }
  };

  // 时间段选择器校验
  timer1Validator = (): { [s: string]: boolean } => {
    let that = this;
    if (that.validateForm && that.validateForm.value) {
      if ((!that.validateForm.value.timerMF1 && that.validateForm.value.timerMF1 != 0) || (!that.validateForm.value.timerSF1 && that.validateForm.value.timerSF1 != 0) || (!that.validateForm.value.timerMT1 && that.validateForm.value.timerMT1 != 0) || (!that.validateForm.value.timerST1 && that.validateForm.value.timerST1 != 0)) {
        return { required: true };
      }

    }

  };
  timer1Validator1 = (): { [s: string]: boolean } => {
    let that = this;
    if (that.validateForm && that.validateForm.value) {
      if (!that.validateForm.value.timer1 || !that.validateForm.value.timer1) {
        return { required: true };
      }

    }

  };


  // 新增表单提交
  submitForm(): void {
    var that = this;
    for (const i in that.validateForm.controls) {
      that.validateForm.controls[i].markAsDirty();
      that.validateForm.controls[i].updateValueAndValidity();
    }
    if (that.selectedDate) {
      var arr = [];
      this.validateForm.value.datesType.forEach(e => {
        if (e.checked) {
          arr.push(e.label)
        }
      });
      if (arr.length == 2) {
        that.validateForm.value.datesType = 3
      } else {
        if (arr[0] == '工作日') {
          that.validateForm.value.datesType = 1
        } else {
          that.validateForm.value.datesType = 2
        }
      }
    }
    console.log(that.validateForm)
    if (that.validateForm.invalid) return;
    let times: any = [];
    times = [
      {
        startTime: "2019-08-28 " + that.validateForm.value.timerF1.getHours() + ":" + that.validateForm.value.timerF1.getMinutes() + ":34",
        endTime: "2019-08-28 " + that.validateForm.value.timerT1.getHours() + ":" + that.validateForm.value.timerT1.getMinutes() + ":37"
      }
    ]
    let data = {
      scheduleClass:
      {
        name: that.validateForm.value.classesName,
        describe: that.validateForm.value.description,
        bindCall: that.validateForm.value.bindCall,
        bindPriority: that.validateForm.value.bindPriority,
        scheduleClassTimes: times,
        type: that.validateForm.value.datesType,
        hospital: { id: this.hospital },
        deleteFlag: 0
      }
    }

    if (that.validateForm.value.timerF2 && that.validateForm.value.timerT2) {
      data.scheduleClass.scheduleClassTimes.push({
        startTime: "2019-08-28 " + that.validateForm.value.timerF2.getHours() + ":" + that.validateForm.value.timerF2.getMinutes() + ":34",
        endTime: "2019-08-28 " + that.validateForm.value.timerT2.getHours() + ":" + that.validateForm.value.timerT2.getMinutes() + ":37"
      })
    }
    if (that.validateForm.value.timerF3 && that.validateForm.value.timerT3) {
      data.scheduleClass.scheduleClassTimes.push({
        startTime: "2019-08-28 " + that.validateForm.value.timerF3.getHours() + ":" + that.validateForm.value.timerF3.getMinutes() + ":34",
        endTime: "2019-08-28 " + that.validateForm.value.timerT3.getHours() + ":" + that.validateForm.value.timerT3.getMinutes() + ":37"
      })
    }
    console.log(data)
    // return;

    if (!that.add) {
      // 编辑
      data.scheduleClass['id'] = that.coopId;
      data.scheduleClass.scheduleClassTimes[0]['id'] = that.coopDatas.scheduleClassTimes[0].id;
      // 删除班次
      if (!data.scheduleClass.scheduleClassTimes[1] && that.coopDatas.scheduleClassTimes[1]) {
        data.scheduleClass.scheduleClassTimes.push({});
        // data.scheduleClass.scheduleClassTimes[1]['id'] = that.coopDatas.scheduleClassTimes[1].id;
      }
      if (!data.scheduleClass.scheduleClassTimes[2] && that.coopDatas.scheduleClassTimes[2]) {
        data.scheduleClass.scheduleClassTimes.push({});
        // data.scheduleClass.scheduleClassTimes[2]['id'] = that.coopDatas.scheduleClassTimes[2].id;
      }

      if (that.coopDatas.scheduleClassTimes[1]) {
        data.scheduleClass.scheduleClassTimes[1]['id'] = that.coopDatas.scheduleClassTimes[1].id;
      }
      if (that.coopDatas.scheduleClassTimes[2]) {
        data.scheduleClass.scheduleClassTimes[2]['id'] = that.coopDatas.scheduleClassTimes[2].id;
      }

    }
    console.log(data)
    that.btnLoading = true;
    that.mainService.coopTypeConfig((that.add ? 'addData' : 'updData'), 'scheduleClass', data).subscribe(data => {
      that.btnLoading = false;
      that.hideAddModal();
      that.initForm();
      if (data.status == 200) {
        that.listLength++;
        that.showPromptModal((that.add ? '新增' : '编辑'), true, '');
      } else {
        that.showPromptModal((that.add ? '新增' : '编辑'), false, data.msg);
      }
    })
  }

  // 编辑
  coopDatas;
  edit(data) {
    console.log(data);
    this.coopDatas = data;
    this.add = false;
    this.modal = true;
    this.coopId = data.id;
    this.validateForm.controls.classesName.setValue(data.name);
    this.validateForm.controls.description.setValue(data.describe);
    this.validateForm.controls.bindCall.setValue(data.bindCall);
    this.validateForm.controls.bindPriority.setValue(data.bindPriority);
    if (data.type == 1) {
      this.oneOption[0]['checked'] = true;
    } else if (data.type == 2) {
      this.oneOption[1]['checked'] = true;
    } else {
      this.oneOption[0]['checked'] = true;
      this.oneOption[1]['checked'] = true;
    }

    let timeF1 = new Date(2018, 11, 12, data.scheduleClassTimes[0].startTime.substring(11, 13), data.scheduleClassTimes[0].startTime.substring(14, 16));
    let timeT1 = new Date(2018, 11, 12, data.scheduleClassTimes[0].endTime.substring(11, 13), data.scheduleClassTimes[0].endTime.substring(14, 16));
    this.validateForm.controls.timerF1.setValue(timeF1)
    this.validateForm.controls.timerT1.setValue(timeT1)
    if (data.scheduleClassTimes[1]) {
      let timeF2 = new Date(2018, 11, 12, data.scheduleClassTimes[1].startTime.substring(11, 13), data.scheduleClassTimes[1].startTime.substring(14, 16));
      let timeT2 = new Date(2018, 11, 12, data.scheduleClassTimes[1].endTime.substring(11, 13), data.scheduleClassTimes[1].endTime.substring(14, 16));
      this.validateForm.controls.timerF2.setValue(timeF2)
      this.validateForm.controls.timerT2.setValue(timeT2)
    }
    if (data.scheduleClassTimes[2]) {
      let timeF3 = new Date(2018, 11, 12, data.scheduleClassTimes[2].startTime.substring(11, 13), data.scheduleClassTimes[2].startTime.substring(14, 16));
      let timeT3 = new Date(2018, 11, 12, data.scheduleClassTimes[2].endTime.substring(11, 13), data.scheduleClassTimes[2].endTime.substring(14, 16));
      this.validateForm.controls.timerF3.setValue(timeF3)
      this.validateForm.controls.timerT3.setValue(timeT3)
    }
  }

  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);

    this.getList();
  }

  // 删除班次
  delModal: boolean = false;//删除模态框
  showDelModal(id) {
    this.delModal = true;
    this.coopId = id;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.delModal = false;
    this.btnLoading = true;
    this.mainService.coopData('rmvData', 'scheduleClass', [this.coopId]).subscribe(data => {
      this.btnLoading = false;
      if (data.status == 200) {
        if (this.listOfData.length == 1 && this.pageIndex == Math.ceil(this.listLength / this.pageSize)) {
          this.listLength--;
          this.pageIndex = Math.ceil(this.listLength / this.pageSize);
        }
        this.showPromptModal('删除', true, '');
      } else {
        this.showPromptModal('删除', false, data.msg);
      }
    })
  }
  // 刷新缓存
  refreshLoading = false;
  refreshTaskType() {
    this.refreshLoading = true;
    this.mainService.refreshTaskType().subscribe(result => {
      this.refreshLoading = false;
      if (result.state == 200) {
        this.msg.create('success', '刷新缓存成功！');
      } else {
        this.msg.create('error', result.msg);
      }
    })
  }
}
