import type { RouteLocationNormalized, RouteRecordNormalized } from 'vue-router';
import type { App, Plugin } from 'vue';

import { unref } from 'vue';
import { isObject } from '/@/utils/is';
import { cloneDeep, intersectionWith } from 'lodash-es';

import dayjs from 'dayjs';

export const noop = () => {};

/**
 * @description:  Set ui mount node
 */
export function getPopupContainer(node?: HTMLElement): HTMLElement {
  return (node?.parentNode as HTMLElement) ?? document.body;
}

/**
 * Add the object as a parameter to the URL
 * @param baseUrl url
 * @param obj
 * @returns {string}
 * eg:
 *  let obj = {a: '3', b: '4'}
 *  setObjToUrlParams('www.baidu.com', obj)
 *  ==>www.baidu.com?a=3&b=4
 */
export function setObjToUrlParams(baseUrl: string, obj: any): string {
  let parameters = '';
  for (const key in obj) {
    parameters += key + '=' + encodeURIComponent(obj[key]) + '&';
  }
  parameters = parameters.replace(/&$/, '');
  return /\?$/.test(baseUrl) ? baseUrl + parameters : baseUrl.replace(/\/?$/, '?') + parameters;
}

// 深度合并
export function deepMerge<T = any>(src: any = {}, target: any = {}): T {
  let key: string;
  const res: any = cloneDeep(src);
  for (key in target) {
    res[key] = isObject(res[key]) ? deepMerge(res[key], target[key]) : (res[key] = target[key]);
  }
  return res;
}

export function openWindow(
  url: string,
  opt?: { target?: TargetContext | string; noopener?: boolean; noreferrer?: boolean },
) {
  const { target = '__blank', noopener = true, noreferrer = true } = opt || {};
  const feature: string[] = [];

  noopener && feature.push('noopener=yes');
  noreferrer && feature.push('noreferrer=yes');

  window.open(url, target, feature.join(','));
}

// dynamic use hook props
export function getDynamicProps<T, U>(props: T): Partial<U> {
  const ret: Recordable = {};

  Object.keys(props).map(key => {
    ret[key] = unref((props as Recordable)[key]);
  });

  return ret as Partial<U>;
}

export function getRawRoute(route: RouteLocationNormalized): RouteLocationNormalized {
  if (!route) return route;
  const { matched, ...opt } = route;
  return {
    ...opt,
    matched: (matched
      ? matched.map((item: any) => ({
          meta: item.meta,
          name: item.name,
          path: item.path,
        }))
      : undefined) as RouteRecordNormalized[],
  };
}

export const withInstall = <T>(component: T, alias?: string) => {
  const comp = component as any;
  comp.install = (app: App) => {
    // console.log('🚀 ~ file: index.ts ~ line 88 ~ withInstall ~ app', app);
    app.component(comp.name || comp.displayName, component);
    if (alias) {
      app.config.globalProperties[alias] = component;
    }
  };
  return component as T & Plugin;
};

export function deleteEmptyChildren(treeData: Array<any>) {
  treeData.forEach(item => {
    if (item.children && item.children.length > 0) {
      item = deleteEmptyChildren(item.children);
    } else {
      delete item.children;
    }
    return item;
  });
  return treeData;
}

export function getAllParentKeys(treeData: Array<any>, key: string) {
  const getParentIds = function (list, id) {
    for (const i in list) {
      if (list[i].id == id) {
        return [];
      }
      if (list[i].children) {
        const ro = getParentIds(list[i].children, id);
        if (ro !== undefined) return ro.concat(list[i].id);
      }
    }
  };
  return getParentIds(treeData, key) || [];
}

// 获取字典值
export function formatDictValue(options: Array<any>, value: string) {
  if (!value) {
    if (value != '0') {
      return '';
    }
  }
  if (!options) {
    return '';
  }
  let matchItem = '';
  if (typeof value == 'boolean') {
    matchItem = value ? '是' : '否';
    return matchItem;
  }
  matchItem = options.find(item => (item['value'] as string) == value);
  return matchItem && matchItem['label'] ? matchItem['label'] : '';
}

// 获取字典值
export function formatDictLabel(options: Array<any>, label: string) {
  if (!label) {
    if (label != '0') {
      return '';
    }
  }
  if (!options) {
    return '';
  }
  let matchItem = '';
  matchItem = options.find(item => (item['label'] as string) == label);
  return matchItem && matchItem['value'] ? matchItem['value'] : '';
}

// 获取字典背景颜色
export function formatDictColor(options: Array<any>, value: string) {
  if (!value) {
    if (value != '0') {
      return '';
    }
  }
  if (!options) {
    return '';
  }
  let matchItem = '';
  matchItem = options.find(item => item['value'] == value);
  return matchItem && matchItem['bgColor'] ? matchItem['bgColor'] : '';
}

// 获取字典字体颜色
export function formatDictFontColor(options: Array<any>, value: string) {
  if (!value) {
    if (value != '0') {
      return '';
    }
  }
  if (!options) {
    return '';
  }
  let matchItem = '';
  matchItem = options.find(item => item['value'] == value);
  return matchItem && matchItem['fontColor'] ? matchItem['fontColor'] : '';
}

// 获取字段前缀颜色
export function formatDictPreColor(options: Array<any>, value: string) {
  if (!value) {
    if (value != '0') {
      return '';
    }
  }
  if (!options) {
    return '';
  }
  let matchItem = '';
  matchItem = options.find(item => item['value'] == value);
  return matchItem && matchItem['prefixColor'] ? matchItem['prefixColor'] : '';
}

// 获取字典数组
export function formatDictTags(options: Array<any>, value: Array<any>) {
  if (!value.length) {
    return [];
  }
  if (!options.length) {
    return [];
  }
  const matchItem =
    intersectionWith(options, value, (arrVal, othVal) => {
      return arrVal.value == othVal.value;
    }) || [];
  return matchItem;
}

// 转换字典
export function transformDict(data) {
  return data.map(ele => {
    return {
      label: ele.dictItemName,
      value: ele.dictItemCode,
    };
  });
}
// 常规状态转换
export function commonDict(data: number | boolean | string, str?: number | null) {
  const val = data == 1 || data == true || data == 'true';
  const map = [
    { str: 0, val: ['是', '否'] },
    { str: 1, val: ['停用', '正常'] },
    { str: 2, val: ['显示', '隐藏'] },
    { str: 3, val: ['可见', '不可见'] },
    { str: 4, val: ['成功', '失败'] },
  ];
  return map[str == null || str == undefined ? 0 : str].val[val ? 0 : 1];
}

// 设置api传参数
export function setParams(params: any) {
  const page = {
    current: 1,
    size: 10,
    orders: [{ field: 'createTime', direction: 'DESC' }],
  };
  if (params?.pageNum && params.pageNum !== undefined) {
    page.current = params.pageNum;
  }
  if (params?.pageSize && params.pageSize !== undefined) {
    page.size = params.pageSize;
  }
  if (params?.orders && params.orders !== undefined) {
    page.orders = params.orders;
  }
  delete params?.pageNum;
  delete params?.pageSize;
  delete params?.orders;
  params['page'] = page;
  console.log('🚀 ~ file: index.ts:194 ~ setParams ~ params', params);
  return params;
}

/**
 * @description: Date Range 预设范围 related enumeration
 */
export function dateRanges(format = 'YYYY-MM-DD') {
  console.log('🚀 ~ file: index.ts:210 ~ dateRanges ~ format:', format);
  return {
    今天: [dayjs(), dayjs()],
    本周: [dayjs().startOf('week'), dayjs().endOf('week')],
    上周: [
      dayjs().add(-1, 'week').startOf('week').add(1, 'day'),
      dayjs().add(-1, 'week').endOf('week').add(1, 'day'),
    ],
    本月: [dayjs().startOf('month'), dayjs().endOf('month')],
    上月: [dayjs().add(-1, 'month').startOf('month'), dayjs().add(-1, 'month').endOf('month')],
    // Today: [dayjs(), dayjs()],
    // 'This Month': [dayjs(), dayjs().endOf('month')],
  };
}
