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";
import { format } from "date-fns";
@Component({
  selector: "app-regular-off-duty",
  templateUrl: "./regular-off-duty.component.html",
  styleUrls: ["./regular-off-duty.component.less"],
})
export class RegularOffDutyComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private tool: ToolService
  ) {}

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

  oneOption: any; //适用日期类型
  btnLoading: boolean = false; //提交按钮loading状态

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

  ngOnInit() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
  }
  // 立即执行
  coopItem: any = {};
  execModal: boolean = false;
  // 打开立即执行模态框
  openExecModal(item) {
    this.coopItem = item;
    this.execModal = true;
  }
  // 确认立即执行
  confirmExec() {
    this.btnLoading = true;
    let posData = this.coopItem.classesIds.split(",");
    this.mainService.executeNowClassesJob(posData).subscribe((result: any) => {
      this.closeExecModal();
      this.btnLoading = false;
      if (result.status == 200) {
        this.showPromptModal("当前班次下班", true, "");
      } else {
        this.showPromptModal("当前班次下班", false, result.msg);
      }
    });
  }
  // 关闭立即执行模态框
  closeExecModal() {
    this.execModal = false;
  }
  // 新增/编辑弹框
  add: boolean; //true:新增；false:编辑
  addModal() {
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  changeForm(flag) {
    if (flag) {
      this.changeInp("no", "form");
    }
  }
  // 边输边搜节流阀
  isLoading = false;
  changeInp(dept, type) {
    if (!dept) {
      return;
    }
    if (dept === "no") {
      dept = "";
    }
    this.isLoading = true;
    this.searchUsers(dept, type);
  }
  // 搜索班次
  snum = 0;
  searchUsers(dept, type) {
    let data = {
      scheduleClass: {
        hospital: { id: this.hosId.toString() },
      },
      idx: 0,
      sum: 20,
    };
    this.snum++;
    this.mainService
      .getFetchDataList("configuration", "scheduleClass", data)
      .subscribe((data) => {
        this.snum--;
        if (data.status == 200) {
          if (type === "form") {
            if (this.snum === 0) {
              this.isLoading = false;
            }
            this.classes = data.list;
          }
        }
      });
  }

  // 初始化权限按钮
  coopBtns: any = {};

  // 表格数据
  loading1 = false;
  getList() {
    let postData = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      messageJob: {
        hospital: this.hosId,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "classesJob", postData)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listOfData.forEach((item) => {
            if (item.timeStep == "week") {
              let weeks = [
                "周一",
                "周二",
                "周三",
                "周四",
                "周五",
                "周六",
                "周日",
              ];
              item.weekName = weeks[item.extra1 - 1];
            }
            item.usersName = item.classes.map((value) => value.name).join();
          });
          this.listLength = data.totalNum;
        }
      });
  }
  //关闭编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }
  // 初始化form表单
  initForm() {
    this.validateForm = this.fb.group({
      title: [null, [Validators.required]], //标题
      timeStep: ["day", [Validators.required]], //重复策略
      executeTime: [null, [Validators.required]], //定时发送时间
      active: [false, [Validators.required]], //是否启用
      classIds: [null, [Validators.required]], //定时下班班次
    });
  }
  //修改重复策略
  months = [...Array(32).keys()].slice(1);
  timeStepChange(e) {
    switch (e) {
      case "day":
        this.validateForm.removeControl("doWeek");
        this.validateForm.removeControl("doMonth");
        this.validateForm.removeControl("doYear");
        break;
      case "week":
        this.validateForm.addControl(
          "doWeek",
          new FormControl(null, Validators.required)
        );
        this.validateForm.removeControl("doMonth");
        this.validateForm.removeControl("doYear");
        break;
      case "month":
        this.validateForm.addControl(
          "doMonth",
          new FormControl(null, Validators.required)
        );
        this.validateForm.removeControl("doWeek");
        this.validateForm.removeControl("doYear");
        break;
      case "year":
        this.validateForm.addControl(
          "doYear",
          new FormControl(null, Validators.required)
        );
        this.validateForm.removeControl("doWeek");
        this.validateForm.removeControl("doMonth");
        break;
    }
  }

  // 表单提交
  submitForm(): void {
    this.btnLoading = true;
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      this.btnLoading = false;
      return;
    }
    let postData: any = {};
    if (this.add) {
      postData = {
        hospital: this.hosId,
        title: this.validateForm.value.title,
        executeTime: new Date(this.validateForm.value.executeTime).getTime(),
        classesIds: this.validateForm.value.classIds.join(),
        active: this.validateForm.value.active,
        key: "regularOffDuty",
        timeStep: this.validateForm.value.timeStep,
      };
    } else {
      postData = {
        title: this.validateForm.value.title,
        executeTime: new Date(this.validateForm.value.executeTime).getTime(),
        classesIds: this.validateForm.value.classIds.join(),
        active: this.validateForm.value.active,
        key: this.dataContent.key,
        id: this.dataContent.id,
        timeStep: this.validateForm.value.timeStep,
      };
    }
    if (this.validateForm.value.timeStep == "day") {
      delete postData.extra1;
    } else if (this.validateForm.value.timeStep == "week") {
      postData.extra1 = this.validateForm.value.doWeek;
    } else if (this.validateForm.value.timeStep == "month") {
      postData.extra1 = this.validateForm.value.doMonth;
    } else if (this.validateForm.value.timeStep == "year") {
      delete postData.extra1;
      postData.executeTime = new Date(
        format(new Date(this.validateForm.value.doYear), "yyyy-MM-dd") +
          " " +
          format(new Date(this.validateForm.value.executeTime), "HH:mm:ss")
      ).getTime();
    }
    this.mainService
      .simplePost(this.add ? "addData" : "updData", "classesJob", postData)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideAddModal();
        this.initForm();
        if (data.status == 200) {
          this.listLength++;
          this.showPromptModal("修改", true, "");
        } else {
          this.showPromptModal("修改", false, data.msg);
        }
      });
  }

  // 编辑
  maskFlag: any = false;
  edit(data) {
    this.add = false;
    this.dataContent = data;
    this.validateForm.controls.executeTime.setValue(new Date(data.executeTime)); //定时发送时间
    this.validateForm.controls.title.setValue(data.title); //标题
    this.validateForm.controls.active.setValue(data.active); //是否启用
    this.timeStepChange(data.timeStep);
    this.validateForm.controls.timeStep.setValue(data.timeStep); //重复策略
    if (data.timeStep == "year") {
      this.validateForm.controls.doYear.setValue(
        format(data.executeTime, "yyyy-MM-dd HH:mm:ss")
      );
    } else if (data.timeStep == "month") {
      this.validateForm.controls.doMonth.setValue(data.extra1);
    } else if (data.timeStep == "week") {
      this.validateForm.controls.doWeek.setValue(data.extra1);
    }
    // --------定时下班班次---
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .getFetchDataList("configuration", "scheduleClass", {
        idx: 0,
        sum: 20,
        user: {
          hosId: this.hosId,
        },
      })
      .subscribe((result) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.modal = true;
        if (result.status == 200) {
          let add = data.classes.filter(
            (item) => !result.list.some((ele) => ele.id == item.id)
          );
          this.classes = add.concat(result.list);
          this.validateForm.controls.classIds.setValue(
            data.classes.map((v) => v.id.toString())
          ); //定时下班班次
        }
      });
    // --------/定时下班班次---
  }

  // 展示信息提示框（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; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  confirmDelIsSwitch: boolean; //启用/停用
  showDelModal(
    dataContent,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
    isSwitch?: boolean
  ) {
    this.confirmDelIsSwitch = isSwitch;
    this.confirmDelType = type;
    this.delModal = true;
    this.dataContent = dataContent;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏
  hideDelModal() {
    this.delModal = false;
  }
  // 确认
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.mainService
        .simplePost("rmvData", "classesJob", [this.dataContent.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);
          }
        });
    } else if (this.confirmDelType === "switch") {
      //启用/停用
      let postData = {
        id: this.dataContent.id,
        title: this.dataContent.title,
        executeTime: this.dataContent.executeTime,
        classesIds: this.dataContent.classes.map((v) => v.id).join(),
        active: this.dataContent.active ? false : true,
        key: this.dataContent.key,
      };
      this.mainService
        .simplePost("updData", "classesJob", postData)
        .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);
          }
        });
    }
  }
}
