import { 
  DATA_MODEL_ERROR_REQUIRED_KEY_MISSING, 
  DATA_MODEL_ERROR_TRY_CONVERT_BAD_TYPE, 
  DATA_MODEL_ERROR_PRINT_SOURCE,
  DATA_MODEL_ERROR_ARRAY_REQUIRED_KEY_MISSING,
  DATA_MODEL_ERROR_ARRAY_IS_NOT_ARRAY,
  DATA_MODEL_ERROR_MUST_PROVIDE_SIDE,
  DATA_MODEL_ERROR_REQUIRED_KEY_NULL,
  DataConverter, 
  DataErrorFormatUtils, 
  defaultDataErrorFormatHandler 
} from "@imengyu/js-request-transform";

function setErrorFormatter() {
  DataErrorFormatUtils.setFormatHandler((error, data) => {
    switch (error) {
      case DATA_MODEL_ERROR_REQUIRED_KEY_MISSING: 
        return `字段 ${data.sourceKey} 必填但未提供。 来源 ${data.source}; 对象 ${data.objectName} ${data.serverKey ? ('服务器应传字段: ' + data.serverKey) : ''}`;
      case DATA_MODEL_ERROR_TRY_CONVERT_BAD_TYPE:
        return `尝试将 ${data.sourceType} 转换为 ${data.targetType}。`;   
      case DATA_MODEL_ERROR_PRINT_SOURCE:
        return `来源: ${data.objectName}.`;
      case DATA_MODEL_ERROR_ARRAY_REQUIRED_KEY_MISSING:
        return `转换数组模型失败: 需要的字段 ${data.sourceKey} 未提供。`
      case DATA_MODEL_ERROR_ARRAY_IS_NOT_ARRAY:
        return `转换数组模型失败: 需要的字段 ${data.sourceKey} 不是数组类型。`
      case DATA_MODEL_ERROR_MUST_PROVIDE_SIDE:
        return `转换字段 ${data.key} 失败: 必须提供 ${data.direction} 侧数据。`;
      case DATA_MODEL_ERROR_REQUIRED_KEY_NULL:
        return `转换字段 ${data.key} 失败: 必填字段 ${data.key} 未提供或者为 null。`;
    }
    return defaultDataErrorFormatHandler(error, data);
  });
}

export function registryConvert() {
  setErrorFormatter();
  DataConverter.registerConverter({
    key: 'SplitCommaArray',
    targetType: 'splitCommaArray',
    converter: (source, key, type) => {
      if (typeof source === 'string') {
        if (source === '') 
          return { success: true, result: [] }
        return {
          success: true,
          result: source?.split(',') || [],
        }
      }
      return {
        success: false,
        convertFailMessage: `[${key}] 不是字符串类型`,
      };
    }
  })
  DataConverter.registerConverter({
    key: 'ArrayNumber',
    targetType: 'arrayInt',
    converter: (source, key, type) => {
      if (source instanceof Array) {
        const result = source.map((p) => {
          if (typeof p === 'number') return p;
          return parseInt(p);
        });
        return {
          success: true,
          result,
        }
      }
      return {
        success: false,
        convertFailMessage: `[${key}] 不是数组类型`,
      };
    }
  })
  DataConverter.registerConverter({
    key: 'CommaArrayMerge',
    targetType: 'commaArrayMerge',
    converter: (source, key, type) => {
      if (source instanceof Array) 
        return {
          success: true,
          result: source?.join(',') || '',
        }
      return {
        success: false,
        convertFailMessage: `[${key}] 不是数组类型`,
      };
    }
  })
}