import Clipboard from "clipboard";
import axios from "axios";
import request from "../../../utils/request.js";
import { decode } from "js-base64";

export function getAccessUrl() {
  return SUPPORT_PREFIX + "/report_ins/getData";
}

export function isNull(value) {
  return value === null || value === undefined;
}

export function isNilOrEmptyStr(value) {
  return value === null || value === undefined || value === "";
}

export function isNotNull(value) {
  return value !== null && value !== undefined;
}

export function isEmptyStr(str) {
  //return (str === undefined) || (!str) || (!/[^\s]/.test(str));
  return (
    str === undefined ||
    (!str && str !== 0 && str !== "0") ||
    !/[^\s]/.test(str)
  );
}

export const generateId = function () {
  return Math.floor(
    Math.random() * 100000 + Math.random() * 20000 + Math.random() * 5000
  );
};

export const createUUID = function () {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
    .replace(/[xy]/g, function (c) {
      var r = (Math.random() * 16) | 0,
        v = c === "x" ? r : (r & 0x3) | 0x8;
      return v.toString(16);
    })
    .replaceAll("-", "");
};

export const deepClone = function (origin) {
  if (origin === undefined) {
    return undefined;
  }

  return JSON.parse(JSON.stringify(origin));
};

export const overwriteObj = function (obj1, obj2) {
  /* 浅拷贝对象属性，obj2覆盖obj1 */
  // for (let prop in obj2) {
  //   if (obj2.hasOwnProperty(prop)) {
  //     obj1[prop] = obj2[prop]
  //   }
  // }

  Object.keys(obj2).forEach((prop) => {
    obj1[prop] = obj2[prop];
  });
};

export const addWindowResizeHandler = function (handler) {
  let oldHandler = window.onresize;
  if (typeof window.onresize != "function") {
    window.onresize = handler;
  } else {
    window.onresize = function () {
      oldHandler();
      handler();
    };
  }
};

const createStyleSheet = function () {
  let head = document.head || document.getElementsByTagName("head")[0];
  let style = document.createElement("style");
  style.type = "text/css";
  head.appendChild(style);
  return style.sheet;
};

export const insertCustomCssToHead = function (cssCode, formId = "") {
  let head = document.getElementsByTagName("head")[0];
  let oldStyle = document.getElementById("vform-custom-css");
  if (!!oldStyle) {
    head.removeChild(oldStyle); //先清除后插入！！
  }
  if (!!formId) {
    oldStyle = document.getElementById("vform-custom-css" + "-" + formId);
    !!oldStyle && head.removeChild(oldStyle); //先清除后插入！！
  }

  let newStyle = document.createElement("style");
  newStyle.type = "text/css";
  newStyle.rel = "stylesheet";
  newStyle.id = !!formId
    ? "vform-custom-css" + "-" + formId
    : "vform-custom-css";
  try {
    newStyle.appendChild(document.createTextNode(cssCode));
  } catch (ex) {
    newStyle.styleSheet.cssText = cssCode;
  }

  head.appendChild(newStyle);
};

export const insertGlobalFunctionsToHtml = function (
  functionsCode,
  formId = ""
) {
  let bodyEle = document.getElementsByTagName("body")[0];
  let oldScriptEle = document.getElementById("v_form_global_functions");
  !!oldScriptEle && bodyEle.removeChild(oldScriptEle); //先清除后插入！！
  if (!!formId) {
    oldScriptEle = document.getElementById(
      "v_form_global_functions" + "-" + formId
    );
    !!oldScriptEle && bodyEle.removeChild(oldScriptEle); //先清除后插入！！
  }

  let newScriptEle = document.createElement("script");
  newScriptEle.id = !!formId
    ? "v_form_global_functions" + "-" + formId
    : "v_form_global_functions";
  newScriptEle.type = "text/javascript";
  newScriptEle.innerHTML = functionsCode;
  bodyEle.appendChild(newScriptEle);
};

export const optionExists = function (optionsObj, optionName) {
  if (!optionsObj) {
    return false;
  }

  return Object.keys(optionsObj).indexOf(optionName) > -1;
};

export const loadRemoteScript = function (srcPath, callback) {
  /*加载远程js，加载成功后执行回调函数*/
  let sid = encodeURIComponent(srcPath);
  let oldScriptEle = document.getElementById(sid);

  if (!oldScriptEle) {
    let s = document.createElement("script");
    s.src = srcPath;
    s.id = sid;
    document.body.appendChild(s);

    s.onload = s.onreadystatechange = function (_, isAbort) {
      /* 借鉴自ace.js */
      if (
        isAbort ||
        !s.readyState ||
        s.readyState === "loaded" ||
        s.readyState === "complete"
      ) {
        s = s.onload = s.onreadystatechange = null;
        if (!isAbort) {
          callback();
        }
      }
    };
  }
};

export function traverseFieldWidgets(
  widgetList,
  handler,
  parent = null,
  staticWidgetsIncluded
) {
  if (!widgetList) {
    return;
  }

  loopHandleWidget(widgetList, (w, parent) => {
    if (w.formItemFlag || (w.formItemFlag === false && staticWidgetsIncluded)) {
      handler(w, parent);
    }
  });

  /* widgetList.forEach((w) => {
    if (w.formItemFlag || (w.formItemFlag === false && staticWidgetsIncluded)) {
      handler(w, parent);
    } else if (w.type === "grid") {
      w.cols.forEach((col) => {
        traverseFieldWidgets(col.widgetList, handler, w, staticWidgetsIncluded);
      });
    } else if (w.type === "table") {
      w.rows.forEach((row) => {
        row.cols.forEach((cell) => {
          traverseFieldWidgets(
            cell.widgetList,
            handler,
            w,
            staticWidgetsIncluded
          );
        });
      });
    } else if (w.type === "tab") {
      w.tabs.forEach((tab) => {
        traverseFieldWidgets(tab.widgetList, handler, w, staticWidgetsIncluded);
      });
    } else if (w.type === "sub-form" || w.type === "grid-sub-form") {
      traverseFieldWidgets(w.widgetList, handler, w, staticWidgetsIncluded);
    } else if (w.category === "container") {
      //自定义容器
      traverseFieldWidgets(w.widgetList, handler, w, staticWidgetsIncluded);
    }
  }); */
}

export function traverseContainerWidgets(
  widgetList,
  handler,
  skipDialogAndDrawer
) {
  if (!widgetList) {
    return;
  }

  loopHandleWidget(widgetList, (w, parent) => {
    if (w.category === "container") {
      if (
        skipDialogAndDrawer &&
        (w.type === "vf-dialog" || w.type === "vf-drawer")
      ) {
        //什么也不做
      } else {
        handler(w);
      }
    }
  });

  /* widgetList.forEach((w) => {
    if (w.category === "container") {
      if (
        skipDialogAndDrawer &&
        (w.type === "vf-dialog" || w.type === "vf-drawer")
      ) {
        //什么也不做
      } else {
        handler(w);
      }
    }

    if (w.type === "grid") {
      w.cols.forEach((col) => {
        traverseContainerWidgets(col.widgetList, handler);
      });
    } else if (w.type === "table") {
      w.rows.forEach((row) => {
        row.cols.forEach((cell) => {
          traverseContainerWidgets(cell.widgetList, handler);
        });
      });
    } else if (w.type === "tab") {
      w.tabs.forEach((tab) => {
        traverseContainerWidgets(tab.widgetList, handler);
      });
    } else if (w.type === "sub-form" || w.type === "grid-sub-form") {
      traverseContainerWidgets(w.widgetList, handler);
    } else if (w.category === "container") {
      //自定义容器
      if (
        skipDialogAndDrawer &&
        (w.type === "vf-dialog" || w.type === "vf-drawer")
      ) {
        //什么也不做
      } else {
        traverseContainerWidgets(w.widgetList, handler);
      }
    }
  }); */
}

export function traverseAllWidgetsNew(widgetList, callback) {
  if (!widgetList) {
    return;
  }
  let columnLoopDo = (t, parentWidget) => {
    if (t.children && t.children.length) {
      t.children.forEach((item) => {
        columnLoopDo(item, parentWidget);
      });
    } else {
      if (t.widget) {
        callback && callback(t.widget, parentWidget);
      }
      if (t.editWidget) {
        callback && callback(t.editWidget, parentWidget);
      }
      if (t.widgetList && t.widgetList.length) {
        loopHandleWidget(t.widgetList, (widget) => {
          callback && callback(widget, parentWidget);
        });
      }
    }
  };
  loopHandleWidget(widgetList, (widget, parentWidget) => {
    if (callback) {
      callback(widget, parentWidget);
      if (widget.type === "data-table") {
        for (let item of widget.options.tableColumns) {
          columnLoopDo(item, parentWidget);
        }
      }
    }
  });
}

export function traverseAllWidgets(widgetList, handler) {
  if (!widgetList) {
    return;
  }

  loopHandleWidget(widgetList, (w, parentWidget) => {
    handler(w, parentWidget);
  });

  /* widgetList.forEach((w) => {
    handler(w);

    if (w.type === "grid") {
      w.cols.forEach((col) => {
        handler(col);
        traverseAllWidgets(col.widgetList, handler);
      });
    } else if (w.type === "table") {
      w.rows.forEach((row) => {
        row.cols.forEach((cell) => {
          handler(cell);
          traverseAllWidgets(cell.widgetList, handler);
        });
      });
    } else if (w.type === "tab") {
      w.tabs.forEach((tab) => {
        traverseAllWidgets(tab.widgetList, handler);
      });
    } else if (w.type === "sub-form" || w.type === "grid-sub-form") {
      traverseAllWidgets(w.widgetList, handler);
    } else if (w.category === "container") {
      //自定义容器
      traverseAllWidgets(w.widgetList, handler);
    }
  }); */
}

function handleWidgetForTraverse(
  widget,
  handler,
  staticWidgetsIncluded = false
) {
  if (!!widget.category && widget.category === "container") {
    traverseFieldWidgetsOfContainer(widget, handler);
  } else if (widget.formItemFlag) {
    handler(widget);
  }
}

export const itemFieldMap = {
  grid: "cols",
  table: "rows",
  "table-cell": "widgetList",
  "h5-table": "rows",
  "h5-table-cell": "widgetList",
  tab: "tabs",
  "tab-pane": "widgetList",
  "grid-col": "widgetList",
  "vf-box": "widgetList",
  card: "widgetList",
  detail: "panes",
  "detail-pane": "widgetList",
  "detail-h5": "panes",
  "h5-card": "panes",
  "h5-card-pane": "widgetList",
};

/**
 * 遍历容器内的字段组件
 * @param con
 * @param handler
 * @param staticWidgetsIncluded
 */
export function traverseFieldWidgetsOfContainer(
  con,
  handler,
  staticWidgetsIncluded = false
) {
  /*loopHandleWidget([con],(w, parent)=>{
		handleWidgetForTraverse(w, handler, staticWidgetsIncluded);
  });*/
  if (con.type === "grid") {
    con.cols.forEach((col) => {
      col.widgetList.forEach((cw) => {
        handleWidgetForTraverse(cw, handler, staticWidgetsIncluded);
      });
    });
  } else if (con.type === "table") {
    con.rows.forEach((row) => {
      row.cols.forEach((cell) => {
        cell.widgetList.forEach((cw) => {
          handleWidgetForTraverse(cw, handler, staticWidgetsIncluded);
        });
      });
    });
  } else if (con.type === "tab") {
    con.tabs.forEach((tab) => {
      tab.widgetList.forEach((cw) => {
        handleWidgetForTraverse(cw, handler, staticWidgetsIncluded);
      });
    });
  } else if (con.type === "sub-form" || con.type === "grid-sub-form") {
    con.widgetList.forEach((cw) => {
      handleWidgetForTraverse(cw, handler, staticWidgetsIncluded);
    });
  } else if (con.type === "data-table") {
    /*con.widgetList.forEach((cw) => {
      handleWidgetForTraverse(cw, handler, staticWidgetsIncluded);
    });*/
    if (!!con.widgetList) {
      con.widgetList.forEach((childItem) => {
        loopHandleWidgetItem(childItem, con, handler);
      });
    }
    if (!!con.buttons) {
      con.buttons.forEach((childItem) => {
        loopHandleWidgetItem(childItem, con, handler);
      });
    }
    for (let column of con.options.tableColumns) {
      if (column.widget) {
        handleWidgetForTraverse(column.widget, handler, staticWidgetsIncluded);
      }
      if (column.widgetList) {
        column.widgetList.forEach((cw) => {
          handleWidgetForTraverse(cw, handler, staticWidgetsIncluded);
        });
        /*loopHandleWidget(column.widgetList, (cw) => {
          handleWidgetForTraverse(cw, handler, staticWidgetsIncluded);
        });*/
      }
    }
  } else if (con.category === "container") {
    //自定义容器
    /*let key = itemFieldMap[con.type]
    con[key].forEach((cw) => {
      handleWidgetForTraverse(cw, handler, staticWidgetsIncluded);
    });*/

    /*con.widgetList.forEach(cw => {
      handleWidgetForTraverse(cw, handler, staticWidgetsIncluded)
    })*/
    loopHandleWidgetItem(con, null, (w) => {
      if (con.id != w.id)
        handleWidgetForTraverse(w, handler, staticWidgetsIncluded);
    });
  }
}

function handleContainerTraverse(
  widget,
  fieldHandler,
  containerHandler,
  internalContainerCallFlag,
  staticWidgetsIncluded
) {
  if (!!widget.category && widget.category === "container") {
    traverseWidgetsOfContainer(
      widget,
      fieldHandler,
      containerHandler,
      internalContainerCallFlag,
      staticWidgetsIncluded
    );
  } else if (widget.formItemFlag) {
    fieldHandler(widget);
  } else if (staticWidgetsIncluded) {
    fieldHandler(widget);
  }
}

/**
 * 遍历容器内部的字段组件和容器组件
 * @param con
 * @param fieldHandler
 * @param containerHandler
 * @param internalContainerCallFlag 是否需要处理内部容器组件，默认不处理
 * @param staticWidgetsIncluded 是否需要处理静态非表单交互类组件
 */
export function traverseWidgetsOfContainer(
  con,
  fieldHandler,
  containerHandler,
  internalContainerCallFlag,
  staticWidgetsIncluded
) {
  if (con.category === "container") {
    containerHandler(con);
  }

  /*loopHandleWidget([con], (cw, parent) => {
    if (con.id !== cw.id) {
      handleContainerTraverse(
        cw,
        fieldHandler,
        containerHandler,
        internalContainerCallFlag,
        staticWidgetsIncluded
      );
    }
  });*/

  if (con.type === "grid") {
    con.cols.forEach((col) => {
      if (internalContainerCallFlag) {
        containerHandler(col);
      }
      col.widgetList.forEach((cw) => {
        handleContainerTraverse(
          cw,
          fieldHandler,
          containerHandler,
          internalContainerCallFlag,
          staticWidgetsIncluded
        );
      });
    });
  } else if (con.type === "table") {
    con.rows.forEach((row) => {
      if (internalContainerCallFlag) {
        containerHandler(row);
      }
      row.cols.forEach((cell) => {
        if (internalContainerCallFlag) {
          containerHandler(cell);
        }
        cell.widgetList.forEach((cw) => {
          handleContainerTraverse(
            cw,
            fieldHandler,
            containerHandler,
            internalContainerCallFlag,
            staticWidgetsIncluded
          );
        });
      });
    });
  } else if (con.type === "tab") {
    con.tabs.forEach((tab) => {
      if (internalContainerCallFlag) {
        containerHandler(tab);
      }
      tab.widgetList.forEach((cw) => {
        handleContainerTraverse(
          cw,
          fieldHandler,
          containerHandler,
          internalContainerCallFlag,
          staticWidgetsIncluded
        );
      });
    });
  } else if (con.type === "sub-form" || con.type === "grid-sub-form") {
    con.widgetList.forEach((cw) => {
      handleContainerTraverse(
        cw,
        fieldHandler,
        containerHandler,
        internalContainerCallFlag,
        staticWidgetsIncluded
      );
    });
  } else if (con.category === "container") {
    //自定义容器
    let key = itemFieldMap[con.type];
    con[key].forEach((cw) => {
      handleContainerTraverse(
        cw,
        fieldHandler,
        containerHandler,
        internalContainerCallFlag,
        staticWidgetsIncluded
      );
    });
  }
}

export function traverseWidgetsOfGridCol(
  gridCol,
  fieldHandler,
  containerHandler
) {
  // if (gridCol.category === 'container') {
  //   containerHandler(gridCol)
  // }

  if (gridCol.type === "grid-col") {
    gridCol.widgetList.forEach((cw) => {
      handleContainerTraverse(cw, fieldHandler, containerHandler);
    });
  }
}

/**
 * 获取所有字段组件
 * @param widgetList
 * @param staticWidgetsIncluded 是否包含按钮等静态组件，默认不包含
 * @returns {[]}
 */
export function getAllFieldWidgets(widgetList, staticWidgetsIncluded) {
  if (!widgetList) {
    return [];
  }

  let result = [];
  let handlerFn = (w) => {
    result.push({
      type: w.type,
      name: w.options.name,
      field: w,
    });
  };
  traverseFieldWidgets(widgetList, handlerFn, null, staticWidgetsIncluded);

  return result;
}

/**
 * 获取所有容器组件
 * @param widgetList
 * @param skipDialogAndDrawer 是否跳过弹窗和抽屉内部组件，默认不跳过
 * @returns {[]}
 */
export function getAllContainerWidgets(widgetList, skipDialogAndDrawer) {
  if (!widgetList) {
    return [];
  }

  let result = [];
  let handlerFn = (w) => {
    result.push({
      type: w.type,
      name: w.options.name,
      container: w,
    });
  };
  traverseContainerWidgets(widgetList, handlerFn, skipDialogAndDrawer);

  return result;
}

export function getFieldWidgetByName(
  widgetList,
  fieldName,
  staticWidgetsIncluded
) {
  if (!widgetList) {
    return null;
  }

  let foundWidget = null;
  let handlerFn = (widget) => {
    if (widget.options.name === fieldName) {
      foundWidget = widget;
    }
  };

  traverseFieldWidgets(widgetList, handlerFn, null, staticWidgetsIncluded);
  return foundWidget;
}

export const columnFormatMap = {
  editInput: "input",
  editNumber: "number",
  editDate: "date",
  editSelect: "select",
  editSearch: "vabsearch",
  editAttachment: "baseAttachment",
  editStatus: "status",
  aText: "a-text",
  aLink: "a-link",
  editDelete: "a-link",
  editButton: "a-link",
  button: "button",
  addSiblingEditRow: "a-link",
  addChildTreeRow: "a-link",
  moveUpRow: "a-link",
  moveDownRow: "a-link",
  removeTreeRow: "a-link",
  text: "text",
  checkbox: "checkbox",
  radio: "radio",
  dropdown: "dropdown",
  textarea: "textarea",
};

export function getFieldWidgetById(widgetList, fieldId, staticWidgetsIncluded) {
  if (!widgetList) {
    return null;
  }

  let foundWidget = null;
  let handlerFn = (widget) => {
    if (widget.id === fieldId) {
      foundWidget = widget;
    } else if (widget.type === "data-table") {
      for (let column of widget.options.tableColumns) {
        if (column?.widget?.id + "" === fieldId) {
          foundWidget = column.widget;
          break;
        } else if (column.widgetList) {
          loopHandleWidget(column.widgetList, (item1) => {
            if (item1.id === fieldId) {
              foundWidget = item1;
            }
          });
        }
      }
    }
  };

  traverseFieldWidgets(widgetList, handlerFn, null, staticWidgetsIncluded);
  return foundWidget;
}

export function getContainerWidgetByName(widgetList, containerName) {
  if (!widgetList) {
    return null;
  }

  let foundContainer = null;
  let handlerFn = (con) => {
    if (con.options.name === containerName) {
      foundContainer = con;
    }
  };

  traverseContainerWidgets(widgetList, handlerFn);
  return foundContainer;
}

export function getContainerWidgetById(widgetList, containerId) {
  if (!widgetList) {
    return null;
  }

  let foundContainer = null;
  let handlerFn = (con) => {
    if (con.id === containerId) {
      foundContainer = con;
    }
  };

  traverseContainerWidgets(widgetList, handlerFn);
  return foundContainer;
}

export function copyToClipboard(
  content,
  clickEvent,
  $message,
  successMsg,
  errorMsg
) {
  const clipboard = new Clipboard(clickEvent.target, {
    text: () => content,
  });

  clipboard.on("success", () => {
    $message.success(successMsg);
    clipboard.destroy();
  });

  clipboard.on("error", () => {
    $message.error(errorMsg);
    clipboard.destroy();
  });

  clipboard.onClick(clickEvent);
}

export function getQueryParam(variable) {
  let query = window.location.search.substring(1);
  let vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split("=");
    if (pair[0] === variable) {
      return pair[1];
    }
  }

  return undefined;
}

export function getDefaultFormConfig() {
  return {
    modelName: "formData",
    refName: "vForm",
    rulesName: "rules",
    labelWidth: 80,
    labelPosition: "left",
    size: "",
    labelAlign: "label-right-align",
    cssCode: "",
    customClass: "",
    functions: "",
    layoutType: "PC",
    dataSources: [],
    onBeforeCreated: "",
    onFormCreated: "",
    onFormBeforeMounted: "",
    onFormMounted: "",
    onFormDataChange: "",
    gridConfig: {
      accessReturnType: 1,
      isLoadDataByAccess: false,
    },
    getConfig: {
      accessType: "1",
      accessUrl: null,
      accessParam: null,
      accessCallback: null,
      scriptName: null,
      scriptCode: null,
    },
    saveConfig: {
      accessType: "1",
      accessUrl: null,
      accessParam: null,
      accessCallback: null,
      scriptName: null,
      scriptCode: null,
    },
    scriptList: [],
    formType: 0,
    entityTableCode: null,
    entityTableDesc: null,
    editFormCode: null,
    editFormName: null,
    searchDialogNameField: null,
    searchDialogUniqueField: null,
    entity: null,
    wfEnabled: false,
    isLoadEntity: false,
    formScriptCode: "getOne",
    formScriptParam: null,
    formScriptSuccess: null,
    saveScriptCode: "saveUpdate",
    wfConfig: null,
    wfStartBindSave: false,
    wfAgreenBindSave: false,
    wfAgreeConfigData: [],
    wfConfigDataEnabled: false,
    wfConfigData: [],
    multiTabEnabled: false,
    multiTabLabelField: null,
    addFormCode: null,
    addFormName: null,
    wfTheme: null,
    otherTabEnabled: false,
    otherTabList: [],
    customListTabLabel: null,
    globalConfig: null,
  };
}

export function buildDefaultFormJson() {
  return {
    widgetList: [],
    formConfig: deepClone(getDefaultFormConfig()),
  };
}

export function cloneFormConfigWithoutEventHandler(e) {
  var t = deepClone(e);
  return (
    (t.onFormCreated = ""),
    (t.onFormBeforeMounted = ""),
    (t.onFormMounted = ""),
    (t.onFormDataChange = ""),
    t
  );
}

export function translateOptionItems(rawData, widgetType, labelKey, valueKey) {
  if (widgetType === "cascader") {
    // 级联选择不转译
    return deepClone(rawData);
  }

  let result = [];
  if (!!rawData && rawData.length > 0) {
    result = deepClone(rawData);
    result.forEach((ri) => {
      ri[labelKey] = ri[labelKey] ?? null;
      ri[valueKey] = ri[valueKey] ?? null;
    });
  }

  return result;
}

export function assembleAxiosConfig(arrayObj, DSV, VFR) {
  var result = {};
  if (arrayObj && arrayObj.length) {
    arrayObj.map(function (ai) {
      if ("String" === ai.type) {
        result[ai.name] = String(ai.value);
      } else if ("Number" === ai.type) {
        result[ai.name] = Number(ai.value);
      } else if ("Boolean" === ai.type) {
        "false" === ai.value.toLowerCase() || "0" === ai.value
          ? (result[ai.name] = !1)
          : "true" === ai.value.toLowerCase() || "1" === ai.value
          ? (result[ai.name] = !0)
          : (result[ai.name] = null);
      } else if ("Variable" === ai.type) {
        result[ai.name] = eval(ai.value);
      } else if ("FormData" === ai.type) {
        if (VFR.formDataModel.hasOwnProperty(ai.value)) {
          result[ai.name] = VFR.formDataModel[ai.value];
        } else {
          let parentForm = VFR.parentForm;
          if (parentForm && parentForm.formDataModel.hasOwnProperty(ai.value)) {
            result[ai.name] = parentForm.formDataModel[ai.value];
          }
        }
      }
    });
  }
  return result;
}

export function buildRequestConfig(dataSource, DSV, VFR, isSandbox) {
  var config = {};
  /* "String" === dataSource.requestaccessType ? config.url = dataSource.requestURL : config.url = eval(dataSource
      .requestURL), */
  let requestAccess = DSV.requestAccess;
  // config.url = dataSource.requestURL;
  config.url = getAccessUrl();
  (config.method = dataSource.requestMethod || "post"),
    (config.headers = assembleAxiosConfig(dataSource.headers, DSV, VFR)),
    (config.params = assembleAxiosConfig(dataSource.params, DSV, VFR));
  // config.data = assembleAxiosConfig(dataSource.data, DSV, VFR);
  let data = {};
  let conditions = assembleAxiosConfig(dataSource.data, DSV, VFR);

  let globalReqData = getReportGlobalMap(); //全局请求参数
  Object.assign(conditions, globalReqData);

  let doms = VFR.getWidgetRef(DSV.widgetName);
  let extraAccessData = doms.extraAccessData || {};

  data.accessCode = requestAccess.accessCode;
  data.conditions = conditions;
  Object.assign(data.conditions, extraAccessData);

  config.data = data;
  var chFn = new Function(
    "config",
    "isSandbox",
    "DSV",
    "VFR",
    dataSource.configHandlerCode
  );
  return chFn.call(null, config, isSandbox, DSV, VFR);
}

export function runDataSourceRequest(e, t, i, n, o) {
  return _runDataSourceRequest.apply(this, arguments);
}

export function _runDataSourceRequest() {
  let _runDataSourceRequestN = function (t, i, n, o, a) {
    var l, s, r, d;
    (l = buildRequestConfig(t, i, n, o)),
      (r = new Function(
        "result",
        "isSandbox",
        "DSV",
        "VFR",
        t.dataHandlerCode
      )),
      (d = new Function(
        "error",
        "isSandbox",
        "DSV",
        "$message",
        "VFR",
        t.errorHandlerCode
      ));

    return new Promise((resolve, reject) => {
      request({
        ...l,
        callback: (res) => {
          resolve(r.call(null, res, o, i, n));
        },
        error: (error) => {
          d.call(null, error, o, i, a, n);
          reject(error);
        },
      });
    });
  };
  return _runDataSourceRequestN.apply(this, arguments);
}

export function getDSByName(e, t) {
  var i = null;
  return (
    t &&
      e.dataSources &&
      e.dataSources.forEach(function (e) {
        e.uniqueName === t && (i = e);
      }),
    i
  );
}

export function setReportGlobalParam(value) {
  sessionStorage.setItem("reportGlobalParam", value);
}

export function getReportGlobalMap() {
  let param = sessionStorage.getItem("reportGlobalParam");
  if (param) {
    let globalReqData = JSON.parse(decode(param));
    return globalReqData;
  }
}

export function getSubFormNameByFieldId(o, e) {
  let n = null;
  return (
    getAllContainerWidgets(o).forEach((s) => {
      const c = (u) => {
        u.id === e && (n = s.name);
      };
      (s.type === "sub-form" || s.type === "grid-sub-form") &&
        traverseFieldWidgetsOfContainer(s.container, c);
    }),
    n
  );
}

export const FORMULA_REG_EXP = /\{\{(\w+\.[^.]+\.\w+)}}/g;

export function fieldIsUsedInFormula(o, e, n) {
  const l = e.match(FORMULA_REG_EXP);
  if (!l) return !1;
  let s = !1;
  return (
    l.forEach((c) => {
      const u = c.split(".")[2];
      if (u.substring(0, u.length - 2) === "func") return;
      const g = c.split(".")[0],
        y = g.substring(2, g.length);
      getFieldWidgetById(n.formJsonObj.widgetList, y, !1).options.name === o &&
        (s = !0);
    }),
    s
  );
}

export function calculateFormula(o, e, n, l, s) {
  if (
    !!l.subFormItemFlag &&
    !!s.subFormItemFlag &&
    s.subFormRowId !== l.subFormRowId
  )
    return;
  let c = l.field.options.formula;
  c = replaceFieldsAndFunctionsOfFormula(o, l);
  const u = c.match(/[A-Za-z]*/g);
  u &&
    u.forEach((g) => {
      if (!!g && findCalFunStartIndex(g) !== -1) {
        const y = g.toUpperCase();
        c = c.replace(g, "formulaJs." + y);
      }
    }),
    console.log("formula: ", c),
    console.log("formulaFieldRef: ", l);
  const $ = evalFn(c, e, o, n);
  l.setValue($);
}

export function replaceFieldsAndFunctionsOfFormula(o, e) {
  let n = e.field.options.formula;
  const l = n.match(FORMULA_REG_EXP);
  if (!l) return n;
  let s = n;
  return (
    l.forEach((c) => {
      const u = c.split(".")[2];
      if (u.substring(0, u.length - 2) === "func") {
        const v = c.split(".")[1];
        s = s.replace(c, v);
        return;
      }
      const g = c.split(".")[0],
        y = g.substring(2, g.length),
        f = getFieldWidgetById(o.formJsonObj.widgetList, y, !1);
      if (f) {
        let v = o.getWidgetRef(f.options.name);
        if (v) s = s.replace(c, v.getValue());
        else {
          const w = o.getSubFormNameOfWidget(f.options.name);
          if (e.subFormItemFlag)
            w === e.subFormName
              ? ((v = o.getWidgetRef(f.options.name + "@row" + e.subFormRowId)),
                v && (s = s.replaceAll(c, v.getValue())))
              : console.error("Invalid formula!");
          else {
            const _ = o.formDataModel[w];
            let O = "";
            const S = f.options.name;
            _.forEach((x, E) => {
              O = E === 0 ? x[S] : O + ", " + x[S];
            }),
              (s = s.replaceAll(c, O));
          }
        }
      }
    }),
    s
  );
}

export function findCalFunStartIndex(o) {
  let e = -1;
  for (let n = 0; n < FORMULA_JS_FUNCTIONS.length; n++) {
    let l = o.indexOf(FORMULA_JS_FUNCTIONS[n]);
    if (l !== -1) return l;
  }
  return e;
}

export const FORMULA_JS_FUNCTIONS = [
    "INT",
    "SUM",
    "AVERAGE",
    "MAX",
    "MIN",
    "ABS",
    "ROUND",
    "CEILING",
    "LOG",
    "MOD",
    "POWER",
    "AND",
    "IF",
    "IFS",
    "IFERROR",
    "IFNA",
    "NOT",
    "OR",
    "SWITCH",
    "XOR",
    "YEAR",
    "MONTH",
    "DAY",
    "TODAY",
    "NOW",
    "EMONTH",
    "EDAY",
    "FIND",
    "LEFT",
    "RIGHT",
    "LEN",
    "LOWER",
    "UPPER",
    "MID",
    "TRIM",
  ],
  formulas = [
    {
      fClass: "designer.hint.formulaFunctionMaths",
      flist: [
        {
          fName: "INT",
          fType: "designer.hint.formulaNumber",
          fIntro: "designer.hint.formulaINT",
        },
        {
          fName: "SUM",
          fType: "designer.hint.formulaNumber",
          fIntro: "designer.hint.formulaSUM",
        },
        {
          fName: "AVERAGE",
          fType: "designer.hint.formulaNumber",
          fIntro: "designer.hint.formulaAVERAGE",
        },
        {
          fName: "MAX",
          fType: "designer.hint.formulaNumber",
          fIntro: "designer.hint.formulaMAX",
        },
        {
          fName: "MIN",
          fType: "designer.hint.formulaNumber",
          fIntro: "designer.hint.formulaMIN",
        },
        {
          fName: "ABS",
          fType: "designer.hint.formulaNumber",
          fIntro: "designer.hint.formulaABS",
        },
        {
          fName: "ROUND",
          fType: "designer.hint.formulaNumber",
          fIntro: "designer.hint.formulaROUND",
        },
        {
          fName: "CEILING",
          fType: "designer.hint.formulaNumber",
          fIntro: "designer.hint.formulaCEILING",
        },
        {
          fName: "LOG",
          fType: "designer.hint.formulaNumber",
          fIntro: "designer.hint.formulaLOG",
        },
        {
          fName: "MOD",
          fType: "designer.hint.formulaNumber",
          fIntro: "designer.hint.formulaMOD",
        },
        {
          fName: "POWER",
          fType: "designer.hint.formulaNumber",
          fIntro: "designer.hint.formulaPOWER",
        },
      ],
    },
  ];

export function evalFn(o, e = null, n = null, l = null) {
  return new Function("DSV", "VFR", "LS", "formulaJs", "return " + o)(
    e,
    n,
    localStorage,
    l
  );
}

export function trimEx(o, e, n) {
  return e
    ? n === "left"
      ? o.replace(new RegExp("^%%" + e + "+", "g"), "")
      : n === "right"
      ? o.replace(new RegExp("%%" + e + "+$", "g"), "")
      : o.replace(new RegExp("^%%" + e + "+|%%" + e + "+$", "g"), "")
    : o.replace(/^%s+|%s+$/g, "");
}

export function hasPropertyOfObject(o, e) {
  const n = e.split(".");
  let l = o,
    s = !0;
  for (const c of n)
    if (l.hasOwnProperty(c)) l = l[c];
    else {
      s = !1;
      break;
    }
  return s;
}

export function objectKeysToArray(o) {
  if (!o) return [];
  const e = [];
  return (
    Object.keys(o).forEach((n) => {
      e.push(n);
    }),
    e
  );
}

//begin
export function loopHandleWidget(widgetList, callback) {
  widgetList &&
    widgetList.length > 0 &&
    widgetList.forEach(function (e) {
      loopHandleWidgetItem(e, null, callback);
    });
}

function loopHandleWidgetItem(e, p, callback) {
  if ("container" === e.category) {
    callback(e, p);
    if ("vf-dialog" === e.type || "vf-drawer" === e.type);
    else if ("data-table" === e.type) {
      if (!!e.widgetList) {
        e.widgetList.forEach((childItem) => {
          loopHandleWidgetItem(childItem, e, callback);
        });
      }
      if (!!e.buttons) {
        e.buttons.forEach((childItem) => {
          loopHandleWidgetItem(childItem, e, callback);
        });
      }
    } else if ("list-h5" === e.type) {
      if (!!e.widgetList && e.widgetList.length > 0) {
        e.widgetList.forEach((childItem) => {
          loopHandleWidgetItem(childItem, e, callback);
        });
      }
    } else if ("grid" === e.type) {
      e.cols &&
        e.cols.length > 0 &&
        e.cols.forEach(function (childItem) {
          loopHandleWidgetItem(childItem, e, callback);
        });
    } else if ("table" === e.type) {
      e.rows &&
        e.rows.length > 0 &&
        e.rows.forEach(function (rowItem) {
          rowItem.cols &&
            rowItem.cols.length > 0 &&
            rowItem.cols.forEach(function (childItem) {
              loopHandleWidgetItem(childItem, e, callback);
            });
        });
    } else if ("h5-table" === e.type) {
      e.rows &&
        e.rows.length > 0 &&
        e.rows.forEach(function (rowItem) {
          rowItem.cols &&
            rowItem.cols.length > 0 &&
            rowItem.cols.forEach(function (childItem) {
              loopHandleWidgetItem(childItem, e, callback);
            });
        });
    } else if ("tab" === e.type) {
      e.tabs &&
        e.tabs.length > 0 &&
        e.tabs.forEach(function (tabItem) {
          tabItem.widgetList &&
            tabItem.widgetList.length > 0 &&
            tabItem.widgetList.forEach(function (childItem) {
              loopHandleWidgetItem(childItem, e, callback);
            });
        });
    } else if ("detail" === e.type) {
      if (e.panes) {
        e.panes.forEach(function (childItem) {
          loopHandleWidgetItem(childItem, e, callback);
        });
      }
      if (e.widgetList) {
        e.widgetList.forEach(function (childItem) {
          loopHandleWidgetItem(childItem, e, callback);
        });
      }
    } else if ("detail-pane" === e.type) {
      if (e.widgetList) {
        e.widgetList.forEach(function (childItem) {
          loopHandleWidgetItem(childItem, e, callback);
        });
      }
      if (e.buttonWidgetList) {
        e.buttonWidgetList.forEach(function (childItem) {
          loopHandleWidgetItem(childItem, e, callback);
        });
      }
    } else {
      "grid-col" === e.type || e.type,
        e.widgetList &&
          e.widgetList.length > 0 &&
          e.widgetList.forEach(function (childItem) {
            loopHandleWidgetItem(childItem, e, callback);
          });
    }
  } else {
    callback && callback(e);
    if (e.widgetList) {
      e.widgetList.forEach(function (childItem) {
        loopHandleWidgetItem(childItem, e, callback);
      });
    }
  }
}

//end

export function trim(value) {
  if (isNull(value)) return value;
  if (value.trim) {
    return value.trim();
  } else {
    return value;
  }
}
