import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { isArray } from 'lodash';
import { DataSourceType, TupleOriginType } from "./formKeyType";
import { t } from "../../src/locale";
import { getInitStateKey } from "../_setters/cBehavior-setter/config/utils";
import { useWalletConnect } from "@cverse/core-connector-beta";
var _useWalletConnect = useWalletConnect(),
  walletConnect = _useWalletConnect.walletConnect;
export { get, set, has } from 'lodash';

// simple uuid
export function uuid() {
  return (Math.random() * 1e6 >> 0).toString(36);
}
export function createOnly() {
  return uuid() + "-" + uuid() + "-" + uuid();
}

/**
 * 用于生成唯一标识，uuid _)(_ str
 * @param str 
 * @returns 
 */
export function createMaterialUUID(str) {
  return "c" + uuid() + materialFlag() + str;
}

/**
 * 统一对外暴露拼接字符串
 * @returns 
 */
export function materialFlag() {
  var flagType = '_'; // 用于处理物料

  return flagType;
}

/**
 * 引擎规则表达式前缀内容
 */
export var EngineRuleBeforeFlag = 'c';
export function isIncludesFlag(str) {
  return str.includes(materialFlag());
}

/**
 * 切割指定字符串，并返回第二个数据
 * @param str 
 * @param flag 
 * @returns 
 */
export function handleMaterialUUID(str, flag) {
  if (flag === void 0) {
    flag = materialFlag();
  }
  var result = str;
  if (str.includes(flag)) {
    result = str.split(flag)[1];
  }
  return result;
}

/**
 * 获取模块id
 * @param props 
 * @returns 
 */
export function getComponentId(props) {
  if (!props) {
    console.error('--The parse object does not exist', props);
    return '';
  }
  // 所有的外层都有node_key_id属性
  if (props.node_key_id) {
    return props.node_key_id;
  }

  // 如果是表单项
  if (props.formItemProps && props.formItemProps.node_key_id) {
    return props.formItemProps.node_key_id;
  }
  return '';
}
export function setSnippetRef() {
  return {
    // getPageThis: {
    //   "type": "JSFunction",
    //   "value": "function() {return this}"
    // },
    // getState: {
    //   "type": "JSFunction",
    //   "value": "function(stateName){return this.state[stateName]}"
    // },
    // setState: {
    //   "type": "JSFunction",
    //   "value": "function (setName,setValue){this.setState({[setName]:setValue})}"
    // },
  };
}
export function isJSON(str) {
  if (typeof str === 'string') {
    try {
      var obj = JSON.parse(str);
      return typeof obj === 'object' && obj;
    } catch (e) {
      console.log('error：' + str + '!!!' + e);
      return false;
    }
  }
  return false;
}

/**
 * 页面组件单选是会存在_source，需要过滤掉
 * @param data 
 * @returns 
 */
export function filter_source(data) {
  if (isArray(data)) {
    for (var i = 0; i < data.length; i++) {
      var item = data[i];
      if (item._source) {
        delete item._source;
      }
    }
  } else {
    if (data._source) {
      delete data._source;
    }
  }
  return data;

  // const keys = Object.keys(data)
  // const result:any = {}
  // keys.forEach(kk => {
  //     if (kk !== '_source') {
  //         result[kk] = data[kk]
  //     }
  // })
  // return result
}

/**
 * 固定值的应该都应先转成字符串
 * 数组[],
 * 对象:{}
 * 布尔都转成字符串，
 * 后期翻译的时候会出来成对应的内容
 * @param value 
 * @returns 
 */
var isObject = function isObject(value) {
  return Object.prototype.toString.call(value) === '[object Object]';
};
export function getValidString(value) {
  var result;
  var regObject = /^\{.*\}$/;
  var regArray = /^\[(.*)]$/;
  if (!(value === undefined || value === null || value === '')) {
    if (isObject(value) || regObject.test(value)) {
      result = JSON.stringify(value);
    } else if (isArray(value) || regArray.test(value)) {
      result = JSON.stringify(value);
    } else {
      result = "" + value;
    }
  } else {
    result = '';
  }
  return result;
}

/**
 * 获取地址栏参数
 * @param name 
 * @returns 
 */
export function getLocationParamsByName(name) {
  var url = new URL(window.location.href);
  var params = new URLSearchParams(url.search);
  return params.get(name);
}
export var SetterEventName = /*#__PURE__*/function (SetterEventName) {
  SetterEventName["flowEventConfig"] = "flowEventConfig";
  SetterEventName["ruleNodeGroupConfig"] = "ruleNodeGroupConfig";
  return SetterEventName;
}({});
function copyData(text) {
  var copyTextarea = document.createElement('textarea');
  copyTextarea.value = text;
  copyTextarea.style.visibility = 'absolute';
  copyTextarea.style.left = '-9999px';
  document.body.appendChild(copyTextarea);
  copyTextarea.select();
  document.execCommand('copy');
  document.body.removeChild(copyTextarea);
}
export function copyToClipboard(_x) {
  return _copyToClipboard.apply(this, arguments);
}

/**
 * 过滤中文，特殊符号
 * @param str 
 * @returns 
 */
function _copyToClipboard() {
  _copyToClipboard = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(text) {
    var newText;
    return _regeneratorRuntime.wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          newText = text.replace(/%n/g, '\r\n');
          copyData(newText);
        case 2:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return _copyToClipboard.apply(this, arguments);
}
export function getEngValue(str) {
  var filteredValue = str.replace(/[^\x00-\x7F]+/g, ''); // 过滤非ASCII字符（包括中文字符）
  return filteredValue.replace(/[^A-Za-z0-9]/g, ''); // 或者仅保留英文和数字
}
export function getLangType() {
  return localStorage.getItem('lang') || 'en';
}
export function handleRenderByFormKeyData(list, callBack) {
  var newItem = {};
  list.forEach(function (item) {
    var key = item.key,
      value = item.value;
    newItem[key] = value;
  });
  callBack(newItem);
}

/**
 * 编辑态通过localStorage缓存获取
 * @returns 
 */
export function getChainIdOptions() {
  var result = [];
  var connectorNetworks = localStorage.getItem('connectorNetworks');
  if (connectorNetworks) {
    var cnObj = JSON.parse(connectorNetworks);
    Object.keys(cnObj).forEach(function (key) {
      var list = cnObj[key];
      if (list) {
        list.forEach(function (item) {
          result.push({
            label: item.chainName,
            value: item.chainId
          });
        });
      }
    });
  }
  var centerChain = result.find(function (item) {
    return "" + item.chainId === '-1';
  });
  if (!centerChain) {
    result.unshift({
      value: -1,
      label: 'Center'
    });
  }
  return result;
}
export function getTupleOriginOptions() {
  return [{
    label: t('setter.tupleOriginDefault'),
    value: TupleOriginType["default"]
  }, {
    label: t('setter.tupleOriginCustomData'),
    value: TupleOriginType.customData
  }];
}
/**
 * 兼容元组数据内容
 * @param value 
 * @returns 
 */
export function compatibleTupleData(value) {
  var result = {
    originType: TupleOriginType["default"],
    defaultData: [],
    customData: getInitStateKey(DataSourceType.defaultType, '')
  };
  if (isArray(value)) {
    result.defaultData = value;
  } else if (value.originType) {
    result = value;
  }
  return result;
}
export function assignValues(data) {
  if (typeof data === "string") {
    return {
      en: data,
      zh: data,
      zh_tw: data
    };
  } else {
    var zh = data.zh,
      zh_tw = data.zh_tw,
      en = data.en;
    if (en && !zh && !zh_tw) {
      return {
        en: en,
        zh: en,
        zh_tw: en
      };
    } else if (en && zh && !zh_tw) {
      return {
        en: en,
        zh: zh,
        zh_tw: zh
      };
    } else if (en && zh_tw && !zh) {
      return {
        en: en,
        zh: zh_tw,
        zh_tw: zh_tw
      };
    } else if (zh && !en && !zh_tw) {
      return {
        en: zh,
        zh: zh,
        zh_tw: zh
      };
    } else if (zh_tw && !zh && !en) {
      return {
        en: zh_tw,
        zh: zh_tw,
        zh_tw: zh_tw
      };
    } else if (zh_tw && zh && !en) {
      return {
        en: zh_tw,
        zh: zh,
        zh_tw: zh_tw
      };
    } else {
      return data;
    }
  }
}
export function isValidJSON(str) {
  try {
    JSON.parse(str);
    return true; // If parsing succeeds, it's valid JSON
  } catch (e) {
    return false; // If parsing fails, it's not valid JSON
  }
}
export function processField(field) {
  if (!field) {
    return {
      en: "",
      zh: "",
      zh_tw: ""
    };
  }
  if (isValidJSON(field)) {
    return JSON.parse(field);
  } else {
    return {
      en: field,
      zh: field,
      zh_tw: field
    };
  }
}
export function getLocalizedDescription(desc) {
  if (!desc) {
    return null;
  }
  var currentLang = walletConnect.value.lang || "en";
  if (isValidJSON(desc)) {
    var newData = JSON.parse(desc);
    return newData[currentLang] || null;
  } else {
    return desc;
  }
}