import cloneDeep from 'lodash/cloneDeep';
import { parseSearchParams } from 'utils/utils';
import { FilterDataFuc } from './convert.types';
import { dispatchDebugScreenEvent, getDebugConfigFromSessionStorage } from './debug-screen';

export const mappingData = function (data: any = [], fields: any = []) {
  if (
    !(data instanceof Array) ||
    !(fields instanceof Array) ||
    fields.length === 0 ||
    data.length === 0
  ) {
    return data;
  }

  return data.map((item) => {
    if (item == null || Array.isArray(item) || typeof item !== 'object') {
      return item;
    }

    const obj = {};
    fields.map((d) => {
      if (d.value && item[d.value] !== undefined) {
        obj[d.name] = item[d.value];
      }
    });
    return {
      ...item,
      ...obj,
    };
  });
};

export const filterData: FilterDataFuc = (params) => {
  const { data, filters, callbackValues = {}, id, name } = params || {};
  const { filterExecute, debugListenStatus } = getDebugConfigFromSessionStorage();
  if (parseSearchParams()?.useFilter === 'false') {
    return data;
  }
  if (!filters || filters.length == 0) {
    return data;
  }

  if (data == null) {
    return [];
  }

  let result = typeof data === 'object' ? cloneDeep(data) : data;
  let curFilterInfo: any;

  try {
    filters.map((d) => {
      curFilterInfo = JSON.parse(JSON.stringify(d || {}));
      const callbackArgs = d.callbackKeys
        ? d.callbackKeys.reduce((all, item) => {
            let callbackValue = callbackValues[item];
            // 对回调值做深拷贝
            if (typeof callbackValue === 'object' && callbackValue !== null) {
              callbackValue = cloneDeep(callbackValue);
            }

            all[item] = callbackValue;
            return all;
          }, {})
        : {};
      curFilterInfo.callbackValues = callbackArgs;

      result = eval(`(function filter(data, callbackArgs){
        // 过滤器名称：${d.name}， 过滤器id: ${d.id};
        ${d.content}
      })(result, callbackArgs)`);
      debugListenStatus === 'recording' &&
        filterExecute &&
        dispatchDebugScreenEvent<'info', 'filter'>({
          debugMsg: {
            callbackValues: callbackArgs,
            id: d?.id,
            name: d?.name,
            data,
          },
          type: 'info',
          dispatchFrom: 'filter',
          name,
          id,
        });
    });
    return result;
  } catch (error: any) {
    console.error('过滤器执行时发生错误：', error);
    dispatchDebugScreenEvent<'error', 'filter'>({
      name,
      id,
      type: 'error',
      dispatchFrom: 'filter',
      debugMsg: {
        data,
        callbackValues: curFilterInfo?.callbackValues,
        name: curFilterInfo?.name,
        id: curFilterInfo?.id,
        message: error.message,
      },
    });
    return {
      isError: true,
      msg: error.toString(),
      originData: data,
    };
  }
};

/**
 * @returns path上是否存在dataRequest=false
 */
export const isCancelRequestData = () => {
  return parseSearchParams()?.dataRequest === 'false';
};
