/**
 * Transform record to option
 *
 * @example
 *   ```ts
 *   const record = {
 *     key1: 'label1',
 *     key2: 'label2'
 *   };
 *   const options = transformRecordToOption(record);
 *   // [
 *   //   { value: 'key1', label: 'label1' },
 *   //   { value: 'key2', label: 'label2' }
 *   // ]
 *   ```;
 *
 * @param record
 */
export function transformRecordToOption<T extends Record<string, string>>(record: T) {
  return Object.entries(record).map(([value, label]) => ({
    value,
    label
  })) as Common.Option<keyof T>[];
}

/**
 * 将数据转换为树形结构
 * @param datas
 * @param key
 * @param parentKey
 * @param childrenKey
 */
export function toTree(datas, key: string = 'id', parentKey: string = 'parentId', childrenKey: string = 'children') {
  let result = [];
  let keyToObject = {};
  for (let i = 0; i < datas.length; ++i) {
    let data = datas[i];
    data[childrenKey] = [];
    //防止undefined造成无限嵌套
    if (data[key]) {
      keyToObject[data[key]] = data;
    } else {
      //直接为顶级内容
      result.push(data);
    }
  }
  //找父级
  for (let key in keyToObject) {
    let data = keyToObject[key];
    if (data[parentKey] && keyToObject[data[parentKey]]) {
      keyToObject[data[parentKey]][childrenKey].push(data);
    } else {
      result.push(data);
    }
  }
  return result;
};


/**
 *
 * @param input
 * @param option
 */
export function selectFilterOption(input: string, option: any) {
  if (!input || !option) {
    return true;
  }
  let inputs = [input];
  if (input.indexOf(",") != -1) {
    inputs = input.split(",");
  } else if (input.indexOf(";") != -1) {
    inputs = input.split(";");
  } else if (input.indexOf("，") != -1) {
    inputs = input.split("，");
  } else if (input.indexOf(" ") != -1) {
    inputs = input.split(" ");
  }
  for (let i = 0; i < inputs.length; i++) {
    if(option.label != null){
      if ((option.label + '').toLowerCase().indexOf(inputs[i].toLowerCase()) >= 0) {
        return true;
      }
    }
    if(option.text   != null){
      if ((option.text + '').toLowerCase().indexOf(inputs[i].toLowerCase()) >= 0) {
        return true;
      }
    }
    if(option.value != null){
      if ((option.value + '').toLowerCase().indexOf(inputs[i].toLowerCase()) >= 0) {
        return true;
      }
    }
  }
  return false;
}
