import { Component, OnInit, ViewChild, OnDestroy } from "@angular/core";
import { MainService } from "../../services/main.service";
import { ActivatedRoute, Router } from "@angular/router";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { startOfDay, format, endOfDay } from "date-fns";
import { ToolService } from 'src/app/services/tool.service';
import { NzMessageService, UploadFile } from "ng-zorro-antd";
import { debounceTime, filter } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { DomSanitizer } from '@angular/platform-browser';
import cloneDeep from 'lodash-es/cloneDeep'
import { HttpRequest, HttpResponse, HttpClient } from '@angular/common/http';
import {
  FormBuilder,
  Validators,
  FormGroup,
  FormControl,
} from "@angular/forms";

@Component({
  selector: "app-web-repairs",
  templateUrl: "./web-repairs.component.html",
  styleUrls: ["./web-repairs.component.less"],
})
export class WebRepairsComponent implements OnInit {
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef2", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef2: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef3", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef3: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef4", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef4: OverlayScrollbarsComponent;
  @ViewChild("osComponentRef5", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef5: OverlayScrollbarsComponent;
  constructor(
	private mainService: MainService,
	public router: Router,
	private route: ActivatedRoute,
	public tool: ToolService,
	private fb: FormBuilder,
	private message: NzMessageService,
	private sanitizer: DomSanitizer,
	private http: HttpClient,
	
	) {}
  // 今日药单量
  todayTotal: undefined;
  // 今日已完成
  todayComplete: undefined;
  //手术间数据
  printPharmacyList = []; //数据列表
  printPharmacyIdx = 0; //页码
  printPharmacyTotal = 0; //总数
  printPharmacyFlag = false; //是否查看更多
  printPharmacySearchKey = ""; //搜索的内容
  printPharmacyLoad = false; //按钮的loading
  // 标本间列表
  waitPharmacyList = [];
  waitPharmacyIdx = 0;
  waitPharmacyTotal = 0;
  waitPharmacyFlag = false;
  waitPharmacySearchKey = "";
  waitPharmacyLoad = false;
  // 今日离科列表
  pharmacyList = [];
  pharmacyIdx = 0;
  pharmacyTotal = 0;
  pharmacyFlag = false;
  pharmacySearchKey = "";
  pharmacyLoad = false;
  // 配送中列表
  distributionList = [];
  distributionIdx = 0;
  distributionTotal = 0;
  distributionFlag = false;
  distributionSearchKey = "";
  distributionLoad = false;
  // 已完成列表
  completedList = [];
  completedIdx = 0;
  completedTotal = 0;
  completedFlag = false;
  completedSearchKey = "";
  completedLoad = false;

	barCode:any; //条码搜索
  // other
  loginUser: any = localStorage.getItem("user")
    ? JSON.parse(localStorage.getItem("user")).user
    : null; //登录人信息

  logTimer = null; //定时器
  logTime = 0; //自动刷新秒数
  logTimeConst = 60; //自动刷新秒数

  time = new Date().getTime(); // 时间戳
  timer = null; // 时间定时器
	showDropdown:boolean = false;
	relevanceModal:boolean = false //关联标本和手术室
	validateForm: FormGroup; //关联标本和手术室表单
	validateVerificationForm: FormGroup; //核验标本
	validateConnectForm: FormGroup; //核验标本
	specimenData:any = []; //标本间数据
	operationData:any = []; //手术间数据
	fixationModal:boolean = false //标本接收固定
	verificationMoadl:boolean = false //标本核验
	specimenCode:any; //标本条码
	listOneData:any=[];
	listOneLength:any;
	pageOneIndex:any = 1;
	pageSize:any = 10;
	listTwoData:any=[];
	listTwoLength:any;
	pageTwoIndex:any = 1;
	listThreeData:any=[];
	listThreeLength:any;
	pageThreeIndex:any = 1;
	loading1:boolean = false;
	loading2:boolean = false;
	loading3:boolean = false;
	loading4:boolean = false;
	loading5:boolean = false;
	fixativeData:any = []; //固体液类型
	hosId:any;
	userId:any;
	detailsData:any;
	isSpinning:boolean = false; //全屏加载状态
	codeData:any = []; //标本条码数据
	btnInfoLoading :boolean = false; //标本加固加载
	activeIndex:any = 0; //tabs选择状态
	changeInpSubject = new Subject(); //防抖
	changeInpSubjectUser = new Subject(); //防抖
	changeInpSubjectSpecimen = new Subject(); //防抖
	changeInpSubjectDepartment = new Subject(); //防抖
	pathologyFormType:any = null; //术中快速
	status:any; //状态
	incidentsign:any //配送人
	userData:any = []; //患者数据
	statusData:any = []; //状态数据
	isLoading:boolean = false;
	listDetailMoadl:boolean = false; //详情弹框
	department:any = []; //科室数据
	hospital:any = []; //院区数据
	distributionName:any;
	businessType:any = null;
	multiModal:boolean = false;
	specimenMultiCode:any = null;
	codeMultiData:any=[];
	errorMultiMsg:any = null;
	connectModal:boolean = false; //标本交接弹框
	receptionModal:boolean = false; //标本接收弹框
	deptId:any = null;
	detailMoadl:boolean = false;
	rowData:any = null; //table选中数据
	toDayData:any = null;
	toDayTime:any = null;
	backType:any = 'list';
	mainRole:any = false;
	coopBtns:any = {};
	deptName:any = null;
	loginUserDeptId: number = JSON.parse(localStorage.getItem("user")).user.dept
	  .id; //登录人所属科室
	
	buildingData:any = [];
	floorData:any = [];
	userInfo:any;
	currentDept:any;
  ngOnInit() {
		this.coopBtns = this.tool.initCoopBtns(this.route);
		this.hosId = this.tool.getCurrentHospital().parent ? this.tool.getCurrentHospital().parent.id : this.tool.getCurrentHospital().id;
		this.userId = this.tool.getCurrentUserId()
		this.deptId = this.tool.getCurrentUserDept().id
		this.deptName = this.tool.getCurrentUserDept().dept
		this.userInfo = this.tool.getCurrentUserInfo();
		this.currentDept = this.tool.getCurrentUserDept();
		if(this.route.snapshot.queryParams && this.route.snapshot.queryParams.type){
			this.backType = this.route.snapshot.queryParams.type
		}
		this.getStatusDic();
		this.getDegrees();
  }
	
	// 初始化新增form表单
	initNum:any = 0;
	initBxForm(content) {
		this.initNum++;
	  this.validateBxForm = this.fb.group({
	    description: [content || null, [Validators.required]],
	    building: [null, [Validators.required]],
	    floor: [null, [Validators.required]],
	    officeAddress: [null, [Validators.required]],
	    contacts: [this.loginUser.name, [Validators.required]],
	    contactsInformation: [this.loginUser.phone, [Validators.required]],
	  });
		this.changeHosp();
		// if(this.userInfo.buildingDTO){
		// 	this.changeHosp();
		// }else{
		// 	this.getUserInfo();
		// }
	}
	// 查询用户信息
	deptDto:any = {};
	getUserInfo(){
		// 回显楼栋
		if(this.userInfo.buildingDTO){
		  this.validateBxForm.controls.building.setValue(this.userInfo.buildingDTO.id);
		}
		// 回显楼层
		if(this.userInfo.floorDTO){
		  this.validateBxForm.controls.floor.setValue(this.userInfo.floorDTO.id);
		}
		if(this.userInfo.address){
			this.validateBxForm.controls.officeAddress.setValue(this.userInfo.address);
		}	
		if(this.userInfo.name){
			this.validateBxForm.controls.contacts.setValue(this.userInfo.name);
		}
		if(this.userInfo.phone){
			this.validateBxForm.controls.contactsInformation.setValue(this.userInfo.phone);
		}
	}
	// 切换院区选项
	buildings: any = []; //楼栋
	changeHosp() {
	  this.buildings = [];
	  let data = {
	    idx: 0,
	    sum: 9999,
	    building: {
	      hosId: this.hosId,
	    }
	  };
	  this.mainService
	    .getFetchDataList("simple/data", "building", data)
	    .subscribe((data:any) => {
	      this.buildings = data.list || [];
	      this.maskFlag = false;
				this.getUserInfo();
	    });
	}
	
	// 切换楼栋信息
	floors: Array<any> = []; //楼层
	floorLoading: boolean = false;
	changeBuilding(buildingId) {
	  if(!buildingId){
	    return;
	  }
		this.validateBxForm.controls.floor.setValue(null);
		this.validateBxForm.controls.officeAddress.setValue(null);
	  this.floors = [];
	
	  let data = {
	    idx: 0,
	    sum: 9999,
	    floor: {
	      buildId: buildingId,
	    }
	  };
	  this.floorLoading = true;
	  this.mainService
	    .getFetchDataList("simple/data", "floor", data)
	    .subscribe((data:any) => {
	      this.floorLoading = false;
	      this.message.remove(this.maskFlag);
	      this.maskFlag = false;
	      this.floors = data.list || [];
	    });
	}
	
	// 快速报修
	bxModal: boolean = false; //模态框
	loading6 = false;
	coopBx: any; //当前操作列
	maskFlag:any;
	fileList:any = [];
	validateBxForm: FormGroup; //新增/编辑表单
	speediness(data?) {
	  this.bxModal = true;
	  this.coopBx = data || {};
		this.fileList = [];
	  this.initBxForm(this.coopBx.content);
	}
	// 隐藏模态框
	hideBxModal() {
		this.initNum = 0;
	  this.bxModal = false;
		this.fileList = [];
	}
	// 确认
	confirmBx() {
	  for (const i in this.validateBxForm.controls) {
	    this.validateBxForm.controls[i].markAsDirty();
	    this.validateBxForm.controls[i].updateValueAndValidity();
	  }
	  if (this.validateBxForm.invalid){
	    this.message.error('请填写必填字段！');
	    return;
	  };
	  this.showReqModal();
	}
	
	// 报修提示框
	reqModal: boolean = false;
	extraData:any = {};
	showReqModal() {
	  this.extraData.floor = this.floors.find(v => v.id == this.validateBxForm.value.floor);
	  // this.reqModal = true;
	  this.confirmBxNext(0);
	}
	
	// 报修
	// type, 1是，0否
	cancenlLoading:boolean = false;
	async confirmBxNext(type){
	  this.maskFlag = this.message.loading("正在加载中..", {
	    nzDuration: 0,
	  }).messageId;
	  if(type == 1){
	    this.btnLoading = true;
	    let loginUser:any = cloneDeep(this.loginUser);
			// loginUser.upType = "changeDept";
	    if(this.deptDto.hospital){
	      loginUser.hospital = { id: this.deptDto.hospital.id };
	    }
	    if(this.deptDto){
	      loginUser.dept = {id: this.deptDto.id};
	    }
	    if(this.validateBxForm.value.contacts){
	      loginUser.name = this.validateBxForm.value.contacts;
	    }
	    // if(this.validateBxForm.value.floor){
	    //   loginUser.place = {id: this.validateBxForm.value.floor, area: { id: this.validateBxForm.value.building }};
	    // }
	    // if(this.validateBxForm.value.officeAddress){
	    //   loginUser.houseNumber = this.validateBxForm.value.officeAddress;
	    // }
	    if(this.validateBxForm.value.contactsInformation){
	      loginUser.phone = this.validateBxForm.value.contactsInformation;
	    }
	    let result:any = await this.mainService.coopData("updData", "user", { user: loginUser }).toPromise();
	    console.log(result);
	    if(result.status != 200){
	      this.hideReqModal();
	      this.btnLoading = false;
	      this.message.remove(this.maskFlag);
	      this.maskFlag = false;
	      this.message.error(result.msg);
	      return;
	    }
	  }else{
	    this.cancenlLoading = true;
	  }
	  this.mainService.getDictionary("list", "incident_source").subscribe((source:any) => {
	    let incidentSourceList = source || [];
	    let pc = incidentSourceList.find(v => v.value === 'pc');
	    this.mainService.getDictionary("list", "repair_incident_type").subscribe((result) => {
	      let repairIncidentTypeList = result || [];
	      let repairIncidentType = repairIncidentTypeList.find(v => v.value === 'public');
	      if (repairIncidentType) {
	        let postData: any = {
	          incident: {
	            repairIncidentType,
	            place: this.validateBxForm.value.floor ? { id: this.validateBxForm.value.floor } : undefined,
	            description: this.validateBxForm.value.description,
	            houseNumber: this.validateBxForm.value.officeAddress,
	            contacts: this.validateBxForm.value.contacts,
	            contactsInformation: this.validateBxForm.value.contactsInformation,
	            hosId: this.hosId,
	            source: pc,
	            fromWx: true,
	            requester: this.loginUser,
	            acceptUser: this.loginUser,
	            deleteFlag: 0,
	          },
	        };
	        if (this.coopBx.category) {
	          postData.incident.category = this.coopBx.categoryDTO;
	        }
	        this.mainService.flowPost("incident/task/request", postData).subscribe((res) => {
	          this.btnLoading = false;
	          this.cancenlLoading = false;
	          this.message.remove(this.maskFlag);
	          this.maskFlag = false;
	          this.bxModal = false;
	          this.hideReqModal();
	          if ((res as any).state == 200) {
							this.initNum = 0;
							// 图片上传
							if(this.fileList.length){
								console.log(this.fileList.map(v => v.originFileObj));
								this.fileList.map(v => v.originFileObj).forEach(async file => {
									await this.uploadImages(file, res.data.id);
								})
							}
							this.getConnectList()
	            this.showPromptModal("提交", true, "");
	          } else {
	            this.showPromptModal("提交", false, (res as any).msg);
	          }
	        });
	      } else {
	        this.btnLoading = false;
	        this.showPromptModal("提交", false, "缺少【科室内报修】数据字典");
	      }
	    });
	  })
	}
	
	hideReqModal() {
	  this.reqModal = false;
	}
	
	// 获取星级
	degrees = [];
	getDegrees() {
	  this.iLoading = true;
	  this.mainService.getDictionary("list", "incident_degree").subscribe((data: any) => {
	    this.iLoading = false;
	    this.degrees = data || [];
	  });
	}
	iLoading = false;
	
	// 报修评价
	appraiseModalBx: boolean = false;
	starNumBx: number = 5; //评价星
	appraiseContentBx: string = ""; //评级
	appraiseDataBx: any;
	showAppraiseBx(data) {
	  this.appraiseDataBx = data;
	  this.appraiseModalBx = true;
	  this.starNumBx = 5;
	  this.appraiseContentBx = "";
	}
	// 保存评价
	confirmAppraiseBx() {
	  console.log(this.starNumBx, this.appraiseContentBx);
	  if (!this.starNumBx) return;
	  this.btnLoading = true;
	  let id = this.degrees.find(v=>v.value == this.starNumBx).id;
	  let postData = {
	    incident: {
	      ...this.appraiseDataBx,
	      wxdegree: { id },
	      wxdegreeremark: this.appraiseContentBx,
	    }
	  };
	  this.mainService
	    .flowPost("incident/task/resolve", postData)
	    .subscribe((data:any) => {
				this.btnLoading = false;
	      this.hideAppraiseBx();
	      if (data.state == 200) {
	        this.getConnectList();
	        this.showPromptModal("评价", true, "");
	      } else {
	        this.showPromptModal("评价", false, data.msg);
	      }
	    });
	}
	hideAppraiseBx() {
	  this.appraiseModalBx = false;
	}
	
	// 预览图片
	imgs = [];
	isPreview = false;
	initialViewIndex:number = 0;
	previewImageHandler(data = [], index = 0) {
	  this.initialViewIndex = index;
	  console.log(index)
	  this.isPreview = false;
	  data = data || [];
	  this.imgs = data.map((v) => location.origin + '/file' + v.relativeFilePath);
	  setTimeout(() => {
	    this.isPreview = true;
	  }, 0)
	}
	
	// 图片相关
	showUploadList = {
	  showPreviewIcon: true,
	  showRemoveIcon: true,
	  hidePreviewIconInNonImage: true
	};
	previewImage: string | undefined = '';
	previewVisible = false;
	repairImgs:any[] = [];//报修图片
	handlePreview = (file: UploadFile) => {
		console.log('file1:', file)
	  this.previewImage = file.url || file.thumbUrl;
	  this.previewVisible = true;
	};
	
	beforeUpload = (file: UploadFile): boolean => {
		console.log('file2:', file)
	  this.fileList = [...this.fileList, file];
	  setTimeout(async () => {
	    file.url = await this.getBase64(file);
	  }, 0);
	  console.log('this.fileList:', this.fileList)
	  return true;
	};
	
	getBase64(file: any): Promise<any> {
	  return new Promise((resolve, reject) => {
	    const reader = new FileReader();
	    reader.readAsDataURL(file);
	    reader.onload = () => resolve(reader.result);
	    reader.onerror = error => reject(error);
	  });
	}
	
	// 临时上传图片
	temporarilyUrl = this.mainService.returnUploadUrl('wechatRequesterIncident', 0);
	
	// 图片上传
	uploadImages(file, id){
	  const formData = new FormData();
	  formData.append('file', file);
	  formData.append('fileName', file.name);
	  const req = new HttpRequest('Post', this.mainService.returnUploadUrl('wechatRequesterIncident', id), formData, {
	    reportProgress: true
	  });
	  return this.http.request(req).pipe(filter(e => e instanceof HttpResponse)).toPromise();
	}
	
	isAllDisplayDataChecked:any = false;
	isOperating:any  = false;
	isIndeterminate:any = false;
	listOfAllData: any = [];
	mapOfCheckedId: { [key: string]: boolean } = {};
	numberOfChecked = 0;
	selectedData:any = null;
	
	// 获取状态字典
	repairIncidentTypeList:any;
	sourceData:any;
	getStatusDic(){
		this.mainService.getDictionary("list", "incident_status").subscribe((res) => {
			this.statusData = res
		});
		
		this.mainService.getDictionary("list", "incident_source").subscribe((res) => {
			this.sourceData = res.find(i=>i.value == 'pc')
			this.mainService.getDictionary("list", "repair_incident_type").subscribe((res) => {
				this.repairIncidentTypeList = res
				this.getConnectList()
			});
		});
		
	}

	// 搜索
	search() {
	  this.pageOneIndex = 1;
	  this.getConnectList();
	}
	// 重置
	reset() {
	  this.pageOneIndex = 1;
		this.status = null;
		this.incidentsign = null;
		this.startDate = format(startOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
		this.endDate = format(endOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
		this.acceptTime = [this.startDate,this.endDate];
	  this.getConnectList();
	}
	// 交接本数据
	getConnectList() {
	  var that = this;
	  let data = {
	    idx: that.pageOneIndex - 1,
	    sum: that.pageSize,
	    incident: {
				incidentsign: this.incidentsign || undefined,
				statusId: this.status || undefined,
	    	requester: {
					id: this.userId
				},
				source:{
					id: this.sourceData.id
				},
				startDate_start: this.startDate,
				startDate_end: this.endDate
	    }
	  };
	  this.loading1 = true;
	  that.mainService
	    .getFetchDataList("simple/data", "incident", data)
	    .subscribe((data) => {
	      this.loading1 = false;
	      that.listOneData = data.list;
	      that.listOneLength = data.totalNum;
	    });
	}
	
	// 报修撤销模态框
	delBxModal: boolean = false;
	delBxData: any; //删除的data
	delBx(data) {
	  this.delBxData = data;
	  this.delBxModal = true;
	}
	confirmDelBx() {
	  this.btnLoading = true;
	  this.mainService
	    .flowPost("incident/task/cancel", { incident: this.delBxData })
	    .subscribe((result) => {
	      if(result.state == 200){
	        this.delBxModal = false;
	        this.showPromptModal("撤销", true, "");
	        this.getConnectList();
	      }else{
	        this.delBxModal = false;
	        this.showPromptModal("撤销", false, result.msg);
	      }
	    });
	}
	hideDelBxModal() {
	  this.delBxModal = false;
	}
	
	// 查看
	detailBx(data){
	  this.router.navigateByUrl("webRepairs/detailBx/" + data.id);
	}
	
	// 获取院区
	getHospitalData(){
		let arr = this.tool.getHospitalList().filter(i=>i.parent==undefined)
		this.hospital = arr
	}

	// 选择院区
	hospitalId:any=null;
	changeHospDate(e){
		this.validateForm.controls.department.setValue(null)
		this.hospitalId = e
		this.getDepartmentData('',e)
	}

	// 获取科室
	isDeptLoading:boolean = false;
	getDepartmentData(e,hospital){
		// this.mainService.getDictionary("list", "dept_type").subscribe((res2) => {
			// let item = res2.find(i=>i.name=='检验科室')
			let data = {
			  idx: 0,
			  sum: 999,
			  department: {
					dept:e,
			    hospital: { id: this.hospitalId || "" },
			    type: {id:null},
			  },
			};
			this.mainService
			  .getFetchDataList("data", "department", data)
			  .subscribe((res) => {
					this.isDeptLoading = false
			    this.department = res.list;
			  });
		// });
	}

	// 接收时间
	startDate:any = format(startOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
	endDate:any = format(endOfDay(new Date()), "yyyy-MM-dd HH:mm:ss");
	acceptTime:any = [this.startDate,this.endDate];
	changeDate(result){
		if(result.length>0){
			this.startDate = format(result[0], 'yyyy-MM-dd' +' '+'00:00:00');
			this.endDate = format(result[1], 'yyyy-MM-dd' +' '+'23:59:59');
			this.acceptTime = [this.startDate,this.endDate]
		}else{
			this.startDate = null;
			this.endDate = null;
			this.acceptTime = []
		}
	}

	// 获取当前用户信息
	getCurrentUserNow() {
	  this.mainService.getCurrentUser1().subscribe((data:any) => {
	    if (data["status"] == 200) {
				this.userInfo = data.data;
				let user = JSON.parse(localStorage.getItem("user"));
				user.user.name = data["data"].name;
				user.user.account = data["data"].account;
				user.user.floorDTO = data["data"].floorDTO;
				user.user.buildingDTO = data["data"].buildingDTO;
				user.user.phone = data["data"].phone;
				user.user.address = data["data"].address;
				localStorage.setItem("user", JSON.stringify(user));
	    }
	  });
	}

	// 成功/失败提示框
	closeModel(){
		
	}


	pathologyLogs:any=[];
	specimenList:any=[]
	stepLength:any = 0;
	closeDetailMoadl(){
		this.detailMoadl = false
	}

  // 退出
  logOut(): void {
    // 假退出
    let hospital = this.tool.getCurrentHospital();
    if(hospital){
      this.router.navigate(["login", hospital.id]);
    }else{
      this.router.navigateByUrl("login");
    }
    localStorage.removeItem("user");
    localStorage.removeItem("menu");
    localStorage.removeItem("index");
		localStorage.removeItem("scanCodeData");
		localStorage.removeItem("dataType");
		localStorage.removeItem("pathologyActiveIndex");
    // 假退出
    this.mainService.logOut().subscribe((data) => {
      if (data.status == 200) {
        if(hospital){
          this.router.navigate(["login", hospital.id]);
        }else{
          this.router.navigateByUrl("login");
        }
        localStorage.removeItem("user");
        localStorage.removeItem("menu");
        localStorage.removeItem("index");
				localStorage.removeItem("scanCodeData");
				localStorage.removeItem("dataType");
				localStorage.removeItem("pathologyActiveIndex");
      }
    });

  }

  // 右侧菜单
  showLastItems: boolean = false;
  // 下拉
  fixedMenuXiala() {
    this.showLastItems = true;
  }

  // 上拉
  fixedMenuShangla() {
    this.showLastItems = false;
  }
	
	// 回到系统管理
	toMain() {
	  this.router.navigateByUrl("main");
	}
	
  // 切换右侧菜单Tab
  fixedTab: string = "";
  checkFixedTab(type: string) {
    if (type == "toSystem") {
      this.router.navigateByUrl("main");
    }
    if (this.fixedTab == type) {
      this.fixedTab = "";
    } else {
      this.fixedTab = type;
    }
  }
	
  //科室切换
  changeShow = true;
  closeTime = 3;
  closeTimeFlag = 0;
  hsPromptModalShow: boolean = false; //科室切换提示框是否展示
  timerCloseTime = null;
  deptDisplay = 1; //护士端是否显示可以别名，1是显示科室名称，2是显示科室别名
  // 修改密码
	isPwdVisible:boolean = false
  etitPasswrod() {
    this.isPwdVisible= true;
  }
	
	//打开修改密码弹窗
	pwdAfterOpen(){
	  this.passwordVisible = false;
	  this.pwdIsOkLoading = false;
	  this.enoughRegFlag = true; //弱
	  this.mediumRegFlag = false; //中
	  this.strongRegFlag = false; //强
	  this.upModalData = {
	    userid: "",
	    pwdOld: "",
	    newPwd: "",
	    newPwd2: "",
	  };
	}
	
	// 修改密码
	passwordVisible = false;
	password?: string;
	pwdIsOkLoading = false;
	upModalData = {
	  userid: "",
	  pwdOld: "",
	  newPwd: "",
	  newPwd2: "",
	};
	upPwd(): void {
	  if(this.upModalData.pwdOld.trim() === ''){
	    this.message.error('请填写原始密码！', {
	      nzDuration: 5000,
	    });
	    return;
	  }
	  if(!this.strongRegFlag){
	    this.message.error('新密码不符合要求！', {
	      nzDuration: 5000,
	    });
	    return;
	  }
	  if(this.upModalData.newPwd !== this.upModalData.newPwd2){
	    this.message.error('新密码与确认新密码不一致！', {
	      nzDuration: 5000,
	    });
	    return;
	  }
	
	  this.pwdIsOkLoading = true;
	  let userid = JSON.parse(localStorage.getItem("user")).user.id;
	  this.upModalData.userid = userid;
	  this.mainService.upPwd(this.upModalData).subscribe((data) => {
	    if (data.status == 200) {
	      this.isPwdVisible = false;
	      this.pwdIsOkLoading = false;
	      this.message.success("修改成功！", {
	        nzDuration: 5000,
	      });
	    } else {
	      this.pwdIsOkLoading = false;
	      this.message.error(data.error, {
	        nzDuration: 5000,
	      });
	    }
	  });
	}
	showUpPwd(): void {
	  this.isPwdVisible = true;
	}
	
	pwdHandleOk(): void {
	  this.upPwd();
	}
	
	pwdHandleCancel(): void {
	  this.isPwdVisible = false;
	}
	
	// 新密码失去焦点
	enoughRegFlag = true; //弱
	mediumRegFlag = false; //中
	strongRegFlag = false; //强
	blurNewPwd(){
	  let enoughReg = /^.{0,6}$/;//密码强度-弱
	  let strongReg = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\!\@\#\$\%\^\&\*]).{9,}$/;//密码强度-强
	  this.enoughRegFlag = enoughReg.test(this.upModalData.newPwd);
	  this.strongRegFlag = strongReg.test(this.upModalData.newPwd);
	  this.mediumRegFlag = !this.enoughRegFlag && !this.strongRegFlag;
	  console.log(this.enoughRegFlag,this.mediumRegFlag,this.strongRegFlag);
	}
	
	// 修改个人信息
	infoModal:boolean = false
	editInfo() {
		this.initForm();
		this.getBuildingList('edit');
		setTimeout(_=>{
			this.validateForm.controls.name.setValue(this.userInfo.name);
			this.validateForm.controls.account.setValue(this.userInfo.account);
			this.validateForm.controls.phone.setValue(this.userInfo.phone?this.userInfo.phone:null);
			this.validateForm.controls.address.setValue(this.userInfo.address?this.userInfo.address:null);
			this.infoModal= true;
		})
	}
	
	// 楼栋列表
	buildingList:any = [];
	getBuildingList(type:any = '') {
		let postData = {
			idx: 0,
			sum: 9999,
			building: { hosId: this.hosId },
		};
		this.mainService
			.getFetchDataList("simple/data", "building", postData)
			.subscribe((result) => {
				if (result.status == 200) {
					this.buildingList = result.list;
					if(type=='edit'){
						this.validateForm.controls.buildingId.setValue(this.userInfo.buildingDTO?this.userInfo.buildingDTO.id +"":null);
						if(this.validateForm.value.buildingId){
							this.getAllFloor(type)
						}
					}
				}
			});
	}
	
	// 选择楼栋
	buildingChange(e){
		this.validateForm.controls.floorId.setValue(null);
		this.getAllFloor()
	}
	
	// 获取选中楼栋下楼层列表
	allFloorList:any = [];
	getAllFloor(type:any = '') {
		let postData = {
			idx: 0,
			sum: 9999,
			floor: { hosId: this.hosId, buildId: this.validateForm.value.buildingId },
		};
		this.mainService
			.getFetchDataList("simple/data", "floor", postData)
			.subscribe((result) => {
				if (result.status == 200) {
					this.allFloorList = result.list;
					if(type=='edit'){
						this.validateForm.controls.floorId.setValue(this.userInfo.floorDTO?this.userInfo.floorDTO.id+"":null);
					}
				}
			});
	}
	
	// 表单提交
	btnLoading:boolean = false;
	submitForm(): void {
	  var that = this;
	  for (const i in that.validateForm.controls) {
	    that.validateForm.controls[i].markAsDirty({ onlySelf: true });
	    that.validateForm.controls[i].updateValueAndValidity();
	  }
	  if (that.validateForm.invalid) return;
	  that.btnLoading = true;
	  let data = {
	    user: {
	      name: that.validateForm.value.name || null,
	      account: that.validateForm.value.account || null,
	      phone: that.validateForm.value.phone || null,
				buildingId: that.validateForm.value.buildingId || null,
				floorId: that.validateForm.value.floorId || null,
				address: that.validateForm.value.address || null,
				id: that.userId
	    },
	  };
	  that.mainService
	    .coopData("updData", "user", data)
	    .subscribe((data) => {
	      that.btnLoading = false;
	      that.hideModal();
	      that.initForm();
	      if (data.status == 200) {
	        that.showPromptModal("修改", true, "");
					this.getCurrentUserNow();
	      } else{
					that.showPromptModal("修改", false, data.msg);
				}
	    });
	}
	
	hideModal() {
	  this.infoModal = false;
	}
	
	// 初始化新增form表单
	initForm() {
	  this.validateForm = this.fb.group({
	    name: [null, [Validators.required]],
	    account: [null, [Validators.required]],
			buildingId: [null],
			floorId: [null],
			address: [null],
	    phone: [null],
	  });
	}
	
	promptModalShow:boolean = false;
	promptContent:any = null;
	ifSuccess:any = null;
	promptInfo:any = null;
	// 展示信息提示框（con:提示信息，success:操作是否成功，promptInfo:操作结果提示信息）
	showPromptModal(con, success, promptInfo?) {
	  this.promptModalShow = false;
	  this.promptContent = con;
	  this.ifSuccess = success;
	  this.promptInfo = promptInfo;
	  setTimeout(() => {
	    this.promptModalShow = true;
	  }, 100);
	}
}

