import axios from 'axios';

// 假设这些类型在其他文件中定义
type Transit = string;
type AttachFile = {
  AttachIndex: string;
  AttachType: string;
  AttachValue: any;
};
type TransitEntity = {
  ServiceName: string;
  FuncName: string;
  Parameters: { [key: string]: string };
  AttachFiles: AttachFile[];
};
type TradeInfo = any;
type IsAuthResult = any;
type AuthResult = any;
type AuthCondInf = any;

// 假设 ServiceManager 封装了 HTTP 请求逻辑
class ServiceManager {
  private static instance: ServiceManager;

  private constructor() {}

  public static GetInstance(): ServiceManager {
    if (!this.instance) {
      this.instance = new ServiceManager();
    }
    return this.instance;
  }

  public async Commit(entity: TransitEntity): Promise<AttachFile[]> {
    try {
      const response = await axios.post('/api/service', entity);
      return response.data as AttachFile[];
    } catch (error) {
      throw error;
    }
  }
}

// 假设这些常量和函数在其他文件中定义
const CommonParames = {
  TempFilePath: '',
  Coding: 'utf-8'
};
const FilesHandle = {
  GetFileData: async (filePath: string): Promise<Uint8Array> => {
    try {
      const response = await axios.get(filePath, { responseType: 'arraybuffer' });
      return new Uint8Array(response.data);
    } catch (error) {
      throw error;
    }
  }
};
const CommonFunction = {
  ChangeEntityTable: <TIn, TOut>(input: TIn): TOut => {
    // 这里需要根据实际逻辑实现转换
    return {} as TOut;
  },
  ChangStrToArray: (str: string): string[] => {
    return str.split(',');
  }
};

export class TradeHandle {
  public static async DoTrade(
    transit: Transit,
    integrateData: Uint8Array,
    kinBrno: string,
    fileName: string,
    fileFlag: boolean,
    args: any[]
  ): Promise<Uint8Array | null> {
    let result: Uint8Array | null = null;
    try {
      const entity: TransitEntity = {
        ServiceName: 'TradeService',
        FuncName: 'DoTradeByTransit',
        Parameters: {
          '1': transit.toString(),
          '3': kinBrno,
          '4': fileName,
          '5': fileFlag.toString(),
          '6': ''
        },
        AttachFiles: []
      };
      const data: AttachFile = {
        AttachIndex: '2',
        AttachType: 'ByteType',
        AttachValue: integrateData
      };
      entity.AttachFiles.push(data);
      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        result = tmpresult[0].AttachValue as Uint8Array;
      }
    } catch (error) {
      throw error;
    }
    return result;
  }

  public static async GetTradeFile(fileName: string): Promise<Uint8Array | null> {
    const filePath = CommonParames.TempFilePath + fileName + 'dhcc';
    try {
      return await FilesHandle.GetFileData(filePath);
    } catch (error) {
      throw error;
    }
  }

  public static async ClearvFile(fileName: string): Promise<boolean> {
    const vfileName = CommonParames.TempFilePath + fileName;
    let result = false;
    try {
      const entity: TransitEntity = {
        ServiceName: 'UtilService',
        FuncName: 'SaveFile',
        Parameters: {
          '1': fileName,
          '3': false.toString()
        },
        AttachFiles: []
      };
      const data: AttachFile = {
        AttachIndex: '2',
        AttachType: 'ByteType',
        AttachValue: new Uint8Array()
      };
      entity.AttachFiles.push(data);
      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        result = Boolean(tmpresult[0].AttachValue);
      }
    } catch (error) {
      throw error;
    }
    return result;
  }

  public static async Addvfile(fileName: string, fileContent: string): Promise<boolean> {
    const vfileName = CommonParames.TempFilePath + fileName;
    const data = new TextEncoder().encode(fileContent);
    let result = false;
    try {
      const entity: TransitEntity = {
        ServiceName: 'UtilService',
        FuncName: 'SaveFile',
        Parameters: {
          '1': vfileName,
          '3': true.toString()
        },
        AttachFiles: []
      };
      const attachdata: AttachFile = {
        AttachIndex: '2',
        AttachType: 'ByteType',
        AttachValue: data
      };
      entity.AttachFiles.push(attachdata);
      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        result = Boolean(tmpresult[0].AttachValue);
      }
    } catch (error) {
      throw error;
    }
    return result;
  }

  public static async CheckAuth(inf: TradeInfo): Promise<IsAuthResult | null> {
    let result: IsAuthResult | null = null;
    try {
      const entity: TransitEntity = {
        ServiceName: 'TradeService',
        FuncName: 'CheckAuth',
        Parameters: {},
        AttachFiles: []
      };
      const data: AttachFile = {
        AttachIndex: '1',
        AttachType: 'TableType',
        AttachValue: CommonFunction.ChangeEntityTable<TradeInfo[], any>([inf])
      };
      entity.AttachFiles.push(data);
      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        const rmpresult = CommonFunction.ChangeEntityTable<any, IsAuthResult[]>(
          tmpresult[0].AttachValue as any
        );
        result = rmpresult[0];
      }
    } catch (error) {
      throw error;
    }
    return result;
  }

  public static async DoAuthByAuthno(authno: string): Promise<AuthResult | null> {
    let result: AuthResult | null = null;
    try {
      const entity: TransitEntity = {
        ServiceName: 'TradeService',
        FuncName: 'DoAuthByAuthno',
        Parameters: {
          '1': authno
        },
        AttachFiles: []
      };
      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        const rmpresult = CommonFunction.ChangeEntityTable<any, AuthResult[]>(
          tmpresult[0].AttachValue as any
        );
        result = rmpresult[0];
      }
    } catch (error) {
      throw error;
    }
    return result;
  }

  public static async DoAuthByAuth(
    auth: string,
    pwd: string,
    lvl: string | null,
    records: string
  ): Promise<AuthResult | null> {
    let result: AuthResult | null = null;
    try {
      const entity: TransitEntity = {
        ServiceName: 'TradeService',
        FuncName: 'DoAuthByAuth',
        Parameters: {
          '1': auth,
          '2': pwd,
          '3': lvl || '',
          '4': records
        },
        AttachFiles: []
      };
      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        const rmpresult = CommonFunction.ChangeEntityTable<any, AuthResult[]>(
          tmpresult[0].AttachValue as any
        );
        result = rmpresult[0];
      }
    } catch (error) {
      throw error;
    }
    return result;
  }

  public static async CheckAuthBytxno(txno: string): Promise<number> {
    let result = 0;
    try {
      const entity: TransitEntity = {
        ServiceName: 'TradeService',
        FuncName: 'CheckAuthBytxno',
        Parameters: {
          '1': txno
        },
        AttachFiles: []
      };
      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        result = Number(tmpresult[0].AttachValue);
      }
    } catch (error) {
      throw error;
    }
    return result;
  }

  public static async Getuserlvl(txno: string): Promise<string | null> {
    let result: string | null = null;
    try {
      const entity: TransitEntity = {
        ServiceName: 'TradeService',
        FuncName: 'Getuserlvl',
        Parameters: {
          '1': txno
        },
        AttachFiles: []
      };
      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        result = tmpresult[0].AttachValue as string;
      }
    } catch (error) {
      throw error;
    }
    return result;
  }

  public static async AddAuthCond(
    txcode: string,
    authcondinf: AuthCondInf[]
  ): Promise<boolean> {
    let result = false;
    try {
      const entity: TransitEntity = {
        ServiceName: 'TradeService',
        FuncName: 'AddAuthCond',
        Parameters: {
          '1': txcode
        },
        AttachFiles: []
      };
      const data: AttachFile = {
        AttachIndex: '2',
        AttachType: 'TableType',
        AttachValue: CommonFunction.ChangeEntityTable<AuthCondInf[], any>(authcondinf)
      };
      entity.AttachFiles.push(data);
      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        result = Boolean(tmpresult[0].AttachValue);
      }
    } catch (error) {
      throw error;
    }
    return result;
  }

  public static async GetAuthCondByTradecode(txcode: string): Promise<AuthCondInf[] | null> {
    let result: AuthCondInf[] | null = null;
    try {
      const entity: TransitEntity = {
        ServiceName: 'TradeService',
        FuncName: 'GetAuthCondByTradecode',
        Parameters: {
          '1': txcode
        },
        AttachFiles: []
      };
      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        result = CommonFunction.ChangeEntityTable<any, AuthCondInf[]>(
          tmpresult[0].AttachValue as any
        );
      }
    } catch (error) {
      throw error;
    }
    return result;
  }

  public static async GetAuthLvls(): Promise<string[] | null> {
    let result: string[] | null = null;
    try {
      const entity: TransitEntity = {
        ServiceName: 'TradeService',
        FuncName: 'GetAuthLvls',
        Parameters: {},
        AttachFiles: []
      };
      const tmpresult = await ServiceManager.GetInstance().Commit(entity);
      if (tmpresult && tmpresult.length === 1) {
        result = CommonFunction.ChangStrToArray(tmpresult[0].AttachValue as string);
      }
    } catch (error) {
      throw error;
    }
    return result;
  }
}