"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.SetterEventName = exports.EngineRuleBeforeFlag = void 0;
exports.assignValues = assignValues;
exports.compatibleTupleData = compatibleTupleData;
exports.copyToClipboard = copyToClipboard;
exports.createMaterialUUID = createMaterialUUID;
exports.createOnly = createOnly;
exports.filter_source = filter_source;
exports.get = void 0;
exports.getChainIdOptions = getChainIdOptions;
exports.getComponentId = getComponentId;
exports.getEngValue = getEngValue;
exports.getLangType = getLangType;
exports.getLocalizedDescription = getLocalizedDescription;
exports.getLocationParamsByName = getLocationParamsByName;
exports.getTupleOriginOptions = getTupleOriginOptions;
exports.getValidString = getValidString;
exports.handleMaterialUUID = handleMaterialUUID;
exports.handleRenderByFormKeyData = handleRenderByFormKeyData;
exports.has = void 0;
exports.isIncludesFlag = isIncludesFlag;
exports.isJSON = isJSON;
exports.isValidJSON = isValidJSON;
exports.materialFlag = materialFlag;
exports.processField = processField;
exports.set = void 0;
exports.setSnippetRef = setSnippetRef;
exports.uuid = uuid;
var _regenerator = _interopRequireDefault(require("@babel/runtime/regenerator"));
var _asyncToGenerator2 = _interopRequireDefault(require("@babel/runtime/helpers/asyncToGenerator"));
var _lodash = require("lodash");
exports.get = _lodash.get;
exports.set = _lodash.set;
exports.has = _lodash.has;
var _formKeyType = require("./formKeyType");
var _locale = require("../../src/locale");
var _utils = require("../_setters/cBehavior-setter/config/utils");
var _coreConnectorBeta = require("@cverse/core-connector-beta");
var _useWalletConnect = (0, _coreConnectorBeta.useWalletConnect)(),
  walletConnect = _useWalletConnect.walletConnect;
// simple uuid
function uuid() {
  return (Math.random() * 1e6 >> 0).toString(36);
}
function createOnly() {
  return uuid() + "-" + uuid() + "-" + uuid();
}

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

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

  return flagType;
}

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

/**
 * 切割指定字符串，并返回第二个数据
 * @param str 
 * @param flag 
 * @returns 
 */
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 
 */
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 '';
}
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})}"
    // },
  };
}
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 
 */
function filter_source(data) {
  if ((0, _lodash.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]';
};
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 ((0, _lodash.isArray)(value) || regArray.test(value)) {
      result = JSON.stringify(value);
    } else {
      result = "" + value;
    }
  } else {
    result = '';
  }
  return result;
}

/**
 * 获取地址栏参数
 * @param name 
 * @returns 
 */
function getLocationParamsByName(name) {
  var url = new URL(window.location.href);
  var params = new URLSearchParams(url.search);
  return params.get(name);
}
var SetterEventName = exports.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);
}
function copyToClipboard(_x) {
  return _copyToClipboard.apply(this, arguments);
}
/**
 * 过滤中文，特殊符号
 * @param str 
 * @returns 
 */
function _copyToClipboard() {
  _copyToClipboard = (0, _asyncToGenerator2["default"])(/*#__PURE__*/_regenerator["default"].mark(function _callee(text) {
    var newText;
    return _regenerator["default"].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);
}
function getEngValue(str) {
  var filteredValue = str.replace(/[^\x00-\x7F]+/g, ''); // 过滤非ASCII字符（包括中文字符）
  return filteredValue.replace(/[^A-Za-z0-9]/g, ''); // 或者仅保留英文和数字
}
function getLangType() {
  return localStorage.getItem('lang') || 'en';
}
function handleRenderByFormKeyData(list, callBack) {
  var newItem = {};
  list.forEach(function (item) {
    var key = item.key,
      value = item.value;
    newItem[key] = value;
  });
  callBack(newItem);
}

/**
 * 编辑态通过localStorage缓存获取
 * @returns 
 */
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;
}
function getTupleOriginOptions() {
  return [{
    label: (0, _locale.t)('setter.tupleOriginDefault'),
    value: _formKeyType.TupleOriginType["default"]
  }, {
    label: (0, _locale.t)('setter.tupleOriginCustomData'),
    value: _formKeyType.TupleOriginType.customData
  }];
}
/**
 * 兼容元组数据内容
 * @param value 
 * @returns 
 */
function compatibleTupleData(value) {
  var result = {
    originType: _formKeyType.TupleOriginType["default"],
    defaultData: [],
    customData: (0, _utils.getInitStateKey)(_formKeyType.DataSourceType.defaultType, '')
  };
  if ((0, _lodash.isArray)(value)) {
    result.defaultData = value;
  } else if (value.originType) {
    result = value;
  }
  return result;
}
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;
    }
  }
}
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
  }
}
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
    };
  }
}
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;
  }
}