import Color from 'color';
import { useRoute } from 'vue-router';
import { cloneDeep } from 'lodash-es';
import { PublicConfigClass } from './PublicConfigClass';

export class PublicGroupConfigClass extends PublicConfigClass {
  // 成组
  isGroup = true;
  // 名称
  chartConfig = {
    key: 'group',
    chartKey: 'group',
    conKey: 'group',
    category: 'group',
    categoryName: 'group',
    package: 'group',
    chartFrame: 'common',
    title: '分组',
    image: ''
  };
  // 组成员列表
  groupList = [];
  // ---- 原有 ---
  // key
  key = 'group';
  // 配置
  option = {};
  // 标识
  id = getUUID();
  // 基本信息
  attr = { w: 0, h: 0, x: 0, y: 0, offsetX: 0, offsetY: 0, zIndex: -1 };
}

/**
 * * 生成一个不重复的ID
 * @param { Number } randomLength
 */
export const getUUID = (randomLength = 10) => {
  return String(Math.random().toString().substring(2, randomLength) + Date.now()).toString(36);
};

/**
 * * hsla 转换
 * @param color 颜色
 * @param alpha 默认1
 * @returns
 */
export function alpha(color, alpha = 1) {
  return Color(color).alpha(alpha).toString();
}

// * 开启加载
export const loadingStart = () => {
  // window['$loading'].start();
};

// * 加载结束
export const loadingFinish = () => {
  setTimeout(() => {
    // window['$loading'].finish();
  });
};

// * 加载错误
export const loadingError = () => {
  setTimeout(() => {
    // window['$loading'].error();
  });
};

export function isString(p) {
  return typeof p === 'string';
}

export function isArray(p) {
  return Array.isArray(p);
}

/**
 * * 判断是否是预览页
 * @returns boolean
 */
export const isPreview = () => {
  const route = useRoute();
  return route.path == '/report/preview';
};

/**
 * * 处理请求事件单位
 * @param num 时间间隔
 * @param unit RequestHttpIntervalEnum
 * @return number 秒数
 */
export const intervalUnitHandle = (num, unit) => {
  switch (unit) {
    // 秒
    case 'second':
      return num * 1000;
    // 分
    case 'minute':
      return num * 1000 * 60;
    // 时
    case 'hour':
      return num * 1000 * 60 * 60;
    // 天
    case 'day':
      return num * 1000 * 60 * 60 * 24;
    default:
      return num * 1000;
  }
};

/**
 * * 函数过滤器
 * @param data 数据值
 * @param res 返回顶级对象
 * @param funcStr 函数字符串
 * @param isToString 是否转为字符串
 * @param errorCallBack 错误回调函数
 * @param successCallBack 成功回调函数
 * @returns
 */
export const newFunctionHandle = (data, res, funcStr, isToString, errorCallBack, successCallBack) => {
  try {
    if (!funcStr) return data;
    const fn = new Function('data', 'res', funcStr);
    const fnRes = fn(cloneDeep(data), cloneDeep(res));
    const resHandle = isToString ? toString(fnRes) : fnRes;
    // 成功回调
    successCallBack && successCallBack(resHandle);
    return resHandle;
  } catch (error) {
    // 失败回调
    errorCallBack && errorCallBack(error);
    return '函数执行错误';
  }
};

/**
 * * 动态注册组件
 */
export const componentInstall = (key, node) => {
  if (!window['$vue'].component(key) && node) {
    window['$vue'].component(key, node);
  }
};


// 组件缓存, 可以大幅度提升组件加载速度
const componentCacheMap = new Map()

const loadConfig = (packageName, categoryName, keyName) => {
  const key = packageName + categoryName + keyName
  if (!componentCacheMap.has(key)) {
    componentCacheMap.set(key, import(`../components/echart/${packageName}/${categoryName}/${keyName}/config.js`))
  }
  return componentCacheMap.get(key)
}

/**
 * * 获取目标组件配置信息
 * @param targetData
 */
export const createComponent = async targetData => {
  const { redirectComponent, category, key } = targetData;
  // redirectComponent 是给图片组件库和图标组件库使用的
  if (redirectComponent) {
    const [packageName, categoryName, keyName] = redirectComponent.split('/')
    const redirectChart = await loadConfig(packageName, categoryName, keyName)
    return new redirectChart.default()
  }
  const chart = await loadConfig(targetData.package, category, key);
  return new chart.default();
};

/**
 * * 获取展示组件
 * @param {ConfigType} dropData 配置项
 */
export const fetchChartComponent = dropData => {
  const { key } = dropData;
  return fetchComponent(key, '0')?.default;
};

const indexModules = import.meta.globEager('../components/echart/**/index.vue');

/**
 * * 获取配置组件
 * @param {ConfigType} dropData 配置项
 */
export const fetchConfigComponent = dropData => {
  const { key } = dropData;
  return fetchComponent(key, '1')?.default;
};

/**
 * * 获取组件
 * @param chartName 名称
 * @param  flag 标识 0为展示组件, 1为配置组件
 */
export const fetchComponent = chartName => {
  const module = indexModules;
  for (const key in module) {
    const urlSplit = key.split('/');
    if (urlSplit[urlSplit.length - 2] === chartName) {
      return module[key];
    }
  }
};

/**
 * 修改元素位置
 * @param target 对象
 * @param x X轴
 * @param y Y轴
 */
export const setComponentPosition = (target, x, y) => {
  x && (target.attr.x = x);
  y && (target.attr.y = y);
};

// * 动画
export const animationsClass = animations => {
  if (animations.length) {
    return `animate__animated  animate__${animations[0]}`;
  }
  return '';
};

// * 滤镜
export const getFilterStyle = styles => {
  if (!styles || !styles.filterShow) return {};
  const { opacity, saturate, contrast, hueRotate, brightness } = styles;
  return {
    opacity: opacity,
    filter: `saturate(${saturate}) contrast(${contrast}) hue-rotate(${hueRotate}deg) brightness(${brightness})`
  };
};

// * 变换
export const getTransformStyle = styles => {
  const { rotateZ, rotateX, rotateY, skewX, skewY } = styles;
  return {
    transform: `rotateZ(${rotateZ || 0}deg) rotateX(${rotateX || 0}deg) rotateY(${rotateY || 0}deg) skewX(${
      skewX || 0
    }deg) skewY(${skewY || 0}deg)`
  };
};

// * 混合模式
export const getBlendModeStyle = styles => {
  if (!styles || !styles.filterShow) return {};
  const { blendMode } = styles;
  return {
    'mix-blend-mode': blendMode
  };
};

/**
 * * 设置按下键盘按键的底部展示
 * @param keyCode
 * @returns
 */
export const setKeyboardDressShow = keyCode => {
  const code = new Map([
    [17, 'ctrl'],
    [32, 'Space']
  ]);

  const dom = document.getElementById('keyboard-dress-show');
  if (!dom) return;
  if (!keyCode) {
    window.onKeySpacePressHold?.(false);
    dom.innerText = '';
    return;
  }
  if (keyCode && code.has(keyCode)) {
    if (keyCode == 32) window.onKeySpacePressHold?.(true);
    dom.innerText = `按下了「${code.get(keyCode)}」键`;
  }
};

/**
 * * 合并基础颜色和自定义颜色
 * @param chartDefaultColors
 * @param customColor
 * @returns
 */
export const colorCustomMerge = customColor => {
  const formateCustomColor = {};
  customColor?.forEach(item => {
    formateCustomColor[item.id] = {
      color: item.color,
      name: item.name
    };
  });
  return { ...formateCustomColor };
};

const imagesModules = import.meta.glob('../../../assets/images/chart/**', {
  eager: true
});

/**
 * * 获取图片内容
 * @param {ConfigType} targetData 配置项
 */
export const fetchImages = async targetData => {
  if (!targetData) return '';
  // 正则判断图片是否为 url，是则直接返回该 url
  if (/^(http|https):\/\/([\w.]+\/?)\S*/.test(targetData.image)) return targetData.image;
  // 新数据动态处理
  const { image } = targetData;
  // 兼容旧数据
  if (image.includes('@') || image.includes('base64')) return image;

  const imageName = image.substring(image.lastIndexOf('/') + 1);
  for (const key in imagesModules) {
    const urlSplit = key.split('/');
    if (urlSplit[urlSplit.length - 1] === imageName) {
      return imagesModules[key]?.default;
    }
  }
  return '';
};

/**
 * 获取随机数
 * @param {*} number
 * @returns
 */
export function getRandomNumber(number) {
  var characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  var result = '';
  for (var i = 0; i < number; i++) {
    var randomIndex = Math.floor(Math.random() * characters.length);
    result += characters.charAt(randomIndex);
  }
  return result;
}
