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 { forkJoin, Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { NzMessageService } from "ng-zorro-antd";
import { format, startOfDay, endOfDay } from 'date-fns';

@Component({
  selector: "app-monthly-task",
  templateUrl: "./monthly-task.component.html",
  styleUrls: ["./monthly-task.component.less"],
})
export class MonthlyTaskComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    private message: NzMessageService,
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private router: Router,
    private mainService: MainService,
    private tool: ToolService
  ) {}

  listOfData: any[] = []; //表格数据

  modal: boolean = false; //新增/编辑模态框
  add: boolean; //true:新增；false:编辑
  validateForm: FormGroup; //新增/编辑表单
	validateAllocationForm: FormGroup; //新增/编辑表单
  coopId: number; //表格中执行操作的id
  dept: any; //所属科室
  drugCode; //编号
  name; //名称
  userType: any; //用户类型
  hosId: any; //院区（搜索）
  userGroup; //所属组
  userGroup1; //所属组(搜索)
  userTypes: Array<any>; //所有用户类型
  alldepart: any = []; //所有所属科室
  alldepart1: any = []; //所有所属科室(搜索)
  hospitals1: any = []; //院区列表(搜索)
	drugTypeData: any = []; //药品类型
  allUserGroup: Array<any>; //所有用户组
  allUserGroup1: Array<any>; //用户组(搜索)
  allUserRole: Array<any>; //所有角色
  pageIndex: number = 1; //页码
  listLength: number = 10; //总条数
  pageSize: number = 10; //每页条数

  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示

  btnLoading: boolean = false; //提交按钮loading状态
  wxRequired = false; //新增或编辑用户的时候，微信号是否必填
  changeInpSubject = new Subject(); //防抖
	searchParentDeptSubject = new Subject();
	specimenName:any = null;
	containPosition:any = null;
	placeList:any = [];
	systemList:any = [];
	apparatusList:any = [];
	specimenNameList:any = [];
	addressLoading:any = false;
	priority:any;
	liableUser:any;
	taskTitle:any;
	
  ngOnInit() {
    this.coopBtns = this.tool.initCoopBtns(this.route);
		this.hosId = this.tool.getCurrentHospital().id;
		this.searchParentDeptSubject.pipe(debounceTime(500)).subscribe((e) => {
			this.isLoading = true;
			this.getAllUser(e[0])
		});
    this.initForm();
		this.getList();
		this.getAllUser('');
		this.getPriorityData();
  }

  // 初始化增删改按钮
  coopBtns: any = {};
  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
  // 重置
  reset() {
    this.pageIndex = 1;
    this.priority = null;
    this.liableUser = null;
    this.taskTitle = null;
    this.startDate = null;
    this.endDate = null;
		this.dateRange = [];
    this.getList();
  }
	
  // 表格数据
  loading1 = false;
  getList() {
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      monthTask: {
				priority: {
					id:this.priority || undefined,
				},
				liableUser: this.liableUser || undefined,
				taskTitle: this.taskTitle || undefined,
				startTime: this.startDate || undefined,
				endTime: this.endDate || undefined
      },
    };
    this.loading1 = true;
    this.mainService
      .getFetchDataList("data", "monthTask", data)
      .subscribe((data) => {
        this.loading1 = false;
        this.listOfData = data.list;
        this.listLength = data.totalNum;
      });
  }
	
	// 日期选择
	startDate: string; //发起时间开始
	endDate: string; //发起时间结束
	dateRange: any = [];
	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.dateRange = [this.startDate,this.endDate]
	}
	
	// 获取责任人
	dutyUser:any= [];
	getAllUser(name) {
	  let data:any = {
	    user: {
				name,
	      hospital: {
					id: this.hosId
				},
	    },
	    idx: 0,
	    sum: 20,
	  };
	  this.mainService
	    .getFetchDataList("data", "user", data)
	    .subscribe((data) => {
				this.isLoading = false
				this.dutyUser = data.list
	    });
	}
	
	// 搜索责任人
	isLoading = false;
	changeUser(e) {
	  this.searchParentDeptSubject.next([e]);
	}
	
	// 获取优先级
	priorityData:any = [];
	getPriorityData(){
		let postData = {
		  idx: 0,
		  sum: 9999,
		  priority: {},
		};
		this.isLoading = true;
		this.mainService
		.getFetchDataList("simple/data", "priority", postData)
		.subscribe((data) => {
			this.isLoading = false;
			if (data.status == 200) {
				this.priorityData = data.list;
			}
		});
	}
	
	// 分配任务
	allocationModal:boolean = false;
	allocation(data){
		this.coopId = data.id;
		this.allocationModal = true
		this.initAllocationForm();
	}
	
	hideAllocationModal() {
	  this.allocationModal = false;
		this.initAllocationForm();
	}
	
	// 初始化新增form表单
	initAllocationForm() {
	  this.validateAllocationForm = this.fb.group({
	    taskContent: [null, [Validators.required]],
			executor: [null, [Validators.required]],
	    estimatedCompletionTime: [null, [Validators.required]],
	  });
	}
	
	onAllocationChange(result?): void {
		console.log('Selected Time: ', result);
		let endTime = format(result, 'yyyy-MM-dd HH:mm:ss');
		this.validateAllocationForm.controls.estimatedCompletionTime.setValue(endTime);
	}
		
	// 表单提交
	submitAllocationForm(): void {
	  var that = this;
		for (const i in that.validateAllocationForm.controls) {
		  that.validateAllocationForm.controls[i].markAsDirty();
		  that.validateAllocationForm.controls[i].updateValueAndValidity();
		}
		if (that.validateAllocationForm.invalid) return;
	  let data = {
			monthTaskList:{
				taskContent: this.validateAllocationForm.value.taskContent,
				executor: this.validateAllocationForm.value.executor,
				estimatedCompletionTime: this.validateAllocationForm.value.estimatedCompletionTime,
				monthTask: that.coopId,
			}
	  };

		that.btnLoading = true;
	  that.mainService
	    .dataPost("addData", "monthTaskList", data)
	    .subscribe((data) => {
	      that.btnLoading = false;
	      that.hideAllocationModal();
	      if (data.status == 200) {
	        that.showPromptModal("分配", true, "");
	      } else {
	        that.showPromptModal("分配", false, data.msg);
	      }
	    });
	}
	
	// 任务完成
	accomplishModal:boolean = false;
	taskConclusion:any;
	accomplish(data){
		this.coopId = data.id;
		this.taskConclusion = null;
		this.accomplishModal = true
	}
	
	// 任务完成提交
	submitAccomplishForm(){
		if(!this.taskConclusion){
			this.message.error('月度任务总结不能为空！')
			return
		}
		let data = {
			monthTask:{
				taskConclusion: this.taskConclusion,
				operationType: 'taskDone',
				id:this.coopId
			}
		};
		this.btnLoading = true;
		this.mainService
		  .dataPost("updData", "monthTask", data)
		  .subscribe((data) => {
		    this.btnLoading = false;
		    this.hideAccomplishModal();
		    if (data.status == 200) {
		      this.showPromptModal("操作", true, "");
		    } else {
		      this.showPromptModal("操作", false, data.msg);
		    }
		  });
	}
	
	hideAccomplishModal(){
		this.accomplishModal = false
	}
	
  // 新增弹框
  showModal() {
    this.add = true;
		this.modal = true;
		this.itemData = null;
    this.initForm();
  }
  hideModal() {
    this.modal = false;
    this.initForm();
  }
	
  // 初始化新增form表单
  initForm() {
    this.validateForm = this.fb.group({
			taskTitle:[null, [Validators.required]],
      taskDescribe: [null, [Validators.required]],
      priority: [null, [Validators.required]],
			liableUser: [null, [Validators.required]],
			liableUserNmae: [null, []],
      startTime: [null, [Validators.required]],
      endTime: [null, [Validators.required]],
    });
  }
	
	// 选择开始时间
	onStartChange(result: Date): void {
		console.log('Selected Time: ', result);
		let startTime = format(result, 'yyyy-MM-dd HH:mm:ss');
		this.validateForm.controls.startTime.setValue(startTime);
	}
	
	// 选择结束时间
	onEndChange(result: Date): void {
		console.log('Selected Time: ', result);
		let endTime = format(result, 'yyyy-MM-dd HH:mm:ss');
		this.validateForm.controls.endTime.setValue(endTime);
	}
		
  // 表单提交
  submitForm(): void {
    var that = this;
		for (const i in that.validateForm.controls) {
		  that.validateForm.controls[i].markAsDirty();
		  that.validateForm.controls[i].updateValueAndValidity();
		}
		if (that.validateForm.invalid) return;
    let data = {
			monthTask:{
				...this.itemData,
				taskTitle: this.validateForm.value.taskTitle,
				taskDescribe: this.validateForm.value.taskDescribe,
				priority: {
					id: this.validateForm.value.priority
				},
				liableUser: this.validateForm.value.liableUser,
				startTime: this.validateForm.value.startTime,
				endTime: this.validateForm.value.endTime,
				id:0,
			}
    };
    if (!that.add) {
      data.monthTask.id = that.coopId;
    }else{
			delete data.monthTask.id
		}
		that.btnLoading = true;
    that.mainService
      .dataPost(this.add ? "addData":"updData", "monthTask", data)
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideModal();
        that.initForm();
        if (data.status == 200) {
          that.showPromptModal(that.add ? "新增" : "编辑", true, "");
        } else {
          that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
        }
      });
  }

  // 编辑
	itemData:any;
  edit(data) {
		this.add = false
		this.itemData = data;
		this.coopId = data.id;
		this.validateForm.controls.taskTitle.setValue(data.taskTitle);
		this.validateForm.controls.taskDescribe.setValue(data.taskDescribe);
		this.validateForm.controls.priority.setValue(data.priority.id);
		this.validateForm.controls.liableUser.setValue(data.liableUserDTO.id)
		this.validateForm.controls.liableUserNmae.setValue(data.liableUserDTO.name)
		this.validateForm.controls.startTime.setValue(data.startTime);
		this.validateForm.controls.endTime.setValue(data.endTime);
		this.modal = true
  }

  // 删除
  delModal: boolean = false; //删除模态框
  del(data) {
    let that = this;
    that.coopId = data.id;
    that.delModal = true;
  }
	
	// 取消删除弹框
	cancelDel(){
		this.hideDelModal();
	}
	
  // 确认删除
  confirmDel() {
    let that = this;
    that.btnLoading = true;
    that.mainService
      .apiPublicData('rmvData', 'monthTask', [this.coopId])
      .subscribe((data) => {
        that.btnLoading = false;
        that.hideDelModal();
        if (data["status"] == 200) {
          that.showPromptModal("删除", true, "");
        } else {
          that.showPromptModal("删除", false, data["msg"]);
        }
      });
  }
	
	// 展示信息提示框（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();
	}
	
  // 关闭删除模态框
  hideDelModal() {
    this.delModal = false;
  }
}

