
/**
 * 这里写的是业务相关的：
 * * 请求数据处理函数。
 * * 自定义请求模块。
 * * 自定义错误报告处理函数。
 */

import AppCofig, { isDev } from "../common/config/AppCofig";
import { RequestSharedData } from "@/api/RequestSharedData";
import ApiCofig from "@/common/config/ApiCofig";
import implementer from "@imengyu/imengyu-utils/dist/request/implementer/WebFetch";
import { 
  RequestApiError, RequestApiResult, type RequestApiErrorType, 
  RequestCoreInstance, RequestOptions, 
  defaultResponseDataGetErrorInfo, defaultResponseDataHandlerCatch, 
  RequestResponse
} from "@imengyu/imengyu-utils/dist/request";
import { appendGetUrlParams, appendPostParams } from "@imengyu/imengyu-utils/dist/request/utils/Utils";
import type { DataModel, NewDataModel } from "@imengyu/js-request-transform";import Swal from 'sweetalert2';
import { StringUtils } from "@imengyu/imengyu-utils";

/**
 * 不报告错误的 code
 */
const notReportErrorCode = [401] as number[];
const notReportMessages = [
  /请授权绑定手机号/g,
] as RegExp[];
function matchNotReportMessage(str: string) {
  for (let i = 0; i < notReportMessages.length; i++) {
    if (notReportMessages[i].test(str))
      return true;
  }
  return false;
}

//请求拦截器
function requestInceptor(url: string, req: RequestOptions) {
  //获取store中的token，追加到头;
    
  const token = RequestSharedData.get('token') ?? '';
  const userId = RequestSharedData.get('userId') ?? '';
  if (StringUtils.isNullOrEmpty((req.header as any).token as string)) {
    req.header['token'] = token
    req.header['__token__'] = token;
  }
  const main_body_user_id = userId ?? '';
  const append_main_body_user_id = !(url.includes('content/content'));

  if (req.method == 'GET') {
    //追加GET参数
    url = appendGetUrlParams(url, 'main_body_id', ApiCofig.mainBodyId);
    if (append_main_body_user_id)
      url = appendGetUrlParams(url, 'main_body_user_id', main_body_user_id);
  } else {
    req.data = appendPostParams(req.data,'main_body_id', ApiCofig.mainBodyId);
    if (append_main_body_user_id)
      req.data = appendPostParams(req.data,'main_body_user_id', main_body_user_id);
  } 
  return { newUrl: url, newReq: req };
}
//响应数据处理函数
function responseDataHandler<T extends DataModel>(response: RequestResponse, req: RequestOptions, resultModelClass: NewDataModel|undefined, instance: RequestCoreInstance<T>, apiName: string | undefined): Promise<RequestApiResult<T>> {
  return new Promise<RequestApiResult<T>>((resolve, reject) => {
    const method = req.method || 'GET';
    response.json().then((json) => {
      if (response.ok) {
        if (!json) {
          reject(new RequestApiError(
            'businessError',
            '后端未返回数据',
            '',
            response.status,
            null,
            null,
            req,
            apiName,
            response.url
          ));
          return;
        }

        //code == 0 错误
        if (json.code === 0) {
          handleError();
          return;
        }

        //处理后端的数据
        let message = '未知错误';
        let data = {} as any;

        //后端返回格式不统一，所以在这里处理格式
        if (typeof json.data === 'object') {
          data = json.data;
          message = json.data?.msg || response.statusText;
        }
        else {
          //否则返回上层对象
          data = json;
          message = json.msg || response.statusText;
        }

        resolve(new RequestApiResult(
          resultModelClass ?? instance.config.modelClassCreator,
          json?.code || response.status,
          message,
          data,
          json
        ));
      }
      else {
        handleError();
      }

      function handleError() {
        let errType : RequestApiErrorType = 'unknow';
        let errString = '';
        let errCodeStr = '';

        if (typeof json.message === 'string') 
          errString = json.message;
        if (typeof json.msg === 'string') 
          errString += json.msg;

        if (StringUtils.isStringAllEnglish(errString))
          errString = '服务器返回：' + errString;

        //错误处理
        if (errString) {
          //如果后端有返回错误信息，则收集错误信息并返回
          errType = 'businessError';
          if (typeof json.data === 'object' && json.data?.errmsg) {
            errString += '\n' + json.data.errmsg;
          }
          if (typeof json.errors === 'object') {
            for (const key in json.errors) {
              if (Object.prototype.hasOwnProperty.call(json.errors, key)) {
                errString += '\n' + json.errors[key];
              }
            }
          }
        } else {
          const res = defaultResponseDataGetErrorInfo(response, json);
          errType = res.errType;
          errString = res.errString;
          errCodeStr = res.errCodeStr;
        }

        reject(new RequestApiError(
          errType,
          errString,
          errCodeStr,
          response.status,
          null,
          null,
          req,
          apiName,
          response.url
        ));
      }
    }).catch((err) => {
      //错误统一处理
      defaultResponseDataHandlerCatch(method, req, response, null, err, apiName, response.url, reject, instance);
    });
  });
}
//错误报告处理
function responseErrReoprtInceptor<T extends DataModel>(instance: RequestCoreInstance<T>, response: RequestApiError) {
  return (
    (response.errorType !== 'businessError' && response.errorType !== 'networkError') ||
    notReportErrorCode.indexOf(response.code) >= 0 ||
    matchNotReportMessage(response.errorMessage) === true
  );
}

//错误报告处理
export function reportError<T extends DataModel>(instance: RequestCoreInstance<T>, response: RequestApiError | Error) {
  if (isDev) {
    if (response instanceof RequestApiError) {
      Swal.fire({
        icon: 'error',
        title: `请求错误 ${response.apiName} : ${response.errorMessage}`,
        text: response.toString() +
          '\r\n请求接口：' + response.apiName +
          '\r\n请求地址：' + response.apiUrl +
          '\r\n请求参数：' + JSON.stringify(response.rawRequest) +
          '\r\n返回参数：' + JSON.stringify(response.rawData) +
          '\r\n状态码：' + response.code +
          '\r\n信息：' + response.errorCodeMessage,
      });
    } else {
      Swal.fire({
        icon: 'error',
        title: '错误报告 代码错误',
        text: response?.stack || ('' + response),
      });
    }
  } else {    
    let errMsg = '';
    if (response instanceof RequestApiError)
      errMsg = response.errorMessage + '。';
      
    errMsg += '服务出现了异常，请稍后重试或联系客服。';
    errMsg += '版本：' + AppCofig.version;

    Swal.fire({
      title: '抱歉',
      icon: 'error',
      text: errMsg
    });
}
}

export class HuliRequestModule<T extends DataModel> extends RequestCoreInstance<T> {
  constructor() {
    super(implementer);
    this.config.baseUrl = 'https://huli-app.wenlvti.net';
    this.config.errCodes = []; //
    this.config.requestInceptor = requestInceptor;
    this.config.responseDataHandler = responseDataHandler;
    this.config.responseErrReoprtInceptor = responseErrReoprtInceptor;
    this.config.reportError = reportError;
  }
}
export class AppServerRequestModule<T extends DataModel> extends RequestCoreInstance<T> {
  constructor() {
    super(implementer);
    this.config.baseUrl = ApiCofig.serverProd;
    this.config.errCodes = []; //
    this.config.requestInceptor = requestInceptor;
    this.config.responseDataHandler = responseDataHandler;
    this.config.responseErrReoprtInceptor = responseErrReoprtInceptor;
    this.config.reportError = reportError;
  }
}
