import { Component, OnInit } from "@angular/core";
import { Subject } from "rxjs";
import { debounceTime } from "rxjs/operators";
import { MainService } from "src/app/services/main.service";
import { ToolService } from "src/app/services/tool.service";
import { format, startOfDay, endOfDay } from 'date-fns';
import { ActivatedRoute, Router } from "@angular/router";
import { FormBuilder, Validators, FormGroup, FormControl } from "@angular/forms";

@Component({
  selector: "app-drug-search",
  templateUrl: "./drug-search.component.html",
  styleUrls: ["./drug-search.component.less"],
})
export class DrugSearchComponent implements OnInit {
  constructor(
	private fb: FormBuilder,
	private mainService: MainService,
	private tool: ToolService,
	private router: Router,
	private route: ActivatedRoute
	) {}

  currentUserAccount: any = JSON.parse(localStorage.getItem("user")).user.account; //当前登录人账号
  searchCriteria = {
    //搜索条件
    packid: "", //请领单号
    launch: null, //发药科室
    target: null, //发药科室
    drugsState: null,
		receiverName: null,
		drugsBagType: null,
		dateRange:[],
  };
  deptList = []; // 院区下的配送人员列表(搜索框)
  hosId;
  listOfData: any[] = []; //表格数据
  pageIndex: number = 1; //表格当前页码
  pageSize: number = 10; //表格每页展示条数
  listLength: number = 10; //表格总数据量
	changeSearchSubject = new Subject();
  changeInpSubject = new Subject();
	changeUserInpSubject = new Subject();
	coopBtns:any;
	validateForm: FormGroup; //新增/编辑表单

  ngOnInit() {
		this.coopBtns = this.tool.initCoopBtns(this.route);
		this.changeSearchSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.getDept(v);
		});
    this.changeInpSubject.pipe(debounceTime(500)).subscribe((v) => {
      this.searchDept(v[0], v[1]);
    });
		this.changeUserInpSubject.pipe(debounceTime(500)).subscribe((v) => {
		  this.searchUser(v);
		});
    this.getHospital();
		this.getDrugsList();
		this.getMarkTypeList();
		this.getDept('');
		this.searchUser('');
		this.searchTypes();
  }
  // 查看流程信息弹窗
  logPromptModalShow = false; //弹窗开关
  drugsBagId = ""; //查看记录携带id
  showLogs(data) {
    this.drugsBagId = data.id;
    this.logPromptModalShow = true;
  }
  // 关闭流程信息弹窗
  closeModelLog(e) {
    this.logPromptModalShow = JSON.parse(e).show;
  }
  // 清空药品
  delModal: boolean = false; //删除模态框
  tipsMsg1: string; //提示框信息
  showDelModal(
    tipsMsg1: string
  ) {
    this.delModal = true;
    this.tipsMsg1 = tipsMsg1;
  }
  // 隐藏删除框
  hideDelModal() {
    this.delModal = false;
  }
  // 确认
  btnLoading: boolean = false; //提交按钮loading状态
  confirmDel() {
    this.btnLoading = true;
    this.mainService
      .coopDataM("drugsBag/emptyData", {"hosId":1,"isEmpty":'ok'})
      .subscribe((data) => {
        this.btnLoading = false;
        this.delModal = false;
        if (data.status == 200) {
          this.showPromptModal("药品清空", true, "");
        } else {
          this.showPromptModal("药品清空", false, "");
        }
      });
  }
  // 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
  promptContent: string; //操作提示框提示信息
  ifSuccess: boolean; //操作成功/失败
  promptInfo: string; //操作结果提示信息
  promptModalShow: boolean; //操作提示框是否展示
  showPromptModal(con, success, promptInfo?) {
    this.promptModalShow = false;
    this.promptContent = con;
    this.ifSuccess = success;
    this.promptInfo = promptInfo;
    setTimeout(() => {
      this.promptModalShow = true;
    }, 100);
    this.getList(0);
  }
  // 搜索类型
  isLoading1 = false;
  types = []; // 类型列表(搜索框)
  searchTypes() {
    this.isLoading1 = true;
    this.mainService.getDictionary("list", "drug_state").subscribe((res) => {
      this.isLoading1 = false;
      this.types = res;
    });
  }
  // 打开搜索框
  changeSearch1(flag) {
    if (flag) {
      this.searchTypes();
    }
  }

	// 获取药品类型
	drugsList:any = [];
	getDrugsList(){
		this.mainService.getDictionary("list", "drugs_bag_type").subscribe((res) => {
		  this.drugsList = res;
		});
	}

  // 获取药单类型
	markTypeList:any = [];
	getMarkTypeList(){
		this.mainService.getDictionary("list", "drugsbag_mark_type").subscribe((res) => {
		  this.markTypeList = res;
		});
	}

	//获取用户
	userSearch:any = [];
	searchUser(keyword) {
	  let data = {
	    user: {
	      // usertype: { id: 106 },
	      name: keyword,
	      hospital: {
	        id: this.hosId,
	      },
	    },
	    idx: 0,
	    sum: 10,
	  };
	  this.mainService
	    .getFetchDataList("data", "user", data)
	    .subscribe((data) => {
	      if (data.status == 200) {
					this.isLoading = false;
					this.userSearch = data.list;
	      }
	    });
	}

	// 搜索用户
	changeUserInp(e){
		this.isLoading = true;
		this.changeUserInpSubject.next(e);
	}

	// 日期选择
	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.searchCriteria.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.searchCriteria.dateRange = [dateStart,dateEnd];
	  }
	}

  // 重置
  reset() {
    this.searchCriteria = {
      //搜索条件
      packid: "",
      launch: null,
      target: null,
      drugsState: null,
			receiverName: null,
			drugsBagType: null,
			dateRange:[]
    };
		this.startDate = null;
		this.endDate = null;
    this.getList(1);
  }

  // 获取所有院区
  getHospital() {
    this.hosId = this.tool.getCurrentHospital().id;
    this.getList(1);
  }
  // 查看标本历史记录
  historyPromptModalShow = false; //标本历史记录弹窗开关
  scode = ""; //查看历史记录携带
  viewSpecimenHistory(data) {
    this.scode = data.scode;
    this.historyPromptModalShow = true;
  }
  // 关闭标本历史记录弹窗
  closeModelHistory(e) {
    this.historyPromptModalShow = JSON.parse(e).show;
  }
  // 打开搜索框
  changeSearch(flag) {
    if (flag) {
      this.changeInp("no");
    }
  }
  // 边输边搜节流阀
  isLoading = false;
  changeInp(dept) {
    if (!dept) {
      return;
    }
    if (dept === "no") {
      dept = "";
    }
    this.isLoading = true;
    this.changeSearchSubject.next(dept);
  }
  // 搜索科室
	deptList1:any = [];
	deptList2:any = [];
  searchDept(dept, type) {
    let postData = {
      department: {
        hospital: { id: this.hosId },
        dept,
      },
      idx: 0,
      sum: 10,
    };
    this.mainService
      .getFetchDataList("data", "department", postData)
      .subscribe((result) => {
        if (result.status == 200) {
          this.isLoading = false;
					if(type == 1){
						this.deptList1 = result.list;
					}else{
						this.deptList2 = result.list;
					}
        }
      });
  }

	getDept(dept){
		let postData = {
		  department: {
		    hospital: { id: this.hosId },
				dept,
		  },
		  idx: 0,
		  sum: 10,
		};
		this.mainService
		  .getFetchDataList("data", "department", postData)
		  .subscribe((result) => {
		    if (result.status == 200) {
		      this.isLoading = false;
					this.deptList = result.list;
		      this.deptList1 = result.list;
					this.deptList2 = result.list;
		    }
		  });
	}

	// 查看
	detail(e, data) {
		if(!data.workOrderDTO){
			return
		}
	  e.stopPropagation();
	  this.router.navigateByUrl("/main/drugSearch/orderDetail/" + data.workOrderDTO.id);
	}

	// 新增弹框
	modal:boolean = false;
	add:boolean = false;
	addMoadl() {
		this.getDept('');
	  this.add = true;
		this.modal = true;
		this.itemData = null;
	  this.initForm();
	}
	hideModal() {
		this.getDept('');
	  this.modal = false;
	  this.initForm();
	}

	// 搜索科室
	changeDept(dept, type){
		this.isLoading = true;
		this.changeInpSubject.next([dept, type]);
	}

	// 初始化新增form表单
	initForm() {
	  this.validateForm = this.fb.group({
			packid:[null, [Validators.required]],
	    batchNo: [null, []],
	    launch: [null, [Validators.required]],
			target: [null, [Validators.required]],
	    creatTime: [null, [Validators.required]],
	    drugsState: [null, [Validators.required]],
			drugsBagType: [null, []],
			markType: [null, []],
	  });
	}

	// // 选择开始时间
	onStartChange(result: Date): void {
		console.log('Selected Time: ', result);
		let startTime = format(result, 'yyyy-MM-dd HH:mm:ss');
		this.validateForm.controls.creatTime.setValue(startTime);
	}

	// 表单提交
	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 = {
			drugsBag:{
				...this.itemData,
				packid: this.validateForm.value.packid,
				batchNo: this.validateForm.value.batchNo || undefined,
				drugsState: {
					id: this.validateForm.value.drugsState
				},
				drugsBagType: {
					id: this.validateForm.value.drugsBagType
				},
				markType: {
					id: this.validateForm.value.markType
				},
				launch: {
					id:this.validateForm.value.launch
				},
				target: {
					id:this.validateForm.value.target
				},
				creatTime: this.validateForm.value.creatTime,
				id:0,
			}
	  };
	  if (!that.add) {
	    data.drugsBag.id = that.coopId;
	  }else{
			delete data.drugsBag.id
		}
		if(this.validateForm.value.drugsBagType){
			data.drugsBag.drugsBagType.id = this.validateForm.value.drugsBagType
		}else{
			delete data.drugsBag.drugsBagType
		}
		if(this.validateForm.value.markType){
			data.drugsBag.markType.id = this.validateForm.value.markType
		}else{
			delete data.drugsBag.markType
		}
		that.btnLoading = true;
	  that.mainService
	    .dataPost(this.add ? "addData":"updData", "drugsBag", data)
	    .subscribe((data) => {
	      that.btnLoading = false;
	      if (data.status == 200) {
					that.hideModal();
	        that.showPromptModal(that.add ? "新增" : "编辑", true, "");
	      } else {
	        that.showPromptModal(that.add ? "新增" : "编辑", false, data.msg);
	      }
	    });
	}

	// 编辑
	itemData:any;
	coopId:any;
	edit(data) {
		this.add = false
		this.initForm();
		this.itemData = data;
		this.coopId = data.id;
		this.validateForm.controls.packid.setValue(data.packid || '');
		this.validateForm.controls.batchNo.setValue(data.batchNo || '');
		this.validateForm.controls.launch.setValue(data.launch.id);
		this.validateForm.controls.target.setValue(data.target.id)
		this.validateForm.controls.drugsState.setValue(data.drugsState.id)
		this.validateForm.controls.drugsBagType.setValue(data.drugsBagType && data.drugsBagType.id)
		this.validateForm.controls.markType.setValue(data.markType && data.markType.id)
		this.validateForm.controls.creatTime.setValue(data.creatTime);
		let item = this.deptList1.find(i=>i.id == data.launch.id)
		if(!item){
			this.deptList1.push({
				dept: data.launch.dept,
				id: data.launch.id,
			})
		}
		let item2 = this.deptList2.find(i=>i.id == data.target.id)
		if(!item2){
			this.deptList2.push({
				dept: data.target.dept,
				id: data.target.id,
			})
		}
		this.modal = true
	}

	// 自动生成
	autoCreateModal:boolean = false;
	autoCreate(){
		this.autoCreateModal = true
		this.initAutoForm()
	}

	// 初始化form
	validateAutoForm: FormGroup
	initAutoForm(){
		this.validateAutoForm = this.fb.group({
			launch: [null, [Validators.required]],
			drugsBagType: [null, [Validators.required]],
			markType: [null, []],
			target: [null, []],
			amount: [1, []],
			sendMsg: ['0', []],
		});
	}

	numChange(e){
		console.log(4, e)
	}

	hideAutoModal(){
		this.autoCreateModal = false
	}

	// 自动生成提交
	submitAutoForm(){
		var that = this;
		for (const i in that.validateAutoForm.controls) {
		  that.validateAutoForm.controls[i].markAsDirty();
		  that.validateAutoForm.controls[i].updateValueAndValidity();
		}
		if (that.validateAutoForm.invalid) return;
		let data = {
			drugsBag:{
				target: this.validateAutoForm.value.target || undefined,
				launch: this.validateAutoForm.value.launch || undefined,
				sendMsg: this.validateAutoForm.value.sendMsg || undefined,
				drugsBagType: {
					id: this.validateAutoForm.value.drugsBagType
				},
				markType: {
					id: this.validateAutoForm.value.markType
				},
			}
		};
		that.btnLoading = true;
		that.mainService
		  .autoMake("drugsBag", this.validateAutoForm.value.amount, data)
		  .subscribe((data:any) => {
		    that.btnLoading = false;
		    that.hideAutoModal();
		    that.initAutoForm();
		    if (data.status == 200) {
		      that.showPromptModal("生成", true, "");
		    } else {
		      that.showPromptModal("生成", false, data.msg);
		    }
		  });
	}

	// 消息发送
	sendModal:boolean = false;
	sendMsg(data){
		this.itemData = data;
		this.sendModal = true
	}

	// 取消删除弹框
	cancelSend(){
		this.hideSendModal();
	}

	hideSendModal(){
		this.sendModal = false
	}

	// 确认发送
	confirmSend() {
	  let that = this;
		let query = {
			drugsBag:{
				...this.itemData,
				operationType:'sendMsg'
			}
		}
	  that.btnLoading = true;
	  that.mainService
	    .dataPost("updData", "drugsBag", query)
	    .subscribe((data) => {
	      that.btnLoading = false;
				this.hideSendModal();
	      if (data.status == 200) {
	        that.showPromptModal("发送", true, "");
	      } else {
	        that.showPromptModal("发送", false, data.msg);
	      }
	    });
	}

  // 表格数据
  loading1 = false;
  getList(type) {
    if (type == 1) {
      this.pageIndex = 1;
    }
    let postData: any = {
      idx: this.pageIndex - 1,
      sum: this.pageSize,
      drugsBag: {
        hosId: this.hosId,
        drugsState: this.searchCriteria.drugsState ? { id: this.searchCriteria.drugsState } : undefined,
				startTime: this.startDate || undefined,
				endTime: this.endDate || undefined,
				drugsBagType:{
					id:null
				},
				deliveryUser:{
					id:null
				}
			},
    };
    if (this.searchCriteria.target) {
      postData.drugsBag.target = { id: this.searchCriteria.target };
    }
    if (this.searchCriteria.launch) {
      postData.drugsBag.launch = { id: this.searchCriteria.launch };
    }
    if (this.searchCriteria.packid) {
      postData.drugsBag.packid = this.searchCriteria.packid;
    }
		if (this.searchCriteria.receiverName) {
		  postData.drugsBag.deliveryUser.id = this.searchCriteria.receiverName;
		}else{
			delete postData.drugsBag.deliveryUser
		}
		if (this.searchCriteria.drugsBagType) {
		  postData.drugsBag.drugsBagType.id = this.searchCriteria.drugsBagType;
		}else{
			delete postData.drugsBag.drugsBagType
		}
    this.loading1 = true;
    this.mainService
      .getFetchDataList("drugsBag", "drugsBag", postData)
      .subscribe((data) => {
        this.loading1 = false;
        if (data["status"] == 200) {
          this.listOfData = data["list"];
          this.listLength = data["totalNum"];
        }
      });
  }
}
