import { Component, OnInit, TemplateRef, ViewChild } from "@angular/core";
import { NavigationEnd, Router } from "@angular/router";
import { MainService } from "../../services/main.service";

import { NzMessageService } from "ng-zorro-antd/message";
import { WebsocketMainService } from "../../services/websocket-main.service";
import http from "../../../assets/js/http";

import { NzNotificationService } from "ng-zorro-antd/notification";
import { OverlayScrollbarsComponent } from "overlayscrollbars-ngx";
import { ToolService } from "../../services/tool.service";
import { filter } from "rxjs/operators";

@Component({
  selector: "app-main",
  templateUrl: "./main.component.html",
  styleUrls: ["./main.component.less"],
})
export class MainComponent implements OnInit {
  userInfo: any = JSON.parse(localStorage.getItem("user"));
  menus: any = JSON.parse(localStorage.getItem("menu"));
  currentHospital; //当前院区
  routerEventsListener; //监听路由

  deskRole: boolean = false; //调度台权限
  nurseRole: boolean = false; //护士端权限
  pharmacyRole: boolean = false; //药房端权限
  largeScreenRole: boolean = false; //大屏端权限
  largeScreenRole2: boolean = false; //大屏端权限
  specimenViewRole: boolean = false; //业务视图权限
  specimenViewRole2: boolean = false; //标本视图权限
	specimenRoomView: boolean = false; //标本间权限
	pathology: boolean = false; //病理科权限
	sampling: boolean = false; //门诊病理采样端权限
	communicationBook: boolean = false; //病理交接本权限
  disinfectionSupplyRole: boolean = false; //全局业务查看权限
  realtimeBroadcastRole: boolean = false; //全局业务查看权限
  incidentConfigRole: boolean = false; //事件配置权限
  otherConfigRole: boolean = false; //三方配置权限
  pageConfigRole: boolean = false; //业务页面控制权限
  nurseConfigRole: boolean = false; //护士端配置控制权限
  PCCommutesToWork: boolean = false; //PC上下班权限
  newStatisticsRole: boolean = false; //新版统计权限
  @ViewChild("osComponentRef1", {
    read: OverlayScrollbarsComponent,
    static: false,
  })
  osComponentRef1: OverlayScrollbarsComponent;
  constructor(
    public router: Router,
    private mainService: MainService,
    private msg: NzMessageService,
    private notification: NzNotificationService,
    private webs: WebsocketMainService,
    public tool: ToolService
  ) {}
  ngOnInit() {
    this.highlightMenuByUrl();
    this.routerEventsListener = this.router.events
      .pipe(filter((event) => event instanceof NavigationEnd))
      .subscribe((event) => {
        this.highlightMenuByUrl();
      });
    this.currentHospital = this.tool.getCurrentHospital();
    this.initLogin();
    this.initMenu();
    this.getWebsocket();
  }

  // 离开管理端
  ngOnDestroy() {
    //取消路由监听
    this.routerEventsListener.unsubscribe();
    // 断掉连接
    this.webs.closeWs(true);
  }

  // 菜单图标名称是否包含transport-
  isTransportIcon(icon:any) {
    if(icon){
      return icon.indexOf("transport-") > -1;
    }else{
      return false;
    }
  }

  //上下班
  loading3 = false;
  workModal: boolean = false; //模态框
  showWorkModal() {
    this.workModal = true;
  }
  hideWorkModal() {
    this.workModal = false;
  }
  confirmWork() {
    this.loading3 = true;
    if (this.userInfo.user.online) {
      // 判断当前启用的工作方案是自主还是综合排班
      this.getUserWorkDept().then((ress:any) => {
        if (ress.status == 200) {
          let workType = ress.settings ? ress.settings.workType : -1; //1是综合，2是自主
          // 自主下班,并且是科室绑定人员,科室绑定分组，绑定分组
          if (workType == 2) {
            this.loading3 = false;
            this.msg.info('不支持此上班模式！');
          } else {
            this.mainService.onOrOffLine({
              type: "off",
            }).subscribe((res:any) => {
              if (res.status == 200) {
                this.getCurrentUserNow();
              } else {
                this.loading3 = false;
                this.msg.error('操作失败');
              }
            });
          }
        } else if (ress.status == 500) {
          //500的时候自选下班
          this.customOff();
        } else {
          this.loading3 = false;
          this.msg.error('操作失败');
        }
      });
    } else {
      this.getWorkScheme();
    }
  }

  // 获取启动中的工作分配方案
  workSchemeType:any = ""; //启动中工作分配方案类型
  getWorkScheme() {
    let postData = {
      idx: 0,
      workScheme: {
        status: 1,
        hosId: this.currentHospital.id
      },
      sum: 1,
    };
    this.mainService.getFetchDataList("simple/data", "workScheme", postData).subscribe((res) => {
      if (res.status == 200) {
        if(Array.isArray(res.list) && res.list.length){
          this.workSchemeType = res.list[0].workType;
          if (this.workSchemeType == 2) {
            this.loading3 = false;
            this.msg.info('不支持此上班模式！');
          } else if (this.workSchemeType == 1) {
            this.mainService.onOrOffLine({
              type: "on",
            }).subscribe((res:any) => {
              if (res.status == 200) {
                this.getCurrentUserNow();
              } else {
                this.loading3 = false;
                this.msg.error('操作失败');
              }
            });
          }
        }
      } else {
        this.loading3 = false;
        this.msg.error('操作失败');
      }
    });
  }

  // 下班
  customOff() {
    this.mainService.onOrOffLine({
      type: "off",
      customWorking: "off",
    }).subscribe((res:any) => {
      if (res.status == 200) {
        this.getCurrentUserNow();
      } else {
        this.loading3 = false;
        this.msg.error('操作失败');
      }
    });
  }

  // 获取执行中列表
  getWorkingNum() {
    return this.mainService.coopWorkerOrder("executingOrders", {
      idx: 0,
      sum: 1,
    }).toPromise();
  }

  // 获取启动中的工作分配方案
  getUserWorkDept() {
    return this.mainService.getUserWorkDept({}).toPromise();
  }

  // 获取当前用户信息
  getCurrentUserNow() {
    this.mainService.getCurrentUser1().subscribe((data:any) => {
      this.loading3 = false;
      if (data.status == 200) {
        let user = JSON.parse(localStorage.getItem("user"));
        user.user = data.data;
        this.userInfo.user = data.data;
        localStorage.setItem("user", JSON.stringify(user));
        this.hideWorkModal();
        this.msg.success('操作成功！');
      }
    });
  }

  // 上下班
  types = "";
  async GoWork() {
    let workingNum = 0;
    if (this.userInfo.user.online) {
      this.maskFlag = this.msg.loading("正在加载中..", {
        nzDuration: 0,
      }).messageId;
      let workingNumResult = await this.getWorkingNum();
      this.msg.remove(this.maskFlag);
      this.maskFlag = false;
      if (workingNumResult.status == 200) {
        workingNum = workingNumResult.data.data.length;
      }
      if (workingNum) {
        this.types = "您还<b style='color:red'>有未完成的工单</b>，确定下班后，<b style='color:red'>未完成工单将不计算积分。</b>";
      } else {
        this.types = "确定是否下班 ?";
      }
    } else {
      this.types = "确定是否上班 ?";
    }
    this.showWorkModal();
  }

  // 根据url高亮菜单baba
  highlightMenuByUrl() {
    console.log(this.router.url);
    let navOne, navTwo;
    let link = this.router.url.split("/").slice(-1)[0];
    let menus = JSON.parse(localStorage.getItem("menu"));
    if (link == "home") {
      this.toMenu("首页");
    } else {
      menus.forEach((oneNav) => {
        if (oneNav.childrens) {
          let findTwoNav = oneNav.childrens.find(
            (twoNav) => twoNav.link == link
          );
          if (findTwoNav) {
            navTwo = findTwoNav;
            navOne = oneNav;
            this.toMenu(navTwo.title, navTwo, navOne);
          }
        }
      });
    }
  }

  // 一级导航点击
  clickMenuOne(data) {
    let menus = JSON.parse(localStorage.getItem("menu"));
    data.flag = !data.flag;
    menus.find((item) => item.id == data.id).flag = data.flag;
    localStorage.setItem("menu", JSON.stringify(menus));
  }
  initMenu() {
    let menus = JSON.parse(localStorage.getItem("menu"));
    let arr = [];
    menus.forEach((e) => {
      if (e.link == "nurse") {
        this.nurseRole = true;
        console.log("护士端权限");
      }
      if (e.link == "dispatchingDesk") {
        this.deskRole = true;
        console.log("调度台权限");
      }
      if (e.link == "pharmacy") {
        this.pharmacyRole = true;
        console.log("药房端权限");
      }
      if (e.link == "largeScreen") {
        this.largeScreenRole = true;
        console.log("大屏端权限");
      }
      if (e.link == "largeScreen2") {
        this.largeScreenRole2 = true;
        console.log("大屏端2权限");
      }
      if (e.link == "specimenView") {
        this.specimenViewRole = true;
        console.log("业务视图权限");
      }
      if (e.link == "specimenView2") {
        this.specimenViewRole2 = true;
        console.log("标本视图权限");
      }
			if (e.link == "specimenRoomView") {
			  this.specimenRoomView = true;
			  console.log("标本间权限");
			}
			if (e.link == "pathology") {
			  this.pathology = true;
			  console.log("病理科权限");
			}
			if (e.link == "pathologySample") {
			  this.sampling = true;
			  console.log("门诊病理采样端权限");
			}
			if (e.link == "pathologyCommunicationBook") {
			  this.communicationBook = true;
			  console.log("病理交接本权限");
			}
      if (e.link == "disinfectionSupply") {
        this.disinfectionSupplyRole = true;
        console.log("全局业务查看权限");
      }
      if (e.link == "realtimeBroadcast") {
        this.realtimeBroadcastRole = true;
        console.log("故障实时播报权限");
      }
      if (e.link == "incidentConfig") {
        this.incidentConfigRole = true;
        console.log("事件配置权限");
      }
      if (e.link == "otherConfig") {
        this.otherConfigRole = true;
        console.log("三方配置权限");
      }
      if (e.link == "pageConfig") {
        this.pageConfigRole = true;
        console.log("业务页面控制权限");
      }
      if (e.link == "nurseConfig") {
        this.nurseConfigRole = true;
        console.log("护士端配置控制权限");
      }
      if (e.link == "PCCommutesToWork") {
        this.PCCommutesToWork = true;
        console.log("PC上下班");
      }
      if (e.type == "newStatistics") {
        this.newStatisticsRole = true;
        console.log("新版统计");
      }
      if (!e.link) {
        arr.push(e);
      }
    });
    this.menus = arr.filter(v => v.type === 'default');
  }

  // 判断登录是否已失效
  initLogin() {
    if (!this.userInfo) {
      this.msg.error("您的登录已失效，请重新登录！", {
        nzDuration: 3000,
      });
      setTimeout(() => {
        this.router.navigateByUrl("login");
      }, 2000);
      return;
    }
  }

  // 新密码失去焦点
  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);
  }

  // 跳转页面
  menuLabel: string; //当前菜单名称
  indexFlag = localStorage.getItem("index") === "true" ? true : false; //首页高亮
  toMenu(title, item?, data?) {
    sessionStorage.setItem("title", title);
    this.menuLabel = sessionStorage.getItem("title");
    if (item && data) {
      // 首页取消高亮
      this.indexFlag = false;
      localStorage.setItem("index", "false");
      // 操作本地存储
      let menus = JSON.parse(localStorage.getItem("menu"));
      menus.forEach((item1) => {
        item1.flagBg = false;
        if (item1.childrens) {
          item1.childrens.forEach((value) => {
            value.flag = false;
          });
        }
      });
      let obj = menus.find((value) => value.id == data.id);
      obj.flagBg = true;
      obj.flag = true;
      obj.childrens.find((value) => value.id == item.id).flag = true;
      localStorage.setItem("menu", JSON.stringify(menus));
      // 操作菜单一级 二级
      this.menus = menus.filter((item) => !item.link);
    } else {
      // 首页高亮
      this.indexFlag = true;
      localStorage.setItem("index", "true");
      // 操作本地存储
      let menus = JSON.parse(localStorage.getItem("menu"));
      menus.forEach((item1) => {
        item1.flagBg = false;
        // item1.flag = false;
        if (item1.childrens) {
          item1.childrens.forEach((value) => {
            value.flag = false;
          });
        }
      });
      localStorage.setItem("menu", JSON.stringify(menus));
      // 操作菜单一级 二级
      this.menus = menus.filter((item) => !item.link);
    }
  }

  // 子路由跳转事件
  activeRoute() {
    this.menuLabel = sessionStorage.getItem("title");
  }

  // 调度台
  toFuwutai(): void {
    this.router.navigateByUrl("dispatchingDesk");
  }

  // 护士建单
  toHuShi(): void {
    this.router.navigateByUrl("nurse");
  }
  // 药房端
  toPharmacy(): void {
    this.router.navigateByUrl("pharmacy");
  }
  // 药房端2
  toPharmacy2(): void {
    this.router.navigateByUrl("pharmacy2");
  }
  // 标本视图
  toSpecimenView2(): void {
    this.router.navigateByUrl("specimenView2");
  }
	// 标本间
	toSpecimenRoomView(): void {
	  this.router.navigateByUrl("specimenRoomView");
	}
	// 病理科
	toPathology(): void {
	  this.router.navigateByUrl("pathology");
	}
	// 门诊病理采样端
	toSampling(): void {
	  this.router.navigateByUrl("pathologySample");
	}
	// 病理交接本
	toCommunicationBook(): void {
	  this.router.navigateByUrl("pathologyCommunicationBook");
	}
  // 全局业务查看
  toDisinfectionSupply(): void {
    this.router.navigateByUrl("disinfectionSupply");
  }
  // 故障实时播报
  toRealtimeBroadcast(): void {
    this.router.navigateByUrl("realtimeBroadcast");
  }
  // 配置中心
  toConfigurationCenter(): void {
    this.iShowMenuModal = true;
    // this.router.navigateByUrl("configurationCenter");
  }
  // 统计
  toNewStatistics(): void {
    let menus = JSON.parse(localStorage.getItem("menu"));
    let firstMenu = menus.find((item) => item.type == "newStatistics");
    this.router.navigateByUrl(`newStatistics/${firstMenu.link}/${firstMenu.childrens[0].link}`);
  }
  // 大屏端或视图端
  screenType;
  hosFlag = false;
  toBigScreen(type): void {
    this.screenType = type;
    this.submitFormHand(this.currentHospital.id);
  }
  submitFormHand(id) {
    if (this.screenType === "largeScreen") {
      window.open(http.bigScreenHost + "/#/" + id);
    } else if (this.screenType === "largeScreen2") {
      window.open(http.bigScreenHost2 + "/#/" + id);
    } else if (this.screenType === "specimenView") {
      window.open(http.specimenViewHost + "/#/" + id);
    }
  }
  //获取系统设置中的科室类型
  getTypeByDept(id) {
    let postData = {
      idx: 0,
      sum: 1,
      systemConfiguration: { keyconfig: "busiViewDeptId" },
    };
    this.maskFlag = this.msg.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .getFetchDataList("simple/data", "systemConfiguration", postData)
      .subscribe((result) => {
        this.msg.remove(this.maskFlag);
        this.maskFlag = false;
        if (result.status == 200) {
          let remember = JSON.parse(localStorage.getItem("remember"));
          window.open(
            http.specimenViewHost +
              "/#/" +
              id +
              "/" +
              encodeURIComponent(remember.username) +
              "/" +
              encodeURIComponent(remember.password) +
              "/" +
              result.list[0].valueconfig
          );
        }
      });
  }
  hosFlagHand(flag) {
    if (!flag) {
      this.hosFlag = false;
    }
  }


  // 选择菜单-知道了
  iShowMenuModal:boolean = false;
  cancelMenuModal(flag) {
    this.iShowMenuModal = false;
  }

  // 下拉
  showDropdown:boolean = false;
  showDropdown1:boolean = false;

  // 选择院区
  selectHospital(){
    this.hosFlag1 = true
  }

  // 退出
  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");

    // 假退出
    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");
      }
    });

  }

  // 连接websocket
  getWebsocket() {
    this.webs
      .connectWs(http.mainWs, { userCount: this.userInfo.user.account })
      .subscribe((data) => {
        console.log(data);
        if (data && data.content) {
          this.createBasicNotification(data);
        }
      });
  }
  @ViewChild("msgTemplate1", { static: false }) msgTemplate1: TemplateRef<any>; //消息通知模板
  // 消息提醒
  createBasicNotification(msgs): void {
    this.notification.template(this.msgTemplate1, {
      nzDuration: 0,
      nzData: msgs,
    });
  }

  //打开修改密码弹窗
  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;

  isPwdVisible = false;
  pwdIsOkLoading = false;
  upModalData = {
    userid: "",
    pwdOld: "",
    newPwd: "",
    newPwd2: "",
  };
  upPwd(): void {
    if(this.upModalData.pwdOld.trim() === ''){
      this.msg.error('请填写原始密码！', {
        nzDuration: 5000,
      });
      return;
    }
    if(!this.strongRegFlag){
      this.msg.error('新密码不符合要求！', {
        nzDuration: 5000,
      });
      return;
    }
    if(this.upModalData.newPwd !== this.upModalData.newPwd2){
      this.msg.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.msg.success("修改成功！", {
          nzDuration: 5000,
        });
      } else {
        this.pwdIsOkLoading = false;
        this.msg.error(data.error, {
          nzDuration: 5000,
        });
      }
    });
  }
  showUpPwd(): void {
    this.isPwdVisible = true;
  }

  pwdHandleOk(): void {
    this.upPwd();
  }

  pwdHandleCancel(): void {
    this.isPwdVisible = false;
  }

  delModal = false;
  tipsMsg1 = "是否确定离开该界面，如果未点击生效，数据可能会遗失？";
  navInfo = {};
  // 隐藏模态框
  hideDelModal() {
    this.delModal = false;
  }
  // 模态框确认
  confirmDel() {
    this.delModal = false;
    if (this.navInfo["title"] == "首页") {
      this.router.navigateByUrl("/main/home");
      this.toMenu("首页");
    } else {
      this.router.navigateByUrl("/main/" + this.navInfo["item"].link);
      this.toMenu(
        this.navInfo["title"],
        this.navInfo["item"],
        this.navInfo["data"]
      );
    }
  }
  //前往菜单连接（拦截版）
  totoMenu(title, item?, data?) {
    let url = location.href.split("#")[1];
    if (url.includes("/main/quickCombination")) {
      //拦截
      this.delModal = true;
      this.navInfo = {
        title,
        item,
        data,
      };
    } else {
      //正常情况
      if (title == "首页") {
        this.router.navigateByUrl("/main/home");
        this.toMenu("首页");
      } else {
        this.router.navigateByUrl("/main/" + item.link);
        this.toMenu(title, item, data);
      }
    }
  }
  // 切换院区
  maskFlag: any = false;
  hosFlag1 = false;
  submitFormHand1(id) {
    if(this.currentHospital.id == id){
      return;
    }
    this.maskFlag = this.msg.loading("正在加载中..", {
      nzDuration: 0,
    }).messageId;
    this.mainService
      .changeHospital({ currentHosId: +id, loginType: "PC" })
      .subscribe((result) => {
        this.msg.remove(this.maskFlag);
        this.maskFlag = false;
        if (result.status == 200) {
          localStorage.setItem("user", JSON.stringify(result.user));
          location.reload(true);
        } else {
          this.msg.create("error", "切换院区失败");
        }
      });
  }
  hosFlagHand1(flag) {
    if (!flag) {
      this.hosFlag1 = false;
    }
  }
}
