import { Component, OnInit, ViewChild } from "@angular/core";
import { ActivatedRoute, Router } 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 { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { NzMessageService } from "ng-zorro-antd";
import { format, startOfMinute } from "date-fns";
@Component({
  selector: "app-inspection-plan",
  templateUrl: "./inspection-plan.component.html",
  styleUrls: ["./inspection-plan.component.less"],
})
export class InspectionPlanComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService
  ) {}

  userInfo: any = JSON.parse(localStorage.getItem("user")) || {}; //登录用户信息

  searchCriteria = {
    //搜索条件
    name: "",
    planTypeId: null,
  };
  formIds = []; //巡检单
  planTypes = []; //重复策略
  types = []; //巡检类型
  signTypes = []; //签到方式
  department = []; // 院区下的科室列表
  departmentSearch = []; // 院区下的科室列表(搜索框)
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  tableHeight: number; //表格动态高
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopId: number; //当前操作列id
  coopData: any = {}; //当前操作列

  hosId: any; //当前院区id
  btnLoading: boolean = false; //提交按钮loading状态

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  demoValue: number = 0;
  changeFormIdSubject = new Subject();
  ngOnInit() {
    this.changeFormIdSubject
      .pipe(debounceTime(500))
      .subscribe((v: any) => {
        this.getFormId(v);
      });
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList(1);
    this.initForm();
    this.getPlanTypes();
    this.getTypes();
    this.getSignTypes();
    this.getFormId();
  }
  // 重置
  reset() {
    this.searchCriteria = {
      //搜索条件
      name: "",
      planTypeId: null,
    };
    this.getList(1);
  }

  // 选择轮巡类型
  selectedTasktype = null; //当前选中的轮巡类型
  // 任务类型防抖搜索
  isLoading = false;
  changeFormId(keyWord = "") {
    this.isLoading = true;
    this.changeFormIdSubject.next(keyWord);
  }

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

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      inspection: {
        hosId: this.hosId,
        planType: this.searchCriteria.planTypeId ? { id: this.searchCriteria.planTypeId } : undefined,
        name: this.searchCriteria.name || undefined,
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "inspection", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
          this.listOfData.forEach((item) => {
            if (item.planType.value == "week") {
              let weeks = [
                "周一",
                "周二",
                "周三",
                "周四",
                "周五",
                "周六",
                "周日",
              ];
              item.weekName = weeks[item.planDay - 1];
            }
          });
        }
      });
  }
  //获取巡检单
  getFormId(keyWord = "") {
    let postData = {
      idx: 0,
      sum: 20,
      inspectionForm: {
        hosId: this.hosId,
        name: keyWord,
        status: { value: '1' },
      },
    };
    this.mainService
      .getFetchDataList("simple/data", "inspectionForm", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.isLoading = false;
          this.formIds = result.list;
        }
      });
  }
  //获取重复策略
  getPlanTypes() {
    this.mainService
    .getDictionary('list', 'inspection_plan_type')
    .subscribe((data) => {
      this.planTypes = data || [];
    });
  }
  //获取巡检类型
  getTypes() {
    this.mainService
    .getDictionary('list', 'inspection_type')
    .subscribe((data) => {
      this.types = data || [];
    });
  }
  //获取签到方式
  getSignTypes() {
    this.mainService
    .getDictionary('list', 'inspection_sign_type')
    .subscribe((data) => {
      this.signTypes = data || [];
    });
  }
  // 新增/编辑弹框
  addModal() {
    this.add = true; //新增
    this.modal = true;
    this.initForm();
  }
  //关闭新增/编辑弹框
  hideAddModal() {
    this.modal = false;
    this.initForm();
  }
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
      name: [null, [Validators.required]],
      content: [null, [Validators.required]],
      formId: [null, [Validators.required]],
      planType: [null, [Validators.required]],
      type: [null, [Validators.required]],
      signType: [null, [Validators.required]],
      execDay: [null, [Validators.required]],
      execTime: [null, [Validators.required]],
    });
  }
  // 修改轮巡策略
  months = [...Array(32).keys()].slice(1);
  planTypeChange(e) {
    this.validateForm.controls.execTime.setValue(null);
    switch (e) {
      case "none":
        this.validateForm.addControl("doNone", new FormControl(null, Validators.required));
        this.validateForm.removeControl("doWeek");
        this.validateForm.removeControl("doMonth");
        this.validateForm.removeControl("doYear");
        break;
      case "day":
        this.validateForm.removeControl("doWeek");
        this.validateForm.removeControl("doMonth");
        this.validateForm.removeControl("doYear");
        this.validateForm.removeControl("doNone");
        break;
      case "week":
        this.validateForm.addControl(
          "doWeek",
          new FormControl(null, Validators.required)
        );
        this.validateForm.removeControl("doMonth");
        this.validateForm.removeControl("doYear");
        this.validateForm.removeControl("doNone");
        break;
      case "month":
        this.validateForm.addControl(
          "doMonth",
          new FormControl(null, Validators.required)
        );
        this.validateForm.removeControl("doWeek");
        this.validateForm.removeControl("doYear");
        this.validateForm.removeControl("doNone");
        break;
      case "year":
        this.validateForm.addControl(
          "doYear",
          new FormControl(null, Validators.required)
        );
        this.validateForm.removeControl("doWeek");
        this.validateForm.removeControl("doMonth");
        this.validateForm.removeControl("doNone");
        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 = {
        name: this.validateForm.value.name,
        content: this.validateForm.value.content,
        hosId: this.hosId,
        formId: this.validateForm.value.formId,
        planType: this.planTypes.find(v => v.value == this.validateForm.value.planType),
        type: this.types.find(v => v.value == this.validateForm.value.type),
        signType: this.signTypes.find(v => v.value == this.validateForm.value.signType),
        execDay: this.validateForm.value.execDay,
        execTime: format(startOfMinute(this.validateForm.value.execTime), 'yyyy-MM-dd HH:mm:ss'),
      };
      if (this.validateForm.value.planType == "day") {
        delete postData.planDay;
      } else if (this.validateForm.value.planType == "week") {
        postData.planDay = this.validateForm.value.doWeek;
      } else if (this.validateForm.value.planType == "month") {
        postData.planDay = this.validateForm.value.doMonth;
      } else if (this.validateForm.value.planType == "year") {
        delete postData.planDay;
        postData.execTime =  format(this.validateForm.value.doYear, "yyyy-MM-dd") + " " + format(startOfMinute(this.validateForm.value.execTime), "HH:mm:ss");
      } else if (this.validateForm.value.planType == "none") {
        delete postData.planDay;
        postData.execTime = format(this.validateForm.value.doNone, "yyyy-MM-dd") + " " + format(startOfMinute(this.validateForm.value.execTime), "HH:mm:ss");
      }
    } else {
      //编辑
      postData = {
        // deleteFlag: this.coopData.deleteFlag,
        ...this.coopData,
        id: this.coopId,
        name: this.validateForm.value.name,
        content: this.validateForm.value.content,
        hosId: this.hosId,
        formId: this.validateForm.value.formId,
        planType: this.planTypes.find(v => v.value == this.validateForm.value.planType),
        type: this.types.find(v => v.value == this.validateForm.value.type),
        signType: this.signTypes.find(v => v.value == this.validateForm.value.signType),
        execDay: this.validateForm.value.execDay,
        execTime: format(startOfMinute(this.validateForm.value.execTime), 'yyyy-MM-dd HH:mm:ss'),
      };
      if (this.validateForm.value.planType == "day") {
        delete postData.planDay;
      } else if (this.validateForm.value.planType == "week") {
        postData.planDay = this.validateForm.value.doWeek;
      } else if (this.validateForm.value.planType == "month") {
        postData.planDay = this.validateForm.value.doMonth;
      } else if (this.validateForm.value.planType == "year") {
        delete postData.planDay;
        postData.execTime = format(this.validateForm.value.doYear, "yyyy-MM-dd") + " " + format(startOfMinute(this.validateForm.value.execTime), "HH:mm:ss");
      } else if (this.validateForm.value.planType == "none") {
        delete postData.planDay;
        postData.execTime = format(this.validateForm.value.doNone, "yyyy-MM-dd") + " " + format(startOfMinute(this.validateForm.value.execTime), "HH:mm:ss");
      }
    }
    console.log(postData);
    this.mainService
      .simplePost("addData", 'inspection', postData)
      .subscribe((data) => {
        this.btnLoading = false;
        this.hideAddModal();
        this.initForm();
        if (data.status == 200) {
          this.listLength++;
          this.showPromptModal(this.add ? "新增" : "修改", true, "");
        } else {
          this.showPromptModal(this.add ? "新增" : "修改", false, data.msg);
        }
      });
  }

  // 编辑
  executionTimeTemporaryStorage; //暂存执行时间
  maskFlag: any = false;
  edit(data) {
    this.initForm();
    this.add = false;
    this.modal = true;
    this.coopId = data.id;
    this.coopData = data;
    this.validateForm.controls.name.setValue(data.name);
    this.validateForm.controls.content.setValue(data.content);
    this.validateForm.controls.planType.setValue(data.planType ? data.planType.value : null);
    this.validateForm.controls.type.setValue(data.type ? data.type.value : null);
    this.validateForm.controls.signType.setValue(data.signType ? data.signType.value : null);
    this.validateForm.controls.execDay.setValue(data.execDay);

    if(data.formId && data.inspectionFormDTO){
      let obj = this.formIds.find(v => v.id == data.formId);
      if(!obj){
        this.formIds.unshift(data.inspectionFormDTO);
      }
      this.validateForm.controls.formId.setValue(data.formId);

    }

    //执行时间 start
    this.planTypeChange(data.planType.value);
    if (data.planType.value == "year") {
      this.validateForm.controls.doYear.setValue(new Date(data.execTime));
      this.validateForm.controls.execTime.setValue(new Date(data.execTime));
    } else if (data.planType.value == "month") {
      this.validateForm.controls.doMonth.setValue(data.planDay);
      this.validateForm.controls.execTime.setValue(new Date(data.execTime));
    } else if (data.planType.value == "week") {
      this.validateForm.controls.doWeek.setValue(data.planDay);
      this.validateForm.controls.execTime.setValue(new Date(data.execTime));
    } else if (data.planType.value == "day") {
      this.validateForm.controls.execTime.setValue(new Date(data.execTime));
    } else if (data.planType.value == "none") {
      this.validateForm.controls.doNone.setValue(new Date(data.execTime));
      this.validateForm.controls.execTime.setValue(new Date(data.execTime));
    }
    //执行时间 end
  }
  coopItem: any = {};
  execModal: boolean = false;
  // 打开立即执行模态框
  openExecModal(item) {
    this.coopItem = item;
    this.execModal = true;
  }
  // 确认立即执行
  confirmExec() {
    this.btnLoading = true;
    this.mainService
      .executeNowOrderPlan(this.coopItem.id)
      .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;
  }
  // 展示信息提示框（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; //确认的类型（启用/停用，删除）
  confirmDelIsSwitch: boolean; //启用/停用
  showDelModal(
    id: number,
    tipsMsg1: string,
    tipsMsg2: string,
    type: string,
    isSwitch?: boolean
  ) {
    this.confirmDelIsSwitch = isSwitch;
    this.confirmDelType = type;
    this.delModal = true;
    this.coopId = id;
    this.tipsMsg1 = tipsMsg1;
    this.tipsMsg2 = tipsMsg2;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认删除
  confirmDel() {
    this.btnLoading = true;
    if (this.confirmDelType === "del") {
      //删除
      this.mainService.simplePost("rmvData", "inspection", [this.coopId]).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") {
      //启用/停用
      this.mainService
        .inspectionPost(
          'inspectionPublish',
          {
            inspectionId: this.coopId,
            type: this.confirmDelIsSwitch ? "disable" : "active",
          }
        )
        .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);
          }
        });
    } else if (this.confirmDelType === "once") {
      //执行一次
      this.mainService
        .inspectionPost(
          'inspectionPublish',
          {
            inspectionId: this.coopId,
            type: "executeOnece",
          }
        )
        .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);
          }
        });
    }
  }

  // 查看
  // detail(id) {
  //   this.router.navigateByUrl("/main/roundRobin/roundRobinDetail/" + id);
  // }
  // -----------------------------------------------------------------------
  //配置
  planConfig(data) {
    this.router.navigateByUrl("inspectionPlanConfig/" + data.id);
  }

  formatterExecDay = (value: number) => value ? `${value} 天` : '';
  parserExecDay = (value: string) => value.replace(' 天', '');
}
