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";

@Component({
  selector: "app-task-list",
  templateUrl: "./task-list.component.html",
  styleUrls: ["./task-list.component.less"],
})
export class TaskListComponent 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; //新增或编辑用户的时候，微信号是否必填
  searchTaskSubject = new Subject(); //防抖
	searchParentDeptSubject = new Subject();
	specimenName:any = null;
	containPosition:any = null;
	placeList:any = [];
	systemList:any = [];
	apparatusList:any = [];
	specimenNameList:any = [];
	addressLoading:any = false;
	month:any = [];
	userId:any;
	
  ngOnInit() {
		for(let i=1; i<13; i++){
			this.month.push({
				name:i + '月'
			})
		}
    this.coopBtns = this.tool.initCoopBtns(this.route);
		this.hosId = this.tool.getCurrentHospital().id;
		this.userId = this.tool.getCurrentUserId();
		this.searchParentDeptSubject.pipe(debounceTime(500)).subscribe((e) => {
			this.isLoading = true;
			this.getAllUser(e[0])
		});
		this.searchTaskSubject.pipe(debounceTime(500)).subscribe((e) => {
			this.isLoading = true;
			this.getmonthlyData(e[0])
		});
		
		this.getList();
		this.getAllUser('');
		this.getStateDic();
		this.getPriorityData();
		this.getmonthlyData('');
  }
	
	// 选择月份
	selectIndex:any;
	itemData:any;
	itemClick(data, index){
		this.selectIndex = index;
		this.itemData = data;
	}
	
  // 初始化增删改按钮
  coopBtns: any = {};
  // 搜索
  search() {
    this.pageIndex = 1;
    this.getList();
  }
	
  // 重置
  reset() {
    this.pageIndex = 1;
    this.state = null;
    this.priority = null;
    this.monthTask = null;
    this.executor = null;
    this.getList();
  }
	
  // 表格数据
  loading1 = false;
	state:any;
	priority:any;
	monthTask:any;
	executor:any;
  getList() {
    let data = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      monthTaskList: {
        priority: {
        	id: '',
        },
        state: {
					id: '',
				},
				monthTask:this.monthTask || undefined,
        executor: this.userId,
      },
    };
		if(this.priority){
			data.monthTaskList.priority.id = this.priority
		}else{
			delete data.monthTaskList.priority
		}
		if(this.state){
			data.monthTaskList.state.id = this.state
		}else{
			delete data.monthTaskList.state
		}
    this.loading1 = true;
    this.mainService
      .getFetchDataList("data", "monthTaskList", data)
      .subscribe((data) => {
        this.loading1 = false;
        this.listOfData = data.list;
        this.listLength = data.totalNum;
      });
  }
	
	// 获取月度任务
	monthlyData:any=[];
	getmonthlyData(name){
		let data = {
		  idx: 0,
		  sum: 20,
		  monthTask: {
				taskTitle: name || undefined,
		  },
		};
		this.mainService
		  .getFetchDataList("data", "monthTask", data)
		  .subscribe((data) => {
		    this.isLoading = false;
		    this.monthlyData = data.list;
		  });
	}
	
	// 获取责任人
	dutyUser:any= [];
	getAllUser(name) {
	  let data:any = {
	    user: {
				name,
	      hosIds: 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]);
	}
	
	// 搜索月度任务
	changeTask(e,type) {
	  this.searchTaskSubject.next([e,type]);
	}
	
	// 获取优先级
	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;
			}
		});
	}
	
	// 获取状态
	stateList:any = [];
	getStateDic(){
		this.mainService.getDictionary("list", "month_task_list_state").subscribe((res) => {
			this.stateList = res
		});
	}
	
	// 开始任务
	startModal:boolean = false
	startTask(data){
		this.coopId = data.id;
		this.startModal = true
	}
	
	hideStartModal(){
		this.startModal = false
	}
	
	// 确认开始任务
	confirmStart() {
	  let that = this;
		let query = {
			monthTaskList:{
				id: this.coopId,
				operationType: 'start'
			}
		}
	  that.btnLoading = true;
	  that.mainService
	    .apiPublicData('updData', 'monthTaskList', query)
	    .subscribe((data) => {
	      that.btnLoading = false;
	      that.hideStartModal();
	      if (data["status"] == 200) {
	        that.showPromptModal("操作", true, "");
	      } else {
	        that.showPromptModal("操作", false, data["msg"]);
	      }
	    });
	}
	
	// 任务记录
	allocationModal:boolean = false;
	record(data){
		this.coopId = data.id;
		this.initAllocationForm();
		this.allocationModal = true
	}
	
	hideAllocationModal() {
	  this.allocationModal = false;
		this.initAllocationForm();
	}
	
	// 初始化新增form表单
	initAllocationForm() {
	  this.validateAllocationForm = this.fb.group({
	    taskConclusion: [null, [Validators.required]],
			manHour: [null, [Validators.required]],
	  });
	}
		
	// 任务记录提交
	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:{
				taskConclusion: this.validateAllocationForm.value.taskConclusion,
				manHour: this.validateAllocationForm.value.manHour,
				id:this.coopId,
				operationType: 'record'
			}
	  };
	
		that.btnLoading = true;
	  that.mainService
	    .dataPost("updData", "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;
	manHour:any;
	accomplish(data){
		this.coopId = data.id;
		this.taskConclusion = null;
		this.accomplishModal = true
	}
	
	// 任务完成提交
	submitAccomplishForm(){
		if(!this.taskConclusion){
			this.message.error('任务总结不能为空！')
			return
		}
		if(!this.manHour){
			this.message.error('总工时不能为空！')
			return
		}
		let data = {
			monthTaskList:{
				taskConclusion: this.taskConclusion,
				manHour: this.manHour,
				operationType: 'done',
				id:this.coopId
			}
		};
		this.btnLoading = true;
		this.mainService
		  .dataPost("updData", "monthTaskList", 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
	}
	
	// 展示信息提示框（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();
	}
}

