import pinyin from 'js-pinyin';
/**
 * 数据过滤工具类
 * @author cls
 * @date 2019-11-01
 */



/**
 * showdoc
 * @catalog JS工具类/DataFilter
 * @title 根据表达式过滤数据结果
 * @description 根据传入js过滤表达式，过滤数据结果, this为当前记录对象
 * @method static
 * @url import { dataFilterByExpr } from '@birt/funclib/DataFilter.js'
 * @param datas 必选 [{},{}] 记录集对象,树分组字段值冗余
 * @param expr js过滤表达式 
 * @return [{'f1':'v1','f2':'v2'}] 过滤结果集
 * @remark 测试用例
 *  dataFilterByExpr(
 *    [{f1:1},{f1:2},{f1:3},{f1:4}],
 *    "this.f1>2"
 *  )
 *  返回==>
 *  [{f1:3},{f1:4}]
 */
export function dataFilterByExpr(datas, expr) {
  if (expr) {
    let filterDatas = [];
    var execFilterExper = function (expr) {
      return eval(expr)
    };
    for (var i = 0, l = datas.length; i < l; i++) {
      let recd = datas[i];
      if (execFilterExper.call(recd, expr)) {
        filterDatas.push(recd);
      }
    }
    return filterDatas;
  } else {
    return datas;
  }
}

/**
 * showdoc
 * @catalog JS工具类/DataFilter
 * @title isFilterRecdByCdionItem(当前记录，过滤条件项)
 * @description 根据过滤条件配置验证当前记录是否合法
 * @method static
 * @url import { isFilterRecdByCdionItem } from '@birt/funclib/DataFilter.js'
 * @param recd 必选 {} 过滤记录
 * @param cdionItem 当前过滤条件 
 * @return true|false 
 * @remark 测试用例
 */
export function isFilterRecdByCdionItem(recd, cdionItem) {
  let label = recd[cdionItem.name];
  if (label == undefined) {
    console.warn("当前记录对象取不到字段[" + cdionItem.name + "],可能字段对象不够完整")
  }
  if (cdionItem.sign == "eq") {
    if (cdionItem.dataType == "boolean") {
      label = convertBooleanFalse(label);
    }
    return label == cdionItem.value;
  } else if (cdionItem.sign == "pinyin") {
    if (!label) return false;
    label += pinyin.getCamelChars(label).toUpperCase();
    return label.indexOf(cdionItem.value.toUpperCase()) !== -1;
  } else if (cdionItem.sign == "method") {
    let filterFunc = cdionItem.filterMethod;
    return filterFunc.call(this, recd, cdionItem);
  }
}

/**
 * showdoc
 * @catalog JS工具类/DataFilter
 * @title convertBooleanFalse(布尔值)
 * @description 根据传入值，判断是否意义上的假值，转换成boolean的false
 * @method static
 * @url import { convertBooleanFalse } from '@birt/funclib/DataFilter.js'
 * @param val 必选 * 布尔值
 * @return 原值|false 
 * @remark 测试用例
 */
export function convertBooleanFalse(val) {
  return (val === undefined || val === '0' || val === 0 || val === 'false') ? false : val;
}