import type { DataSource } from "../types";
import { defaultsDeep } from "lodash-es";
import { containerDefaultConfig, chartDefaultConfig } from "../config";
import { EChartsOption } from "echarts";
import { PropType } from "vue";
import { DataSourceType } from "../chartEnum";

/**
 * 获取容器组件属性
 *  @param {Record<string, any>} config - 传入属性
 *  @returns {Record<string, any>} - 返回与默认配置合并后的属性
 */
export function getNormalizedContainer(config: Record<string, any>) {
  return defaultsDeep(config, containerDefaultConfig);
}

/**
 * 获取图表组件属性
 *  @param {Record<string, any>} config - 传入属性
 *  @returns {Record<string, any>} - 返回与默认配置合并后的属性
 */
export function getNormalizedChart(config: EChartsOption) {
  return defaultsDeep(config, chartDefaultConfig);
}

// 图表组件数据来源prop
export const dataSource = {
  type: Object as PropType<DataSource>,
  default: () => ({
    sourceType: DataSourceType.STATIC,
    data: [],
    url: "",
    method: "GET",
    params: {},
    headers: {},
    refreshTime: 0,
    dataProcess: () => [],
  }),
}


/**
 * 执行动态js
 * @param code 代码
 * @param param 参数
 * @returns promise
 */
export const cllJsCode = (code: string, param: string): Promise<any> => {
  
  return new Promise((resove, reject) => {
    // 生成一份new webwork
    const blob = new Blob([`
      self.onmessage = function(e) {
        self.postMessage((${code}).call(null, e.data));
      }
    `], { type: 'application/javascript' });

    const worker = new Worker(URL.createObjectURL(blob));
    // 向webwork发送消息
    worker.postMessage(JSON.parse(param));
    worker.onmessage = (e) => {
      worker.terminate();
      resove(e.data);
    }
    worker.onerror = (e) => {
      worker.terminate();
      reject(e);
    }
  });
}