import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup } from "@angular/forms";
import setSeconds from "date-fns/setSeconds";
import setMinutes from "date-fns/setMinutes";
import setHours from "date-fns/setHours";

import { MainService } from "../../services/main.service";
import { DisabledTimeFn } from "ng-zorro-antd/date-picker/standard-types";
import { ToolService } from "../../services/tool.service";
@Component({
  selector: "app-work-assignment",
  templateUrl: "./work-assignment.component.html",
  styleUrls: ["./work-assignment.component.less"],
})
export class WorkAssignmentComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService
  ) {}

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

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

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  nextSchemeName = ""; //下一个开启的方案名称
  modelName = ""; //模态框名称

  busyList:any[] = [
    {
      id: 1,
      busyContent: '',
      busyMinute: 1,
    },
    {
      id: 2,
      busyContent: '',
      busyMinute: 1,
    },
    {
      id: 3,
      busyContent: '',
      busyMinute: 1,
    },
    {
      id: 4,
      busyContent: '',
      busyMinute: 1,
    },
    {
      id: 5,
      busyContent: '',
      busyMinute: 1,
    },
  ]

  ngOnInit() {
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.initForm();
    this.getList(1);
  }

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

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      workScheme: {
        hosId: this.currentHospital.id,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("configuration", "workScheme", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }
      });
  }

  // 新增弹框
  addModal() {
    this.modelName = "新增";
    this.add = true; //新增
    this.modal = true;
    this.copyModel = false;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }
  // 新增/编辑弹框
  timeFlag = ""; //open开启，close关闭
  addDateModal(data) {
    if (!data.timingStatus) {
      this.datePicker = "";
    }
    this.timeFlag = data.timingStatus ? "close" : "open";
    this.coopId = data;
    if (this.timeFlag == "close") {
      this.showDelModal(
        data,
        "是否确定关闭定时启用？确定后该方案将不会执行！",
        "关闭定时启用",
        "switchTime"
      );
    } else {
      this.dateModal = true;
    }
    this.initDateForm();
  }
  //关闭定时启用设置日期弹框
  hideDateModal() {
    this.dateModal = false;
    this.initDateForm();
  }
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      workAssignmentName: [null, [Validators.required]],
      workAssignmentType: ["1", [Validators.required]],
      showBusy: [0, [Validators.required]],
      workAssignmentDescribe: [null, [Validators.required]],
    });
  }
  // 初始化新增form表单
  initDateForm() {
    this.validateDateForm = this.fb.group({
      datePickerTime: [null, [Validators.required]],
    });
  }

  changeShowBusy(){
    this.busyList = [
      {
        id: 1,
        busyContent: '',
        busyMinute: 1,
      },
      {
        id: 2,
        busyContent: '',
        busyMinute: 1,
      },
      {
        id: 3,
        busyContent: '',
        busyMinute: 1,
      },
      {
        id: 4,
        busyContent: '',
        busyMinute: 1,
      },
      {
        id: 5,
        busyContent: '',
        busyMinute: 1,
      },
    ];
  }

  // 新增/编辑表单提交
  btnLoading1 = false; //完成
  submitForm(noGoTo?): void {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.invalid) {
      return;
    }
    if (noGoTo) {
      this.btnLoading1 = true;
    } else {
      this.btnLoading = true;
    }
    let data:any = {};

    if (this.add) {
      //增加
      data = {
        workScheme: {
          name: this.validateForm.value.workAssignmentName,
          workType: this.validateForm.value.workAssignmentType,
          showBusy: this.validateForm.value.showBusy,
          describe: this.validateForm.value.workAssignmentDescribe,
          status: 0,
          hosId: this.currentHospital.id,
        },
      };
    } else {
      //编辑
      data = {
        workScheme: {
          id: this.coopId.id,
          name: this.validateForm.value.workAssignmentName,
          workType: this.validateForm.value.workAssignmentType,
          showBusy: this.validateForm.value.showBusy,
          describe: this.validateForm.value.workAssignmentDescribe,
          hosId: this.currentHospital.id,
        },
      };
    }
    if (this.copyModel) {
      //复制
      data = {
        workScheme: {
          name: this.validateForm.value.workAssignmentName,
          workType: this.validateForm.value.workAssignmentType,
          showBusy: this.validateForm.value.showBusy,
          describe: this.validateForm.value.workAssignmentDescribe,
          status: 0,
          copy: 1,
          copySchemeId: this.coopId.id,
          hosId: this.currentHospital.id,
        },
      };
    }
    // 示忙原因
    this.busyList.forEach(v => {
      if(v.busyContent && v.busyContent.trim()){
        data.workScheme['busyContent' + v.id] = v.busyContent.trim();
        data.workScheme['busyMinute' + v.id] = v.busyMinute;
      }
    })
    this.mainService
      .coopTypeConfig("addData", "workScheme", data)
      .subscribe((result) => {
        if (noGoTo) {
          this.btnLoading1 = false;
        } else {
          this.btnLoading = false;
        }
        this.hideAddModal();
        this.initForm();
        if (result.status == 200) {
          if (this.copyModel) {
            //复制
            this.listLength++;
            this.showPromptModal("复制", true, "");
            if (!noGoTo) {
              this.router.navigateByUrl(
                `/main/quickCombination?id=${result.data.id}&name=${result.data.name}&type=${result.data.workType}`
              );
            }
            return;
          }
          if (!this.add) {
            //编辑
            this.showPromptModal("编辑", true, "");
            if (!noGoTo) {
              this.router.navigateByUrl(
                `/main/quickCombination?id=${result.data.id}&name=${result.data.name}&type=${result.data.workType}`
              );
            }
            return;
          }
          if (this.add) {
            this.listLength++;
          }
          this.router.navigateByUrl(
            `/main/quickCombination?id=${result.data.id}&name=${result.data.name}&type=${result.data.workType}`
          );
        } else {
          let msg = "";
          if (this.add) {
            msg = "新增";
          } else {
            msg = "修改";
          }
          if (this.copyModel) {
            msg = "复制";
          }
          this.showPromptModal(msg, false, result.msg);
        }
      });
  }
  // 时间选择范围
  disabledDateTime: DisabledTimeFn = () => {
    return {
      nzDisabledHours: () => [],
      nzDisabledMinutes: () => [],
      nzDisabledSeconds: () => this.range(1, 60),
    };
  };
  range(start: number, end: number): number[] {
    const result: number[] = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }
  // 选择日期表单提交
  submitDateForm(): void {
    this.btnLoading = true;
    for (const i in this.validateDateForm.controls) {
      this.validateDateForm.controls[i].markAsDirty();
      this.validateDateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateDateForm.invalid) {
      this.btnLoading = false;
      return;
    }
    let data = {};
    let todayDate = new Date(this.validateDateForm.value.datePickerTime);
    let year = todayDate.getFullYear();
    let month = (todayDate.getMonth() + 1).toString().padStart(2, "0");
    let date = todayDate.getDate().toString().padStart(2, "0");
    let hour = todayDate.getHours().toString().padStart(2, "0");
    let minutes = todayDate.getMinutes().toString().padStart(2, "0");
    // 2020-07-28 16:45:00
    data = {
      workScheme: {
        id: this.coopId.id,
        timingStatus: 1,
        startTime: `${year}-${month}-${date} ${hour}:${minutes}:00`,
        hosId: this.currentHospital.id,
      },
    };
    this.mainService
      .coopTypeConfig("addData", "workScheme", data)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideDateModal();
        this.initDateForm();
        if (data.status == 200) {
          this.listLength++;
          this.showPromptModal("定时启用时间设置", true, "");
        } else {
          this.showPromptModal("定时启用时间设置", false, data.msg);
        }
      });
  }

  // 编辑
  edit(data) {
    console.log(data);
    this.modelName = "编辑";
    this.add = false;
    this.modal = true;
    this.coopId = data;
    this.copyModel = false;
    this.validateForm.controls.workAssignmentName.setValue(data.name); //名称
    this.validateForm.controls.workAssignmentType.setValue(data.workType + ""); //类型
    this.validateForm.controls.showBusy.setValue(data.showBusy || 0);
    if(this.validateForm.value.showBusy == 1){
      this.busyList.forEach(v => {
        v.busyContent = data['busyContent' + v.id];
        v.busyMinute = data['busyMinute' + v.id] || 0;
      })
    }
    this.validateForm.controls.workAssignmentDescribe.setValue(data.describe); //描述
  }
  //复制
  copyModel = false; //复制
  copy(data) {
    this.modelName = "复制";
    this.copyModel = true;
    this.modal = true;
    this.coopId = data;
    this.validateForm.controls.workAssignmentName.setValue(data.name); //名称
    this.validateForm.controls.workAssignmentType.setValue(data.workType + ""); //类型
    this.validateForm.controls.showBusy.setValue(data.showBusy || 0);
    if(this.validateForm.value.showBusy == 1){
      this.busyList.forEach(v => {
        v.busyContent = data['busyContent' + v.id];
        v.busyMinute = data['busyMinute' + v.id] || 0;
      })
    }
    this.validateForm.controls.workAssignmentDescribe.setValue(data.describe); //描述
  }

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

  // 启用
  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  tipsMsg2: string; //操作后信息
  confirmDelType: string; //确认的类型（启用/停用，删除）
  confirmDelIsSwitch: boolean; //启用/停用
  showDelModal(
    data,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
    isSwitch?: boolean
  ) {
    this.confirmDelIsSwitch = isSwitch;
    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.mainService
        .coopTypeConfig("rmvData", "workScheme", [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);
          }
        });
    } else if (this.confirmDelType === "switch") {
      //启用
      let data = {
        workScheme: {
          id: this.coopId.id,
          hosId: this.currentHospital.id,
          status: 1,
          workType: this.coopId.workType,
        },
      };
      this.mainService
        .coopConfig("activeWorkScheme", data)
        .subscribe((result) => {
          this.btnLoading = false;
          this.delModal = false;
          if (result.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, result.msg);
          }
        });
    } else if (this.confirmDelType === "switchTime") {
      //关闭定时启用
      let data = {
        workScheme: {
          id: this.coopId.id,
          hosId: this.currentHospital.id,
          timingStatus: 0,
        },
      };
      this.mainService
        .coopTypeConfig("addData", "workScheme", data)
        .subscribe((result) => {
          this.btnLoading = false;
          this.delModal = false;
          if (result.status == 200) {
            this.showPromptModal(this.tipsMsg2, true, "");
          } else {
            this.showPromptModal(this.tipsMsg2, false, result.msg);
          }
        });
    }
  }

  // 查看
  detail(id) {
    this.router.navigateByUrl(
      "/main/workAssignment/workAssignmentDetail/" + id
    );
  }
  //时间选择框相关
  defaultTimePickerOpenValue = new Date();
  // 更改日期
  datePicker;
  datePickerChange(e) {
    if (!e) {
      return;
    }
    let todayDate = new Date(e);
    let year = todayDate.getFullYear();
    let month = (todayDate.getMonth() + 1).toString().padStart(2, "0");
    let date = todayDate.getDate().toString().padStart(2, "0");
    let hour = todayDate.getHours().toString().padStart(2, "0");
    let minutes = todayDate.getMinutes().toString().padStart(2, "0");
    this.datePicker = `${year}-${month}-${date} ${hour}:${minutes}:00`;
  }
}
