import moment from 'moment';

/**
 * 在reducer中继续请求异步action
 */
export const asyncAction = action => {
  return dispatch => {
    action && dispatch(action());
  };
};

/**
 * 过滤reducer中的数据
 */
export const filterPayload = payload => {
  if (payload !== null && typeof payload === 'object') {
    return payload.dataList ? payload.dataList : payload;
  }
  return payload;
};

/**
 * 构建表格过滤条件
 * @param {any} filterOpts: [{name: 'orgName', type: 'LIKE'}]
 * @param {any} values
 */
export const generateTableFilter = (filterOpts, values) => {
  let result = [];
  filterOpts.map(f => {
    let type = f.type;
    let name = f.name;
    let value = values[name];
    if (value !== undefined && value !== '' && value !== null) {
      result.push({ name, type, value });
    }
  });
  return result;
};

/**
 * 构建树行数据
 * @param {any} varOpts: [{oldKey: 'text', newKey: 'title'},{oldKey: 'id', newKey: 'key'}]要添加的属性
 * @param {array} treeData 树形原始数据
 */
export const convertTree = (treeData = [], varOpts = []) => {
  const loop = data =>
    data.map(item => {
      varOpts.map(e => {
        item[e.newKey] = item[e.oldKey];
      });
      if (item.children) {
        loop(item.children);
      }
    });
  loop(treeData);
  return treeData;
};

/**
 * 构建表格过滤条件(多个模糊匹配)
 * @param {any} filterOpts: [{name: 'orgName', type: 'LIKE'},{name: 'StoreName', type: 'LIKE'}]
 * @param {any} values
 */
export const generateTableFilterOrLike = (filterOpts, values) => {
  let result = [];
  filterOpts.map(f => {
    let type = f.type;
    let name = f.name;
    let value = values['multipleLike'];
    if (value !== undefined) {
      result.push({ name, type, value });
    }
  });
  return result;
};

/**
 * 检测对象是否是空对象(不包含任何可枚举属性)。
 * 方法只既检测对象本身的属性，不检测从原型继承的属性。
 * @param {object} obj
 */
export const isEmptyObject = obj => {
  if (obj) {
    for (let key in obj) {
      if (key) {
        return false;
      }
    }
  }
  return true;
};

/**
 * 将所有的undefined设置为默认值
 * @param {object} any 目标数据 array、object、string
 * @param {object} val 默认值
 */
export const undefined2default = (any, val) => {
  if (Array.isArray(any)) {
    //
  }
};

/**
 * 格式化时间
 * @param {any} text
 * @param {any} record
 */
export const renderSimpleTime = (text, record) => (text ? moment(text).format('YYYY-MM-DD') : '');

/**
 * 格式化时间
 * @param {any} text
 * @param {any} record
 */
export const renderLongTime = (text, record) => (text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : '');
