const backendCode: Service.BackendResultConfig = {
  statusKey: 'status',
  dataKey: 'data',
  msgKey: 'msg',
  successCode: true,
  total: 'total',
  codeKey: 'code'
};

/** 统一失败和成功的请求结果的数据类型 */
export async function handleServiceResult<T = any>(error: Service.RequestError | null, data: any, backend?: any) {
  if (error) {
    const failMsg = error.msg ? error.msg : 'fail';
    const fail: Service.FailedResult = {
      error,
      code: error.code,
      data: backend ? backend[backendCode.dataKey] : null,
      total: backend ? backend[backendCode.total] : 0,
      status: backend ? backend[backendCode.statusKey] : false,
      msg: backend ? backend[backendCode.msgKey] : failMsg
    };
    return fail;
  }
  const success: Service.SuccessResult<T> = {
    error: null,
    data,
    total: backend ? backend[backendCode.total] : 0,
    status: backend ? backend[backendCode.statusKey] : true,
    msg: backend ? backend[backendCode.msgKey] : 'success',
    code: backend ? backend[backendCode.codeKey] : 200
  };
  return success;
}

/** 请求结果的适配器：用于接收适配器函数和请求结果 */
export function adapter<T extends Service.ServiceAdapter>(
  adapterFun: T,
  ...args: Service.MultiRequestResult<Parameters<T>>
): Service.RequestResult<ReturnType<T>> {
  let result: Service.RequestResult | undefined;

  const hasError = args.some(item => {
    const flag = Boolean(item.status === false);
    if (flag) {
      result = {
        error: item.error,
        data: item.data,
        total: null,
        status: false,
        code: item.code,
        msg: item.msg
      };
    }
    return flag;
  });

  if (!hasError) {
    const adapterFunArgs = args.map(item => item.data);
    const adapterFunArgss = args.map(item => item.total);
    result = {
      error: null,
      data: adapterFun(...adapterFunArgs),
      total: adapterFun(...adapterFunArgss),
      status: true,
      msg: 'success',
      code: 200
    };
  }

  return result!;
}
