import { cloneDeep, omit, get, head, last } from 'lodash';

/**
 * @constructor
 * 通过object传过来,名称需要匹配Param
 * @:范围查询 ${prop}@start/${prop}@end
 * []:多条件查询: ${prop}[]
 * @param {Array} like_prop 范围查询字段数组
 * @param {Array} props 需要处理的属性
 * @param {object} mapping 属性的映射
 */
export class SearchBase {
  constructor({ like_prop = [], props = [], mapping = {} }) {
    this.like_prop = like_prop;
    this.props = props;
    this.mapping = mapping;
  }
  /** 模糊查询字段数组 */
  like_prop: Array<string>;
  /** class定义字段 */
  props: Array<string>;
  /**字段映射:key:DTO接收字段; value:服务查询字段 */
  mapping: object;
  /**
   * 此处将字段转换为使用的方式
   */
  getFilter() {
    const that = cloneDeep(this);
    const others = omit(that, ['like_prop', 'props', 'mapping']);
    let keys = Object.keys(others);
    keys = keys.filter(f => this.props.includes(f));
    const result = {};
    for (const i of keys) {
      const value = this[i];
      if (value === undefined) continue;
      if (this.like_prop.includes(i)) {
        // 处理模糊查询
        const propName = get(this.mapping, i, i);
        result[propName] = new RegExp(value);
      } else if (i.includes('@')) {
        // 处理范围查询
        const arr = i.split('@');
        const prop = head(arr);
        const propName = get(this.mapping, prop, prop);
        const pos = last(arr);
        const pd = get(result, propName, {});
        if (pos === 'start') {
          Object.assign(pd, { $gte: value });
        } else if (pos === 'end') {
          Object.assign(pd, { $lte: value });
        } else continue;
        result[propName] = pd;
      } else if (i.includes('[]')) {
        const arr = i.split('[]');
        const prop = head(arr);
        const propName = get(this.mapping, prop, prop);
        result[propName] = value;
      } else {
        // 正常处理
        const propName = get(this.mapping, i, i);
        result[propName] = value;
      }
    }
    return result;
  }
}
