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-work-log",
  templateUrl: "./work-log.component.html",
  styleUrls: ["./work-log.component.less"],
})
export class WorkLogComponent 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.currentHospital = this.tool.getCurrentHospital();
		this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  let fun = v[0];
		  fun.call(this, v[1], v[2]);
		});
		this.getAllWorker();
		this.getTypeData();
    this.getList(1);
  }
	
	// 日期选择
	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');
	}
	
	// 选择时间
	dateRange:any = [];
	onCalendarChangeDate(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];
	  }
	}
	
	// 获取类型
	typeData:any = [];
	logType:any;
	getTypeData(){
		this.mainService.getDictionary("list", "work_log_type").subscribe((res) => {
			this.typeData = res
		});
	}
	
	// 获取操作人
	operationUser:any;
	allWorker:any = [];
	getAllWorker(e?, those?) {
	  let that = those || this;
	  let postData = {
	    user: {
	      name: e || "",
	      hospital: { id: that.currentHospital.id },
	    },
	    idx: 0,
	    sum: 20,
	  };
	  that.isLoading = true;
	  that.mainService
	    .getFetchDataList("data", "user", postData)
	    .subscribe((data) => {
	      that.allWorker = data.list;
	      that.isLoading = false;
	    });
	}
	
	// 用户输入搜索配送人员
	changeUser(e) {
	  this.searchTimer(this.getAllWorker, e);
	}
	
	// 边输入边搜索节流阀
	isLoading:boolean = false;
	searchTimer(fun, e) {
	  this.isLoading = true;
	  this.changeInpSubject.next([fun, e]);
	}
	
  // 表格数据
  searchDto: any = {};
  productDto:any = {};
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      baseWorkLog: {
				hosId: this.currentHospital.id,
        startTime: this.startDate || undefined,
    		endTime: this.endDate || undefined,
    		operationUser: this.operationUser || undefined,
    		logType:{
    			id: this.logType
    		}
      },
    };
    
    if(this.logType){
    	data.baseWorkLog.logType.id = this.logType
    }else{
    	delete data.baseWorkLog.logType 
    }
    this.loading1 = true;
    this.mainService
      .getFetchDataList("simple/data", "baseWorkLog", data)
      .subscribe((data) => {
        this.loading1 = false;
        if (data.status == 200) {
          this.listOfData = data.list;
          this.listLength = data.totalNum;
        }else{
          this.message.error(data.msg || "请求数据失败");
        }
      });
  }
	
	// 搜索
	search() {
	  this.pageIndex = 1;
	  this.getList(1);
	}
	
	// 重置
	reset() {
	  this.pageIndex = 1;
	  this.logType = null;
	  this.dateRange = [];
		this.startDate = null;
		this.endDate = null;
	  this.operationUser = null;
	  this.getList(1);
	}
	
  // 展示信息提示框（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);
  }
}
