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

import { ToolService } from "../../services/tool.service";
import { LimitInitiationTimeService } from './limit-initiation-time.service';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { format, startOfMinute, endOfMinute } from 'date-fns';
import { NzMessageService } from 'ng-zorro-antd/message';
@Component({
  selector: "app-limit-initiation-time",
  templateUrl: "./limit-initiation-time.component.html",
  styleUrls: ["./limit-initiation-time.component.less"],
})
export class LimitInitiationTimeComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private limitInitiationTimeService: LimitInitiationTimeService,
    private route: ActivatedRoute,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  userInfo: any = JSON.parse(localStorage.getItem("user")) || {}; //登录用户信息
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  tableHeight: number; //表格动态高
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: any; //当前操作列
  currentHospital; //当前院区

  btnLoading: boolean = false; //提交按钮loading状态

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  modelName = ""; //模态框名称

  changeInpSubject = new Subject(); //防抖

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[1] === 'taskTypeIds'){
        this.getTaskTypeList(true, v[0]);
      }else if(v[1] === 'building'){
        this.getBuildingList(true, v[0]);
      }else if(v[1] === 'department'){
        this.getDepartmentList(true, v[0]);
      }
    });
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    // this.initForm(true);
    this.getList(1);
  }

  // 写入
  variableNamesCreate = ['[$待接单数量$]', '[$执行中数量$]'];
  variableNamesYy = ['[$预约单数量$]'];
  writeIn(content, event, type){
    var element = event.target.parentElement.parentElement.parentElement.parentElement.getElementsByTagName('input')[0];
    if (element.selectionStart || element.selectionStart == '0') {
        var startPos = element.selectionStart;
        var endPos = element.selectionEnd;
        this.validateForm.controls[type].setValue(element.value.substring(0, startPos) + content + element.value.substring(endPos));
        element.focus();
        setTimeout(() => {
          element.setSelectionRange(startPos + content.length, startPos + content.length);
        },0)
    } else {
        var val = element.value + content;
        this.validateForm.controls[type].setValue(val);
        element.focus();
    }
  }

  // 初始化增删改按钮
  coopBtns: any = {};

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      workTimeRule: {
        hosId: this.currentHospital.id,
      },
    };
    this.loading1 = true;
    this.limitInitiationTimeService
      .getFetchDataList(data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list.map(v => ({...v, taskNames: v.taskTypes.map(v => v.taskName.toString())}));
          this.listLength = data.totalNum;
        }
      });
  }

  //打开查询任务类型下拉框
  isLoading:boolean = false;
  taskTypeList:any[] = [];
  getTaskTypeList(flag, keyWord = '') {
    if (flag) {
      let postData = {
        idx: 0,
        sum: 9999,
        taskType: {
          simpleQuery: true,
          taskName: keyWord,
          hosId: {
            id: this.currentHospital.id,
          },
        }
      };
      this.isLoading = true;
      this.limitInitiationTimeService
      .getTaskTypes(postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.taskTypeList = data.list;
        }
      });
    }
  }

  //打开查询楼栋下拉框
  buildingList:any[] = [];
  getBuildingList(flag, keyWord = '') {
    if (flag) {
      let postData = {
        idx: 0,
        sum: 9999,
        building: {
          simpleQuery: true,
          buildingName: keyWord,
          cascadeHosId: this.currentHospital.id,
        }
      };
      this.isLoading = true;
      this.limitInitiationTimeService
      .getBuildings(postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.buildingList = data.list;
        }
      });
    }
  }

  //打开查询科室下拉框
  departmentList:any[] = [];
  getDepartmentList(flag, keyWord = '') {
    if (flag) {
      let postData = {
        idx: 0,
        sum: 9999,
        department: {
          searchType: 1,// 简单查询
          dept: keyWord,
          cascadeHosId: this.currentHospital.id,
        }
      };
      this.isLoading = true;
      this.limitInitiationTimeService
      .getDepartments(postData)
      .subscribe((data) => {
        this.isLoading = false;
        if (data.status == 200) {
          this.departmentList = data.list;
        }
      });
    }
  }

  //搜索
  changeInp(e, type) {
    this.isLoading = true;
    this.changeInpSubject.next([e, type]);
  }

  // 新增弹框
  addModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modal = true;
    this.initForm();
    this.changeLimitType(this.validateForm.value.limitType, true);
    this.changeLimitNum(this.validateForm.value.limitNum, true);
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    // this.initForm();
  }

  //服务时间选择
  // 禁用的小时
  startTimeHourdis() {
    return [];
  }
  endTimeHourdis() {
    return [];
  }

  // 禁用的分钟
  startTimeMindis() {
    return [];
  }
  endTimeMindis() {
    return [];
  }

  timeChange(e: boolean, type: string) {
    if (!e && this.validateForm.value[type]) {
      let hour = new Date(this.validateForm.value[type]).getHours();
      // let minute = new Date(this.validateForm.value[type]).getMinutes();
      if (type == "startTime") {
        this.endTimeHourdis = () => this.generateArray(0, hour);
        // this.endTimeMindis = () => this.generateArray(0, minute + 1);
      } else if (type == "endTime") {
        this.startTimeHourdis = () => this.generateArray(hour + 1, 24);
        // this.startTimeMindis = () => this.generateArray(minute, 60);
      }
    }
  }

  /**
   * 生成一个从 start 到 end 的连续数组
   * @param start
   * @param end
   */
  generateArray(start, end) {
    return Array.from(new Array(end).keys()).slice(start);
  }

  // 初始化新增form表单
  initForm() {
    this.endTimeHourdis = () => [];
    this.endTimeMindis = () => [];
    this.startTimeHourdis = () => [];
    this.startTimeMindis = () => [];
    this.validateForm = this.fb.group({
      taskTypeIds: [null, [Validators.required]],
      limitAllDept: [1, [Validators.required]],
      buildingIds: [[]],
      deptIds: [[]],
      limitType: [1, [Validators.required]],
      startTime: [null],
      endTime: [null],
      remark: ['', [Validators.required]],
      // new
      limitNum: [0, [Validators.required]],
      limitTime: ['0.5', [Validators.required]],
      fqLimitNum: [0, [Validators.required]],
      yyLimitNum: [0, [Validators.required]],
      createRemark: ['', [Validators.required]],
      yyLimitRemark: ['', [Validators.required]],
      limitDispatchDesk: [0, [Validators.required]],
    });
  }

  // 修改是否限制所有科室
  changeLimitAllDept(e){
    this.validateForm.controls.buildingIds.setValue([]);
    this.validateForm.controls.deptIds.setValue([]);
  }

  // 修改限制方式
  changeLimitType(e, isFirst = false){
    console.log(e);
    if(!isFirst){
      this.validateForm.controls.limitDispatchDesk.setValue(0);
    }
    if(e == 1){
      // 仅提示允许建单
      this.validateForm.get('limitDispatchDesk')!.clearValidators();
      this.validateForm.get('limitDispatchDesk')!.markAsPristine();
    }else if(e == 2){
      // 提示不允许建单
      this.validateForm.get('limitDispatchDesk')!.setValidators(Validators.required);
      this.validateForm.get('limitDispatchDesk')!.markAsDirty();
    }
    this.validateForm.get('limitDispatchDesk')!.updateValueAndValidity();
  }

  // 修改是否限制发起数量
  changeLimitNum(e, isFirst = false){
    console.log(e);
    if(!isFirst){
      this.validateForm.controls.limitTime.setValue('0.5');
      this.validateForm.controls.fqLimitNum.setValue(0);
      this.validateForm.controls.yyLimitNum.setValue(0);
      this.validateForm.controls.createRemark.setValue('');
      this.validateForm.controls.yyLimitRemark.setValue('');
      this.validateForm.controls.remark.setValue('');
    }
    if(e == 1){
      //  是
      this.validateForm.controls.limitAllDept.setValue(1);

      this.validateForm.get('limitTime')!.setValidators(Validators.required);
      this.validateForm.get('limitTime')!.markAsDirty();

      this.validateForm.get('fqLimitNum')!.setValidators(Validators.required);
      this.validateForm.get('fqLimitNum')!.markAsDirty();

      this.validateForm.get('yyLimitNum')!.setValidators(Validators.required);
      this.validateForm.get('yyLimitNum')!.markAsDirty();

      this.validateForm.get('createRemark')!.setValidators(Validators.required);
      this.validateForm.get('createRemark')!.markAsDirty();

      this.validateForm.get('yyLimitRemark')!.setValidators(Validators.required);
      this.validateForm.get('yyLimitRemark')!.markAsDirty();

      this.validateForm.get('remark')!.clearValidators();
      this.validateForm.get('remark')!.markAsPristine();
    }else if(e == 0){
      // 否
      this.validateForm.get('limitTime')!.clearValidators();
      this.validateForm.get('limitTime')!.markAsPristine();

      this.validateForm.get('fqLimitNum')!.clearValidators();
      this.validateForm.get('fqLimitNum')!.markAsPristine();

      this.validateForm.get('yyLimitNum')!.clearValidators();
      this.validateForm.get('yyLimitNum')!.markAsPristine();

      this.validateForm.get('createRemark')!.clearValidators();
      this.validateForm.get('createRemark')!.markAsPristine();

      this.validateForm.get('yyLimitRemark')!.clearValidators();
      this.validateForm.get('yyLimitRemark')!.markAsPristine();

      this.validateForm.get('remark')!.setValidators(Validators.required);
      this.validateForm.get('remark')!.markAsDirty();
    }
    this.validateForm.get('limitDispatchDesk')!.updateValueAndValidity();
    this.validateForm.get('fqLimitNum')!.updateValueAndValidity();
    this.validateForm.get('yyLimitNum')!.updateValueAndValidity();
    this.validateForm.get('createRemark')!.updateValueAndValidity();
    this.validateForm.get('yyLimitRemark')!.updateValueAndValidity();
    this.validateForm.get('remark')!.updateValueAndValidity();
  }

  // 新增/编辑表单提交
  submitForm(): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }
    if(this.validateForm.value.limitAllDept == 0 && !this.validateForm.value.buildingIds.length && !this.validateForm.value.deptIds.length){
      this.message.info('请设置楼栋或科室！');
      return;
    }
    if((/^\s+/.test(this.validateForm.value.remark) || /\s+$/.test(this.validateForm.value.remark)) && !this.validateForm.value.remark.trim()){
      this.message.info('请设置提示备注！');
      return;
    }

    if(this.validateForm.value.startTime.getTime() >= this.validateForm.value.endTime.getTime()){
      this.message.info('开始时间不能大于结束时间！');
      return;
    }

    this.btnLoading = true;
    let data = {};

    if (this.add) {
      //增加
      data = {
        taskTypeIds: this.validateForm.value.taskTypeIds.toString(),
        limitAllDept: this.validateForm.value.limitAllDept,
        buildingIds: this.validateForm.value.buildingIds.length ? this.validateForm.value.buildingIds.toString() : null,
        deptIds: this.validateForm.value.deptIds.length ? this.validateForm.value.deptIds.toString() : null,
        limitType: this.validateForm.value.limitType,
        startTime: format(startOfMinute(this.validateForm.value.startTime), "yyyy-MM-dd HH:mm:ss"),
        endTime: format(endOfMinute(this.validateForm.value.endTime), "yyyy-MM-dd HH:mm:ss"),
        remark: this.validateForm.value.remark.trim(),
        hosId: this.currentHospital.id,
        limitNum: this.validateForm.value.limitNum,
        limitTime: this.validateForm.value.limitTime,
        fqLimitNum: this.validateForm.value.fqLimitNum,
        yyLimitNum: this.validateForm.value.yyLimitNum,
        createRemark: this.validateForm.value.createRemark.trim(),
        yyLimitRemark: this.validateForm.value.yyLimitRemark.trim(),
        limitDispatchDesk: this.validateForm.value.limitDispatchDesk,
      };
    } else {
      //编辑
      data = {
        ...this.coopId,
        taskTypeIds: this.validateForm.value.taskTypeIds.toString(),
        limitAllDept: this.validateForm.value.limitAllDept,
        buildingIds: this.validateForm.value.buildingIds.length ? this.validateForm.value.buildingIds.toString() : null,
        deptIds: this.validateForm.value.deptIds.length ? this.validateForm.value.deptIds.toString() : null,
        limitType: this.validateForm.value.limitType,
        startTime: format(startOfMinute(this.validateForm.value.startTime), "yyyy-MM-dd HH:mm:ss"),
        endTime: format(endOfMinute(this.validateForm.value.endTime), "yyyy-MM-dd HH:mm:ss"),
        remark: this.validateForm.value.remark.trim(),
        hosId: this.currentHospital.id,
        limitNum: this.validateForm.value.limitNum,
        limitTime: this.validateForm.value.limitTime,
        fqLimitNum: this.validateForm.value.fqLimitNum,
        yyLimitNum: this.validateForm.value.yyLimitNum,
        createRemark: this.validateForm.value.createRemark.trim(),
        yyLimitRemark: this.validateForm.value.yyLimitRemark.trim(),
        limitDispatchDesk: this.validateForm.value.limitDispatchDesk,
      };
    }
    this.limitInitiationTimeService
      .simplePost("addData", "workTimeRule", data)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hideAddModal();
        if (result.status == 200) {
          if (this.add) {
            this.showPromptModal("新增", true, "");
            this.listLength++;
          }else{
            this.showPromptModal("编辑", true, "");
          }
        } else {
          this.showPromptModal(this.add ? '新增' : '修改', false, result.msg);
        }
      });
  }

  // 编辑
  edit(data) {
    console.log(data);
    this.initForm();
    this.changeLimitType(data.limitType, false);
    this.changeLimitNum(data.limitNum, false);
    this.modelName = "编辑";
    this.add = false;
    this.modal = true;
    this.coopId = data;

    this.taskTypeList = data.taskTypes || [];
    this.validateForm.controls.taskTypeIds.setValue(this.taskTypeList.map(v => v.id)); //任务类型

    this.validateForm.controls.limitAllDept.setValue(data.limitAllDept); //是否限制所有科室

    this.buildingList = data.buildingList || [];
    this.validateForm.controls.buildingIds.setValue(this.buildingList.map(v => v.id)); //楼栋

    this.departmentList = data.deptList || [];
    this.validateForm.controls.deptIds.setValue( this.departmentList.map(v => v.id)); //科室
    this.validateForm.controls.limitType.setValue(data.limitType); //限制方式
    if (data.startTime && data.endTime) {
      this.validateForm.controls.startTime.setValue(new Date(data.startTime));
      this.validateForm.controls.endTime.setValue(new Date(data.endTime));
    }
    this.validateForm.controls.remark.setValue(data.remark); //提示备注

    this.validateForm.controls.limitNum.setValue(data.limitNum);
    this.validateForm.controls.limitTime.setValue(data.limitTime);
    this.validateForm.controls.fqLimitNum.setValue(data.fqLimitNum);
    this.validateForm.controls.yyLimitNum.setValue(data.yyLimitNum);
    this.validateForm.controls.createRemark.setValue(data.createRemark);
    this.validateForm.controls.yyLimitRemark.setValue(data.yyLimitRemark);
    this.validateForm.controls.limitDispatchDesk.setValue(data.limitDispatchDesk);
  }

  // 展示信息提示框（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(0);
  }

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    this.confirmDelType = type;
    this.delModal = true;
    this.coopId = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.limitInitiationTimeService
        .simplePost("rmvData", "workTimeRule", [this.coopId.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            if (
              this.listOfData.length == 1 &&
              this.pageIndex == Math.ceil(this.listLength / this.pageSize)
            ) {
              this.listLength--;
              if (this.listLength === 0) {
                this.pageIndex = 1;
              } else {
                this.pageIndex = Math.ceil(this.listLength / this.pageSize);
              }
            }
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }
}

