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

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

  userInfo: any = JSON.parse(localStorage.getItem("user")) || {}; //登录用户信息
  hosId;
  createUser = "";
  scheduleClasses = []; // 用户列表
  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();
    this.getScheduleClass();
  }

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

  // 表格数据
  loading1 = false;
  getList() {
    let postData = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      workOrderMessageSettingsDTO: {
        hosId: this.hosId,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "WorkOrderMessageSettings", postData)
      .subscribe((data) => {
        this.loading1 = false;
        if (data["status"] == 200) {
          this.listOfData = data["list"].data;
          this.listOfData.forEach((item) => {
            item.applicableShiftName = Object.values(
              JSON.parse(item.applicableShift)
            ).join("，");
          });
          this.listLength = data["totalNum"];
        }
      });
  }
  //关闭编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }
  // 初始化form表单
  initForm() {
    this.validateForm = this.fb.group({
      applicableShift: [null, [Validators.required]], //班次
    });
  }
  // 表单提交
  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 applicableShift: any = {};
    this.scheduleClasses.forEach((item) => {
      this.validateForm.value.applicableShift.forEach((v) => {
        if (item.id == v) {
          applicableShift[item.id] = item.name;
        }
      });
    });
    let postData: any = {
      workOrderMessageSettingsDTO: {
        status: this.dataContent.status,
        applicableShift: JSON.stringify(applicableShift),
        id: this.dataContent.id,
      },
    };
    this.mainService
      .simplePost("addData", "WorkOrderMessageSettings", 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"]);
        }
      });
  }
  // 获取班次
  getScheduleClass() {
    this.mainService
      .getFetchDataList("configuration", "scheduleClass", {
        idx: 0,
        sum: 9999,
        scheduleClass: {
          hosId: this.hosId,
        },
      })
      .subscribe((result) => {
        if (result.status == 200) {
          this.scheduleClasses = result.list;
        }
      });
  }
  // 编辑
  edit(data) {
    this.dataContent = data;
    this.modal = true;
    this.validateForm.controls.applicableShift.setValue(
      Object.keys(JSON.parse(data.applicableShift))
    ); //班次
  }

  // 展示信息提示框（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 === "switch") {
      //启用/停用
      let postData: any = {
        workOrderMessageSettingsDTO: {
          status: this.dataContent.status == 1 ? 0 : 1,
          applicableShift: this.dataContent.applicableShift,
          id: this.dataContent.id,
        },
      };
      this.mainService
        .simplePost("addData", "WorkOrderMessageSettings", 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"]);
          }
        });
    }
  }
}
