import { Injectable } from "@angular/core";
import { MainService } from "./main.service";
import { Subject } from "rxjs";

@Injectable({
  providedIn: "root",
})
export class ToolService {
  logoUrl = '';
  logoTitle = '';
  faviconUrl = '';
	changeInpSubject:any;
	allSubject = new Subject();
	allEndSubject = new Subject();
	 
	// 提供方法来触发事件
	triggerEvent(data: any) {
		this.allSubject.next(data);
	}
	
	// 提供方法来触发事件
	triggerEndEvent(data: any) {
		this.allEndSubject.next(data);
	}
	
	// 提供方法来订阅事件
	getEventObservable() {
		return this.allSubject.asObservable();
	}
	
	// 提供方法来订阅事件
	getEventEndObservable() {
		return this.allEndSubject.asObservable();
	}
	
  // 附件类型
  // word，excel，pdf，txt，ppt
  attachmentsTypes:string = 'text/plain,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/pdf,application/vnd.ms-excel,application/msword,application/vnd.openxmlformats-officedocument.presentationml.presentation';

  constructor(private mainService: MainService) {}
	
	
  // 获取logoUrl和logoTitle
  getSysNameAndLogoAsync(hosId = ''){
    return this.mainService.getSysNameAndLogo(hosId);
  }

  // 设置logoTitle
  setSysName(logoTitle){
    this.logoTitle = logoTitle;
  }

  // 设置logoUrl
  setLogo(logoUrl){
    this.logoUrl = logoUrl;
  }

  // 设置faviconUrl
  setFavicon(faviconUrl){
    this.faviconUrl = faviconUrl;
  }

  // 获取权限中的院区
  getHospitalList() {
    return (
      JSON.parse(localStorage.getItem("user")).infoPermission.hospitals || []
    );
  }
	// 获取权限中的信息
	getUserInfoPermission() {
	  return JSON.parse(localStorage.getItem("user")).infoPermission || {};
	}
  // 获取权限中的分组
  getGroupList() {
    return JSON.parse(localStorage.getItem("user")).infoPermission.groups || [];
  }
  // 获取当前院区
  getCurrentHospital() {
    return JSON.parse(localStorage.getItem("user")).user.currentHospital
      ? JSON.parse(localStorage.getItem("user")).user.currentHospital
      : JSON.parse(localStorage.getItem("user")).infoPermission.hospitals[0];
  }
	//获取当前用户信息
	getCurrentUserInfo() {
	  return JSON.parse(localStorage.getItem("user")).user;
	}
  //获取当前用户科室
  getCurrentUserDept() {
    return JSON.parse(localStorage.getItem("user")).user.dept;
  }
  //获取当前用户id
  getCurrentUserId() {
    return JSON.parse(localStorage.getItem("user")).user.id;
  }
  //返回当前人的院区是院区或责任部门
  getHospitalOrDuty() {
    let hospital = this.getCurrentHospital();
    let type = 'hospital';//默认是院区
    if(hospital.type && hospital.type.value == 6){
      // 当前是责任部门
      type = 'duty';
    }

    if(hospital.type && hospital.type.value != 6){
      // 当前是普通部门
      type = 'department';
    }

    return {
      hospital,
      type,
    }
  }

  //判断是否是责任部门
  isDuty(hospital) {
    return hospital.type && hospital.type.value == 6;
  }

  // 返回当前用户的组
  getCurrentGroupList(){
    return JSON.parse(localStorage.getItem("user")).user.group || [];
  }
  // 根据route查询菜单-新版统计专用
  getMenuAutoType() {
    let menu: any = JSON.parse(localStorage.getItem("menu")) || []; //菜单
    return menu.filter( v => v.type == 'newStatistics');
  }
  //获取当前菜单的权限
  initCoopBtns(route) {
    let link = route.parent.snapshot.routeConfig.path; //当前路由;
    let menu: any = JSON.parse(localStorage.getItem("menu")) || []; //菜单

    let secondMenus = []; // 二级菜单
    let jurisdiction = []; //当前菜单的权限列表
		let menuItem = null;
    let coopBtns: any = {}; // 初始化权限
    menu.forEach((e) => {
      if (e.childrens) {
        e.childrens.forEach((el) => {
          secondMenus.push(el);
        });
      }
    });
    secondMenus.forEach((e) => {
      if (e.link == link) {
        jurisdiction = e.childrens || []; //匹配路由后，取得对应的权限
      }
    });
    if(!jurisdiction.length){
      menu.forEach(v => {
        // type为panel路由
        if(v.type === 'panel' && v.link == link && v.childrens){
          jurisdiction = v.childrens || []; //匹配路由后，取得对应的权限
        }
      })
    }
		menuItem = jurisdiction
		localStorage.setItem("menuItem", JSON.stringify(menuItem))
    jurisdiction.forEach((e) => {
      switch (e.link) {
        case "look":
          coopBtns.look = true; //查看
          break;
        case "add":
          coopBtns.add = true; //新增
          break;
        case "edit":
          coopBtns.edit = true; //编辑
          break;
        case "del":
          coopBtns.del = true; //删除
          break;
        case "reply":
          coopBtns.reply = true; //回复
          break;
        case "mediate":
          coopBtns.mediate = true; //调解
          break;
        case "designate":
          coopBtns.designate = true; //指派
          break;
        case "export":
          coopBtns.export = true; //导出
          break;
        case "import":
          coopBtns.import = true; //导入
          break;
        case "templateDownload":
          coopBtns.templateDownload = true; //模板下载
          break;
        case "isStartUp":
          coopBtns.isStartUp = true; //是否启用
          break;
        case "isTimedStartUp":
          coopBtns.isTimedStartUp = true; //是否定时启用
          break;
        case "copy":
          coopBtns.copy = true; //复制
          break;
        case "generateQRcode":
          coopBtns.generateQRcode = true; //生成二维码
          break;
        case "deleted":
          coopBtns.deleted = true; //已删除
          break;
        case "executeNow":
          coopBtns.executeNow = true; //立即执行
          break;
        case "resetPwd":
          coopBtns.resetPwd = true; //重置密码
          break;
        case "print":
          coopBtns.print = true; //打印
          break;
        case "currentDept":
          coopBtns.currentDept = true; //当前科室工单
          break;
        case "currentUser":
          coopBtns.currentUser = true; //当前人员工单
          break;
        case "allOrders":
          coopBtns.allOrders = true; //全部工单
          break;
        case "batchConversion":
          coopBtns.batchConversion = true; //批量转换
          break;
        case "oneClickConversion":
          coopBtns.oneClickConversion = true; //一键转换
          break;
        case "oneClickRecovery":
          coopBtns.oneClickRecovery = true; //一键恢复
          break;
        case "view":
          coopBtns.view = true; //查看视图
          break;
        case "recount":
          coopBtns.recount = true; //重新统计
          break;
        case "editNum":
          coopBtns.editNum = true; //矫正重量
          break;
				case "establish":
				  coopBtns.establish = true; //配送建单
				  break;
				case "historyRecord":
				  coopBtns.historyRecord = true; //历史记录
				  break;
				case "batchPrint":
				  coopBtns.batchPrint = true; //发药并打印
				  break;
        case "config":
          coopBtns.config = true; //配置
          break;
        case "publish":
          coopBtns.publish = true; //发布
          break;
        case "reset":
          coopBtns.reset = true; //重置
          break;
				case "pause":
				  coopBtns.pause = true; //停用
				  break;
				case "renew":
				  coopBtns.renew = true; //恢复
				  break;
				case "audit":
				  coopBtns.audit = true; //审核
				  break;
				case "upgrade":
				  coopBtns.upgrade = true; //升级
				  break;
        case "commonFault":
          coopBtns.commonFault = true; //常见故障
          break;
				case "dispensingInfo":
				  coopBtns.dispensingInfo = true; //发药信息
				  break;
				case "dispensingGross":
				  coopBtns.dispensingGross = true; //发药总量
				  break;
        case "assign":
          coopBtns.assign = true; //指派
          break;
        case "handle":
          coopBtns.handle = true; //处理
          break;
        case "settings":
          coopBtns.settings = true; //设置
          break;
        case "all":
          coopBtns.all = true; //全部故障
          break;
        case "reassign":
          coopBtns.reassign = true; //重新指派
          break;
        case "callback":
          coopBtns.callback = true; //待我回访
          break;
        case "receive":
          coopBtns.receive = true; //接单
          break;
        case "transfer":
          coopBtns.transfer = true; //转派
          break;
        case "visit":
          coopBtns.visit = true; //回访
          break;
        case "continue":
            coopBtns.continue = true; //继续建单
            break;
        case "generate":
          coopBtns.generate = true; //生成
          break;
        case "reject":
          coopBtns.reject = true; //不受理
          break;
				case "strideLook":
				  coopBtns.strideLook = true; //跨科查看
				  break;
				case "crossHospital":
				  coopBtns.crossHospital = true; //跨部门选组
				  break;
				case "maintenance":
				  coopBtns.maintenance = true; //运维
				  break;
				case "distributionPj":
				  coopBtns.distributionPj = true; //配送陪检
				  break;
				case "extension":
				  coopBtns.extension = true; //分机绑定
				  break;
				case "callCenter":
				  coopBtns.callCenter = true; //呼叫中心
				  break;
				case "log":
				  coopBtns.log = true; //日志
					break
				case "viewGd":
				  coopBtns.viewGd = true; //查看工单
				  break;
        case "tagBackDepartment":
				  coopBtns.tagBackDepartment = true; //标记回科
				case "updata":
				  coopBtns.updata = true; //更新
				  break;
				case "download":
				  coopBtns.download = true; //下载
				  break;
        case "removeSign":
				  coopBtns.removeSign = true; //清空标记
				  break;
        case "lookLog":
				  coopBtns.lookLog = true; //查看日志
				case "allocation":
				  coopBtns.allocation = true; //分配任务
				  break;
				case "accomplish":
				  coopBtns.accomplish = true; //任务完成
				  break;
				case "startTask":
				  coopBtns.startTask = true; //开始任务
				  break;
				case "record":
				  coopBtns.record = true; //任务记录
				  break;
				case "send":
				  coopBtns.send = true; //发送消息
				  break;
				case "batchRecover":
				  coopBtns.batchRecover = true; //批量恢复
				  break;
				case "batchProcessing":
				  coopBtns.batchProcessing = true; //批量不处理
				  break;
				case "unlock":
				  coopBtns.unlock = true; //解锁
				  break;
				case "lock":
					coopBtns.lock = true; //锁定
					break;
				case "collect":
					coopBtns.collect = true; //设置核收
					break;
				
      }
    });
    console.log(coopBtns);
    return coopBtns;
  }
  // 获取护士端是否使用科室别名的系统配置
  getDeptDisplay() {
    let postData = {
      idx: 0,
      sum: 1,
      systemConfiguration: { keyconfig: "deptDisplay" },
    };
    return this.mainService.getFetchDataList(
      "simple/data",
      "systemConfiguration",
      postData
    );
  }

  /**
   * @description: 扁平化结构转成树形结构
   * @param {*} list 扁平化的数组
   * @param {*} rootValue 顶级parentKeyName的值
   * @param {*} parentKeyName 父级字段名称
   * @param {*} keyName 字段名称
   * @return {*} 返回树形结构
   * @author: seimin
   */
  tranListToTreeData(list:Array<any>, rootValue:any, parentKeyName:string, keyName:string = 'id'):Array<any> {
    return list.filter((t) =>
      t[parentKeyName] === rootValue
        ? (t.children = this.tranListToTreeData(list, t[keyName], parentKeyName, keyName))
        : false
    );
  }

  /**
   * @description: 树形结构转扁平化结构
   * @param {*} tree 树形结构
   * @return {*} 返回扁平化结构
   * @author: seimin
   */
  tranTreeToListData(tree: Array<any>): Array<any> {
    let res: Array<any> = [];
    for (const item of tree) {
      const { children, ...i } = item;
      if (children && children.length) {
        res = res.concat(this.tranTreeToListData(children));
      }
      res.push(i);
    }
    return res;
  }

  /**
   * @description: 扁平化结构转成树形结构-ng-zorro级联组件专用
   * @param {*} list 扁平化的数组
   * @param {*} rootValue 顶级parentKeyName的值
   * @param {*} parentKeyName 父级字段名称
   * @param {*} keyName 字段名称
   * @return {*} 返回树形结构
   * @author: seimin
   */
  tranListToTreeDataLeaf(list:Array<any>, rootValue:any, parentKeyName:string, keyName:string = 'id'):Array<any> {
    return list.filter((t) => {
      let children = this.tranListToTreeData(list, t[keyName], parentKeyName, keyName);
			if(!children.length){
        t.isLeaf = true;
      }
      return t[parentKeyName] === rootValue
      ? (t.children = children)
      : false
    });
  }

  /**
   * @description: 树形结构根据id回显-ng-zorro级联组件专用
   * @param {*} tree 树形结构
   * @param {*} id 要查询的id
   * @return {*} 返回数组-用于回显
   * @author: seimin
   */
  tranListToTreeDataFindIdsLeaf(tree: Array<any>, id: number, arr = []):Array<number> {
    let list = this.tranTreeToListData(tree);
    console.log(list)
    let obj = list.find(v => v.id === id);
    arr.unshift(id);
    if(obj.parentId){
      this.tranListToTreeDataFindIdsLeaf(tree, obj.parentId, arr);
    }
    return arr;
  }

  /**
   * @description 生成连续的数字
   * @param {number} start 起点数字
   * @param {number} end 终点数字
   * @return {array}
   */
  generateNumberArray(start, end){
    return Array.from(new Array(end + 1).keys()).slice(start);
  }
}
