import moment from 'moment';
// import { FormItemMap } from '../detail/displayComp';
import { createFunc } from '../../utils/JSExecutor';

const numeral = require('numeral');

const isNeedTransForm = type => {
  return type === 'SELECT'
    || type === 'CHECKBOXGROUP'
    || type === 'CHECKBOX'
    || type === 'RADIO'
    || type === 'RADIOGROUP';
};

export const arr2obj = (array, key) =>
  array.reduce((result, item) => {
    result[item[key]] = item;
    return result;
  }, {});

export const handleFilterItems = (filterItems, fieldsObject) =>
  filterItems.map(filter => {
    // const fieldData = data.fields.find(field => field.name === filter.name);
    const fieldData = fieldsObject[filter.name];
    if (fieldData) {
      return {
        ...filter,
        type: fieldData.displayComponent.componentType,
        extra: fieldData.displayComponent.dictionaryItems,
        dataType: fieldData.type,
      };
    }
    return filter;
  });

export const handleOrderItems = orderItems => {
  const orderFields = {};
  if (orderItems && orderItems.length > 0) {
    orderItems.forEach(item => {
      // const temp = {
      //   orderField: item.name,
      //   orderType: item.isAsc ? 'Asc' : 'Desc'
      // };
      orderFields[item.name] = item;
    });
  }
  return orderFields;
};

export const renderColumn = (text, fieldContent, record) => {
  let ret = text;
  if (!fieldContent) {
    ret = '';
  } else if (isNeedTransForm(fieldContent.displayComponent.componentType)) {
    const valueList = (text && text.split(',')) || [];
    const dictItem = fieldContent.displayComponent.dictionaryItems
      .filter(dict => valueList.indexOf(dict.code) >= 0);
    ret = (dictItem && dictItem.reduce((res, f) => res + ' ' + f.value, '')) || text;
  } else if (fieldContent.type === 'Date') {
    if (text) {
      ret = moment(new Date(text)).format('YYYY-MM-DD');
    } else {
      ret = '';
    }
  } else if (fieldContent.displayComponent.componentType === 'INPUTNUMBER') {
    const magnitude = fieldContent.displayComponent.magnitude || 1;
    if (text) {
      let isAmountFormat = null;
      fieldContent && fieldContent.formValidates && fieldContent.formValidates.forEach((item, index1) => {
        if (item.validateType === 'ISAMOUNT') {
          isAmountFormat = item.format;
        }
      });
      const format = isAmountFormat || '0,0.0000';
      ret = numeral(text * magnitude).format(format);
    } else {
      ret = text;
    }
    const addOnBefore = fieldContent.displayComponent.addOnBefore;
    if (addOnBefore) {
      if (addOnBefore.indexOf('function') >= 0 && record) {
        ret = createFunc(addOnBefore)(record) + ' ' + ret;
      } else {
        ret = addOnBefore + ' ' + ret;
      }
    }
  } else {
    ret = text;
  }
  return ret;
};
