/**
 * 速停车开票接口模块
 */

 import Axios, { AxiosInstance, AxiosResponse } from "axios";
 import { logger } from "mslib";
 import { Container, Singleton } from "typescript-ioc";
 import Contants from "./Contants";
 import { CryptoUtils } from "./CryptoUtils";
 import { throwApiErrorFromAxiosError } from "./Errors";
 
 /**
  * 速停车开票接口客户端
  */
 @Singleton
 export default class StcInvoiceApiClient {
     /**
      * 根据订单号和车场id开票
      * 
      * 接口文档上的同路劲的接口实际上是同路劲的get接口，post的看不到接口文档
      * /ei/service/api/ei/invoice
      * https://ts.keytop.cn/eitest/doc.html#/%E9%BB%98%E8%AE%A4%E6%8E%A5%E5%8F%A3/%E5%8F%91%E7%A5%A8API/invoiceUsingPOST
      * 
      * @param request {@link InvoiceResquest}
      */
     async invoice(url, request: string): Promise<ApiResponse<InvoiceResponse>> {
         let axiosResponse = await axiosInstance.post(url, request);
         return axiosResponse.data;
     }
 
     /**
      * 新江南查票
      * 
      * /ei/service/v1/invoice/open/queryByOrderId
      * 
      * https://ts.keytop.cn/eitest/doc.html#/%E9%BB%98%E8%AE%A4%E6%8E%A5%E5%8F%A3/%E5%8F%91%E7%A5%A8API/queryByOrderIdV1UsingPOST
      */
     async queryByOrderId(url, request: QueryByOrderIdRequest): Promise<ApiResponse<QueryByOrderIdResponse>> {
         let axiosResponse = await axiosInstance.post(url, request);
         return axiosResponse.data;
     }
 }
 
 export class InvoiceResquest {
     lotId: string;
     orderAmount: number;
     requestId: string;
     type: string;
     title: string;
     sn: string;
     phone: string;
     email: string;
     sign: string;
 }
 
 export class InvoiceResponse {
     /**
      * 
      */
     fileUrl?: string;
 
     /**
      * 
      */
     invoiceCode?: string;
 
     /**
      * 
      */
     invoiceNo?: string;
 
     /**
      * 成功=successful
      */
     resultCode?: 'successful' | string;
 
     /**
      * 
      */
     resultMsg?: string;
 
     /**
      * 
      */
     returnCode?: string;
 
     /**
      * 
      */
     returnMsg?: string;
 
     /**
      * 
      */
     sign?: string;
 }
 
 export class QueryByOrderIdRequest {
     /**
      * 外部系统订单号（开票时传入的） ,示例值(MERCOUPON1611815103780)
      */
     orderNo: string;
 
     /**
      * 	开票类型，是否查红票（蓝票false，红票true）
      */
     redInvoice?: boolean
 }
 
 export class QueryByOrderIdResponse {
     /**
      * 开票金额单位：分
      */
     amount?: number;
 
     /**
      * EI号（发票系统订单号）
      */
     eiNo?: string;
 
     /**
      * 发票代码（实际发票上的发票代码）
      */
     invoiceCode?: string;
 
     /**
      * 
      */
     invoiceDate?: string;
 
     /**
      * 发票号码（实际发票上的发票号码）
      */
     invoiceNo?: string;
 
     /**
      * 发票类型00蓝票，01蓝票
      */
     invoiceType?: string;
 
     /**
      * 车场名称
      */
     lotName?: string;
 
     /**
      * 请求ID（外部订单号）
      */
     orderId?: string;
 
     /**
      * 发票url
      */
     pdfUrl?: string;
 
     /**
      * 状态代码（00申请成功、01开票中、02开票成功、03开票失败）
      */
     status?: string;
 
     /**
      * 状态（00申请成功、01开票中、02开票成功、03开票失败）
      */
     statusName?: string;
 }
 
 /**
  * 速停车开票接口响应
  */
 export class ApiResponse<T = any> {
     code: string;
     message: string;
     data: T;
 
     static codeIsSuccess(code: string) {
         return code?.toString() === '2000';
     }
 }
 
 export function throwIfCodeNoSuccess(apiResponse: ApiResponse) {
     if (!ApiResponse.codeIsSuccess(apiResponse.code)) {
         throw new Error(`速停车开票接口返回错误,返回值:${JSON.stringify(apiResponse)}`);
     }
 }
 
 export class SignUtils {
     static sign(data, appKey) {
         let signStr = Object.keys(data).sort().map(k => `${k}=${data[k]}`).join('&') + `&key=${appKey}`;
         return CryptoUtils.md5(signStr).toUpperCase();
     }
 }
 
 function generateAxiosInstance() {
     const axiosInstance = Axios.create({
        //  baseURL: Contants.IS_PROD ? 'https://cloud.keytop.cn/ei' : 'https://ts.keytop.cn/eitest',
         timeout: 10000,
     });
 
     axiosInstance.interceptors.request.use(config => {
         config.headers['Content-Type'] = 'application/json;charset=utf-8';
         return config;
     }, error => {
         throwApiErrorFromAxiosError(error, '速停车开票接口');
     });
 
     axiosInstance.interceptors.response.use(response => {
         logger.info(`速停车开票接口'${response.config['apiDesc'] || response.config.url}'调用成功,请求地址:${response.config.url.startsWith('http') ? response.config.url : response.config.baseURL + response.config.url},请求参数:${response.config.data},返回值:${response.data}`);
 
         return response;
     }, error => {
         throwApiErrorFromAxiosError(error, '速停车开票接口');
     });
 
     return axiosInstance;
 }
 
 export let axiosInstance: AxiosInstance = generateAxiosInstance();
 
 export { StcInvoiceApiClient }