import { Component, OnInit } from "@angular/core";
import { ActivatedRoute } from "@angular/router";
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { MainService } from "../../../services/main.service";
import { Validators, FormGroup, FormBuilder } from '@angular/forms';
import { ToolService } from 'src/app/services/tool.service';
import { NzMessageService } from 'ng-zorro-antd';

@Component({
  selector: "app-configuration-priority",
  templateUrl: "./configuration-priority.component.html",
  styleUrls: ["./configuration-priority.component.less"],
})
export class ConfigurationPriorityComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private mainService: MainService,
    private fb: FormBuilder,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  coopData: any = {}; //当前操作列
  currentHospital; //当前院区

  formatterMinute = (value: number) => `${value} 分钟`;
  parserMinute = (value: string) => value.replace(' 分钟', '');

  ngOnInit() {
    this.currentHospital = this.tool.getCurrentHospital();
    // 优先级
    setTimeout(() => {
      this.tablePriorityHeight = document.querySelector('#priorityTable').clientHeight - document.querySelector('#priorityTable .list-template__top').clientHeight - 8 - document.querySelector('#priorityTable .thead').clientHeight;
    }, 0)
    this.getPriorityList();
    this.getClassList(1);
    this.getClassList(2);
  }

  // 新增优先级弹框
  modelName = ""; //模态框名称
  modalPriority: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  addPriorityModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modalPriority = true;
    this.initPriorityForm();
  }
  //关闭新增/编辑弹框
  hidePriorityModal() {
    this.modalPriority = false;
  }

  // 编辑
  editPriority(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modalPriority = true;
    this.initPriorityForm();
    this.coopData = data;
    this.validatePriorityForm.controls.name.setValue(data.name);
    this.validatePriorityForm.controls.orders.setValue(data.orders);
    this.validatePriorityForm.controls.responseTime.setValue(data.responseTime);
    this.validatePriorityForm.controls.handleTime.setValue(data.handleTime);
    this.validatePriorityForm.controls.holidayClassId.setValue(data.holidayClassId);
    this.validatePriorityForm.controls.workdayClassId.setValue(data.workdayClassId);
  }

  // 新增/编辑表单提交
  btnLoading: boolean = false; //提交按钮loading状态
  submitPriorityForm(): void {
    for (const i in this.validatePriorityForm.controls) {
      this.validatePriorityForm.controls[i].markAsDirty();
      this.validatePriorityForm.controls[i].updateValueAndValidity();
    }
    if (this.validatePriorityForm.invalid) {
      return;
    }
    console.log(this.validatePriorityForm.value);
    this.btnLoading = true;
    let postData:any = {};

    if (this.add) {
      //增加
      postData = {
        // priority: {
          name: this.validatePriorityForm.value.name,
          orders: this.validatePriorityForm.value.orders,
          responseTime: this.validatePriorityForm.value.responseTime,
          handleTime: this.validatePriorityForm.value.handleTime,
          holidayClassId: this.validatePriorityForm.value.holidayClassId,
          workdayClassId: this.validatePriorityForm.value.workdayClassId,
        // }
      };
    } else {
      //编辑
      postData = {
        // priority: {
          ...this.coopData,
          ...{
            name: this.validatePriorityForm.value.name,
            orders: this.validatePriorityForm.value.orders,
            responseTime: this.validatePriorityForm.value.responseTime,
            handleTime: this.validatePriorityForm.value.handleTime,
            holidayClassId: this.validatePriorityForm.value.holidayClassId,
            workdayClassId: this.validatePriorityForm.value.workdayClassId,
          }
        // }
      };
    }
    this.mainService
      .simplePost("addData", "priority", postData)
      .subscribe((result) => {
        this.btnLoading = false;
        this.hidePriorityModal();
        let msg = "";
        if (this.add) {
          msg = "新增";
        } else {
          msg = "修改";
        }
        if (result.status == 200) {
          this.showPromptModal(msg, true, '');
        } else {
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }

  // 初始化新增form表单
  validatePriorityForm: FormGroup; //新增/编辑表单
  initPriorityForm() {
    this.validatePriorityForm = this.fb.group({
      name: [null, [Validators.required]],//优先级名称
      orders: [null, [Validators.required]],//排序号
      responseTime: [0, [Validators.required]],//响应时间
      handleTime: [0, [Validators.required]],//解决时间
      holidayClassId: [null],//节假日班次
      workdayClassId: [null],//工作日班次
    });
    console.log(this.validatePriorityForm.controls)
  }

  // 获取优先级列表
  loading1:boolean = false;
  priorityList: any[] = []; //表格数据
  tablePriorityHeight:number = 0;
  getPriorityList() {
    let data = {
      idx: 0,
      sum: 9999,
      priority: {},
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "priority", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.priorityList = data.list || [];
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 获取班次
  isLoading:boolean = false;
  classList1: any = [];
  classList2: any = [];
  // type: 1工作日，2节假日
  getClassList(type:number) {
    let postData = {
      idx: 0,
      sum: 9999,
      scheduleClass: {
        hospital: { id: this.currentHospital.id },
        bindPriority: 1,
        type,
      },
    };
    this.mainService
      .getFetchDataList("simple/data", "scheduleClass", postData)
      .subscribe((data) => {
        this.isLoading = false;
        this['classList' + type] = data.list || [];
      });
  }

  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  showDelModal(
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
  ) {
    this.confirmDelType = type;
    this.delModal = true;
    this.coopData = data;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "delPriority") {
      //删除-优先级
      this.mainService
        .simplePost("rmvData", "priority", [this.coopData.id])
        .subscribe((data) => {
          this.btnLoading = false;
          this.delModal = false;
          if (data.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, data.msg);
          }
        });
    }
  }

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