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-execute",
  templateUrl: "./inspection-execute.component.html",
  styleUrls: ["./inspection-execute.component.less"],
})
export class InspectionExecuteComponent 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(); //防抖
	changePollingInpSubject = new Subject(); //防抖
  showDropdown:boolean = false;

  ngOnInit() {
    //防抖
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      if(v[1] === 'inspectionPlan'){
        this.getIncidentPlans(v[0], v[2]);
      } else if(v[1] === 'inspectionBatch'){
        this.getInspectionBatchs(v[0], v[2]);
      }
    });
		
		this.changePollingInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.getPollingList(v);
    });
    this.currentHospital = this.tool.getCurrentHospital();
    this.coopBtns = this.tool.initCoopBtns(this.route);
    this.getList(1);
    this.getIncidentPlans('search', '');
		this.getPollingList()
    this.getStatus();
  }
	
	// 日期选择
	startDate: string; //发起时间开始
	endDate: string; //发起时间结束
	changeDate(result?): void {
	  if (result.length==0) {
	    this.startDate = this.endDate = null;
	    return;
	  }
		this.startDate = format(result[0], 'yyyy-MM-dd HH:mm:ss');
		this.endDate = format(result[1], 'yyyy-MM-dd HH:mm:ss');
	  this.searchDto.dateRange = [this.startDate,this.endDate]
	}
	
	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.searchDto.dateRange = [dateStart,dateEnd];
	  }
	}
	
	// 获取巡检点
	pollingData:any = [];	
	getPollingList(name?) {
	  let data = {
	    idx: 0,
	    sum: 20,
	    inspectionNode: {
	      hosId: this.currentHospital.id,
				name
	    },
	  };
	  this.mainService
	    .getFetchDataList("simple/data", "inspectionNode", data)
	    .subscribe((data) => {
	      this.isLoading = false;
	      if (data.status == 200) {
	        this.pollingData = data.list;
	      }else{
	        this.message.error(data.msg || "请求数据失败");
	      }
	    });
	}
  // 初始化增删改按钮
  coopBtns: any = {};

  // 查看
  detail(e, id) {
    e.stopPropagation();
    this.router.navigateByUrl("/main/inspectionExecute/inspectionExecuteDetail/" + id);
  }

  // 查看故障单详情-弹窗
  detailModalShow = false; //弹窗开关
  viewIncidentDetail(e, data) {
    e.stopPropagation();
    this.coopData = data;
    this.detailModalShow = true;
  }
  // 关闭弹窗
  closeDetailModelOrder(e) {
    this.detailModalShow = JSON.parse(e).show;
  }
  // 弹窗确定
  confirmDetailModelOrder(e){
    console.log(e);
    this.detailModalShow = false;
  }

  // 派单给人
  inspectionExecuteAssignPromptModalShow = false;
  showInspectionExecuteAssign(data?) {
    this.coopData = data;
    this.inspectionExecuteAssignPromptModalShow = true;
  }
  // 关闭弹窗
  closeModelInspectionExecuteAssign(e) {
    this.inspectionExecuteAssignPromptModalShow = JSON.parse(e).show;
  }
  // 确认弹窗
  maskFlag: any = false;
  confirmModelInspectionExecuteAssign(userId) {
    this.maskFlag = this.message.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.inspectionExecuteAssignPromptModalShow = true;
    console.log(userId);
    let postData:any = {
      taskIds: this.coopData ? this.coopData.id.toString() : this.checkedDepIds.toString(),
      userId,
    };
    console.log(postData);
    this.btnLoading = true;
    this.mainService
      .inspectionPost("batchAssignTask", postData)
      .subscribe((result) => {
        this.message.remove(this.maskFlag);
        this.maskFlag = false;
        this.btnLoading = false;
        if (result.status == 200) {
          this.inspectionExecuteAssignPromptModalShow = false;
          this.showPromptModal('操作', true, '');
        } else {
          this.showPromptModal('操作', false, result.msg);
        }
      });
  }

  // 选中表格单列
  mapOfCheckedId: { [key: string]: boolean } = {};
  checkedDepIds:any[] = []; //已选中单列id
  refreshStatus(): void {
    let listOfData = this.listOfData.filter(
      (item) => item.status.value == 1
    );
    this.isAllDisplayDataChecked = listOfData.every(
      (item) => this.mapOfCheckedId[item.id]
    );
    let arr:any[] = [];
    for (var k in this.mapOfCheckedId) {
      if (this.mapOfCheckedId[k]) {
        arr.push(Number(k));
      }
    }
    this.checkedDepIds = arr;
  }
  // 整行操作
  selectedListData(data) {
    if (data.status.value != 1) {
      return;
    }
    this.mapOfCheckedId[data.id] = !this.mapOfCheckedId[data.id];
    this.refreshStatus();
  }
  // 全选
  isAllDisplayDataChecked = false; //当前页是否全选
  checkAll(value: boolean): void {
    this.listOfData.forEach((item) => {
      if (item.status.value == 1) {
        this.mapOfCheckedId[item.id] = value;
      }
    });
    this.refreshStatus();
  }

  // 搜索
  search() {
    this.getList(1);
  }
  // 重置
  reset() {
    this.inspectionBatchSearchList = [];
    this.searchDto = {};
		this.startDate = undefined,
		this.endDate = undefined,
    this.getList(1);
  }

  // 表格数据
  searchDto: any = {};
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      inspectionTask: {
        simpleQuery: true,
        hosId: this.currentHospital.id,
        code: this.searchDto.code || undefined,
        inspectionId: this.searchDto.inspectionId || undefined,
        batchId: this.searchDto.batchId || undefined,
        status: this.searchDto.statusId ? { id: this.searchDto.statusId } : undefined,
        exception: this.searchDto.exceptionId === undefined ? undefined : this.searchDto.exceptionId,
				overTimeStart: this.startDate || undefined,
				overTimeEnd: this.endDate || undefined,
				nodeId: this.searchDto.nodeId || undefined,
			},
    };
    this.mapOfCheckedId = {};
    this.checkedDepIds = [];
    this.isAllDisplayDataChecked = false;
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "inspectionTask", 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]);
  }
	// 搜索巡检点
	changePollingInp( e) {
    this.isLoading = true;
    this.changePollingInpSubject.next(e);
  }
	
  // 获取巡检计划
  inspectionPlanSearchList: any = []; //所有所属科室(搜索)
  getIncidentPlans(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;
      });
  }

  // 获取批次
  inspectionBatchSearchList: any = [];
  getInspectionBatchs(type, keyword, init = false) {
    let postData = {
      inspectionBatch: {
        name: keyword,
        hosId: this.currentHospital.id,
        inspectionId: this.searchDto.inspectionId || undefined,
      },
      idx: 0,
      sum: 20,
    };
    this.mainService
      .getFetchDataList("simple/data", "inspectionBatch", postData)
      .subscribe((data) => {
        this.inspectionBatchSearchList = data.list;
        this.isLoading = false;
      });
  }

  // 修改巡检计划
  changeInspection(e){
    this.inspectionBatchSearchList = [];
    this.searchDto.inspectionBatchId = null;
    this.getInspectionBatchs('search', '');
  }

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

  // 是否异常
  exceptionList:any[] = [
    { id: 0, name: "否" },
    { id: 1, name: "是" },
  ];

  // 展示信息提示框（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", "inspectionTask", [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);
          }
        });
    } else if (this.confirmDelType === "delList") {
      //批量删除
      this.mainService
        .simplePost("rmvData", "inspectionTask", this.checkedDepIds)
        .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);
          }
        });
    }
  }
}
