import axios from 'axios';

// 假设这些类型定义在其他文件中
interface TransitEntity {
  ServiceName: string;
  FuncName: string;
  Parameters: { [key: string]: string };
  AttachFiles: AttachFile[];
}

interface AttachFile {
  AttachIndex: string;
  AttachType: string;
  AttachValue: any;
}

interface TradeForms {}
interface TradePrintMessage {}
interface TPrintData {
  Formdata: any;
  FormdataLength: number;
}

// 假设 ServiceManager 类的 Commit 方法对应一个 HTTP 请求
const ServiceManager = {
  GetInstance: () => ({
    Commit: async (entity: TransitEntity) => {
      try {
        const response = await axios.post('/api/print-service', entity);
        return response.data;
      } catch (error) {
        throw error;
      }
    },
  }),
};

// 假设 CommonFunction 类的方法已经实现
class CommonFunction {
  static ChangeEntityToTable(entity: any) {
    // 实现实体到 DataTable 的转换逻辑
    return null;
  }

  static ChangeTableToEntitys<T>(table: any): T[] {
    // 实现 DataTable 到实体数组的转换逻辑
    return [];
  }
}

// 假设 PlatformLogger 类的方法已经实现
class PlatformLogger {
  static SystemErrorInfo(message: string, error: any) {
    console.error(message, error);
  }
}

export class PrintHandle {
  static async AddTradeForm(tradeid: string, tradeform: TradeForms[]): Promise<boolean> {
    try {
      const entity: TransitEntity = {
        ServiceName: 'PrintService',
        FuncName: 'AddTradeForm',
        Parameters: { '1': tradeid },
        AttachFiles: [],
      };

      const data: AttachFile = {
        AttachIndex: '2',
        AttachType: 'TableType',
        AttachValue: CommonFunction.ChangeEntityToTable(tradeform),
      };
      entity.AttachFiles.push(data);

      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        return Boolean(tmpresult[0].AttachValue);
      }
      return false;
    } catch (e) {
      PlatformLogger.SystemErrorInfo('AddTradeForm方法出现异常：', e);
      throw e;
    }
  }

  static async GetTradePrintMessage(tradeno: string, tradename: string): Promise<TradePrintMessage[]> {
    try {
      const entity: TransitEntity = {
        ServiceName: 'PrintService',
        FuncName: 'GetTradePrintMessage',
        Parameters: { '1': tradeno, '2': tradename },
        AttachFiles: [],
      };

      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        return CommonFunction.ChangeTableToEntitys<TradePrintMessage>(tmpresult[0].AttachValue);
      }
      return [];
    } catch (e) {
      PlatformLogger.SystemErrorInfo('GetTradePrintMessage方法出现异常：', e);
      throw e;
    }
  }

  static async GetTradeFormsByTradecode(tradecode: string): Promise<TradeForms[]> {
    try {
      const entity: TransitEntity = {
        ServiceName: 'PrintService',
        FuncName: 'GetTradeFormsByTradecode',
        Parameters: { '1': tradecode },
        AttachFiles: [],
      };

      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        return CommonFunction.ChangeTableToEntitys<TradeForms>(tmpresult[0].AttachValue);
      }
      return [];
    } catch (e) {
      PlatformLogger.SystemErrorInfo('GetTradeFormsByTradecode方法出现异常：', e);
      throw e;
    }
  }

  static async AddPrintData(printdata: TPrintData): Promise<string> {
    try {
      const entity: TransitEntity = {
        ServiceName: 'PrintService',
        FuncName: 'AddPrintData',
        Parameters: {},
        AttachFiles: [],
      };

      const attcheds: AttachFile = {
        AttachIndex: '1',
        AttachType: 'TableType',
        AttachValue: CommonFunction.ChangeEntityToTable([printdata]),
      };
      entity.AttachFiles.push(attcheds);

      const attcheds2: AttachFile = {
        AttachIndex: '2',
        AttachType: 'ByteType',
        AttachValue: printdata.Formdata,
      };
      entity.AttachFiles.push(attcheds2);

      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        return tmpresult[0].AttachValue as string;
      }
      return null;
    } catch (e) {
      PlatformLogger.SystemErrorInfo('AddPrintData方法出现异常：', e);
      throw e;
    }
  }

  static async GetPrintDataByBusinessId(businessId: string): Promise<TPrintData[]> {
    try {
      const entity: TransitEntity = {
        ServiceName: 'PrintService',
        FuncName: 'GetPrintDataByBusinessId',
        Parameters: { '1': businessId },
        AttachFiles: [],
      };

      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 2) {
        const result = CommonFunction.ChangeTableToEntitys<TPrintData>(tmpresult[0].AttachValue);
        let i = 0;
        if (result) {
          result.forEach((tmp) => {
            tmp.Formdata = new Uint8Array(tmp.FormdataLength);
            tmp.Formdata.set(tmpresult[1].AttachValue.slice(i, i + tmp.FormdataLength));
            i += tmp.FormdataLength;
          });
        }
        return result;
      }
      return [];
    } catch (e) {
      PlatformLogger.SystemErrorInfo('GetPrintDataByBusinessId方法出现异常：', e);
      throw e;
    }
  }

  static async GetFormPrintedCount(id: string): Promise<number> {
    try {
      const entity: TransitEntity = {
        ServiceName: 'PrintService',
        FuncName: 'GetFormPrintedCount',
        Parameters: { '1': id },
        AttachFiles: [],
      };

      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        return Number(tmpresult[0].AttachValue);
      }
      return 0;
    } catch (e) {
      PlatformLogger.SystemErrorInfo('GetFormPrintedCount方法出现异常：', e);
      throw e;
    }
  }

  static async AddPrintHistory(pdid: string, worker: string, author: string): Promise<boolean> {
    try {
      const entity: TransitEntity = {
        ServiceName: 'PrintService',
        FuncName: 'AddPrintHistory',
        Parameters: { '1': pdid, '2': worker, '3': author },
        AttachFiles: [],
      };

      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        return Boolean(tmpresult[0].AttachValue);
      }
      return false;
    } catch (e) {
      PlatformLogger.SystemErrorInfo('AddPrintHistory方法出现异常：', e);
      throw e;
    }
  }
}