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

import { MainService } from "../../services/main.service";
import { ToolService } from "../../services/tool.service";
import { NzMessageService } from 'ng-zorro-antd';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { format } from 'date-fns';
@Component({
  selector: "app-inspection-batch",
  templateUrl: "./inspection-batch.component.html",
  styleUrls: ["./inspection-batch.component.less"],
})
export class InspectionBatchComponent implements OnInit {
  constructor(
    private fb: FormBuilder,
    private mainService: MainService,
    private route: ActivatedRoute,
    private router: Router,
    private tool: ToolService,
    private message: NzMessageService,
  ) {}

  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
  coopData: any; //当前操作列
  currentHospital; //当前院区

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

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

  changeInpSubject = new Subject(); //防抖
  showDropdown:boolean = false;

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[1] === 'inspectionPlan'){
        this.getInspectionPlans(v[0], v[2]);
      }
    });
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getList(1);
    this.getInspectionPlans('search', '');
    this.getStatus();
  }

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

  // 批量关联科室
  inspectionAddressDepartmentPromptModalShow = false; //标本历史记录弹窗开关
  showInspectionAddressDepartment() {
    this.inspectionAddressDepartmentPromptModalShow = true;
  }
  // 关闭弹窗
  closeModelInspectionAddressDepartment(e) {
    this.inspectionAddressDepartmentPromptModalShow = JSON.parse(e).show;
  }
  // 确认弹窗
  checkedDepIdsModel = [];
  confirmModelInspectionAddressDepartment(checkedDepIds) {
    this.inspectionAddressDepartmentPromptModalShow = true;
    this.checkedDepIdsModel = checkedDepIds;
    console.log(checkedDepIds)
    this.showInspectionAddressTag();
  }

  // 批量关联科室-标签
  inspectionAddressTagPromptModalShow = false; //标本历史记录弹窗开关
  showInspectionAddressTag() {
    this.inspectionAddressTagPromptModalShow = true;
  }
  // 关闭弹窗
  closeModelInspectionAddressTag(e) {
    this.inspectionAddressTagPromptModalShow = JSON.parse(e).show;
  }
  // 确认弹窗
  maskFlag: any = false;
  confirmModelInspectionAddressTag(tags) {
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.inspectionAddressTagPromptModalShow = true;
    console.log(this.checkedDepIdsModel, tags);
    let postData:any = {
      deptIds: this.checkedDepIdsModel.toString(),
      hosId: this.currentHospital.id,
      tagIds: tags.toString(),
    };
    console.log(postData);
    this.btnLoading = true;
    this.mainService
      .inspectionPost("batchBindFormNode", postData)
      .subscribe((result) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.btnLoading = false;
        if (result.status == 200) {
          this.inspectionAddressDepartmentPromptModalShow = false;
          this.inspectionAddressTagPromptModalShow = false;
          this.showPromptModal('操作', true, '');
        } else if (result.status == 501) {
          this.inspectionAddressDepartmentPromptModalShow = false;
          this.inspectionAddressTagPromptModalShow = false;
          this.showPromptModal('操作', true, result.msg);
        } else {
          this.showPromptModal('操作', false, result.msg);
        }
      });
  }

  // 搜索
  search() {
    this.getList(1);
  }
  // 重置
  reset() {
    this.dateRange = [];
    this.changeDate();
    this.searchDto = {};
    this.getList(1);
  }

  // 表格数据
  searchDto: any = {};
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data:any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      inspectionBatch: {
        hosId: this.currentHospital.id,
        inspectionId: this.searchDto.inspectionId || undefined,
        status: this.searchDto.statusId ? { id: this.searchDto.statusId } : undefined,
      },
    };
    if (this.startDate && this.endDate) {
      data.inspectionBatch.addTimeStart = this.startDate;
      data.inspectionBatch.addTimeEnd = this.endDate;
    }
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "inspectionBatch", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }

  // 边输边搜节流阀
  isLoading = false;
  changeInp(type, model, e) {
    this.isLoading = true;
    this.changeInpSubject.next([type, model, e]);
  }

  // 获取巡检计划
  inspectionPlanSearchList: any = [];
  getInspectionPlans(type, keyword, init = false) {
    let postData = {
      inspection: {
        name: keyword,
        hosId: this.currentHospital.id,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("data", "inspection", postData)
      .subscribe((data) => {
        this.inspectionPlanSearchList = data.list;
        this.isLoading = false;
      });
  }

  // 获取状态
  statusSearchList: any = [];
  getStatus() {
    this.mainService
    .getDictionary('list', 'inspection_batch_status')
    .subscribe((data) => {
      this.statusSearchList = data || [];
    });
  }

  dateRange: any = []; //时间范围
  onCalendarChangeDate(dateArr){
    console.log(dateArr)
    if(dateArr.length == 2){
      let dateStart = new Date(dateArr[0]);
      let dateEnd = new Date(dateArr[1]);
      dateStart.setHours(0,0,0);
      dateEnd.setHours(23,59,59);
      this.dateRange = [dateStart,dateEnd];
    }
  }

  // 日期选择
  startDate: string; //发起时间开始
  endDate: string; //发起时间结束
  changeDate(result?): void {
    if (!result) {
      this.startDate = this.endDate = "";
      return;
    }
    this.startDate = format(result[0], 'yyyy-MM-dd HH:mm:ss');
    this.endDate = format(result[1], 'yyyy-MM-dd HH:mm:ss');
  }

  // 展示信息提示框（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; //确认的类型（启用/停用，删除）
  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 === "del") {
      //删除
      this.mainService
        .simplePost("rmvData", "inspectionBatch", [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);
          }
        });
    }
  }
}
