import { http } from '@kit.NetworkKit';
import { authStore } from './auth';
import { promptAction, router } from '@kit.ArkUI';
import { BusinessError } from '@ohos.base';
import { logger } from './logger';
import { HashMap } from '@kit.ArkTS';
import { CryptoJS } from '@ohos/crypto-js'
import { Base64Util } from './Base64Util';
import { ChangeUtil } from './ChangeUtil'

interface HdRequestOptions {
  baseURL?: string
}

type HdParams = Record<string, string | number | boolean>

export interface HdResponse<T> {
  code: number
  message: string
  data: T
}
export interface TimestampBean {
 timestamp:string


}
class HdHttp {
  baseURL: string

  constructor(options: HdRequestOptions) {
    this.baseURL = options.baseURL || ''
  }

  private request1<T>(path: string, method: http.RequestMethod = http.RequestMethod.GET, extraDatas:HashMap<string, string>) {
    const httpInstance = http.createHttp()
    let fullUrl = this.baseURL + path
    let promise = httpInstance.request(
      // 请求url地址
      fullUrl,
      {
        // 请求方式
        method: http.RequestMethod.POST,
        // 可选，默认为60s
        connectTimeout: 60000,
        // 可选，默认为60s
        readTimeout: 60000,
        // 开发者根据自身业务需要添加header字段
        header: {
          'Content-Type': 'application/json',
          'sign':this.getSign(extraDatas)
        },
        extraData:ChangeUtil.map2Json(extraDatas)
      });
    logger.info('Response JSON.stringify(extraDatas)' + ChangeUtil.map2Json(extraDatas))
   return promise.then((data) => {
     logger.info('Response request:' + data.result);
      if (data.result) {
        const result = data.result as HdResponse<T>
        logger.info('Response result:' + result);
          return result

      }
      return Promise.reject(data.result)
      // if (data.responseCode === http.ResponseCode.OK) {
      //   console.info('Response request:' + data.result);
      //
      // }
      // else
      // {
      //
      // }
      // return Promise.reject(data.result)
    }

    ).catch((err:BusinessError) => {
     logger.info('Response httpReq request:' + JSON.stringify(err));
      return Promise.reject(err)

    }).finally(() => {
        httpInstance.destroy()
      })

  }
  private request<T>(path: string, method: http.RequestMethod = http.RequestMethod.POST, extraDatas :HashMap<string, string>) {
    const httpInstance = http.createHttp()

    const options: http.HttpRequestOptions = {
      method: http.RequestMethod.POST,
      // 可选，默认为60s
      connectTimeout: 60000,
      // 可选，默认为60s
      readTimeout: 60000,
      // 开发者根据自身业务需要添加header字段
      header: {
        'Content-Type': 'application/json',
        'sign':this.getSign(extraDatas)
      },
      extraData:ChangeUtil.map2Json(extraDatas)
    }

    let fullUrl = this.baseURL + path


    return httpInstance.request(fullUrl, options).then((res) => {
      logger.info('Response fullUrl:' +fullUrl+ res.result);
      const result = res.result as HdResponse<T>
      return result
    }).catch((err: BusinessError) => {
      logger.info(fullUrl+`Response succeeded: ${err}`);
      promptAction.showToast({ message: err.message || '网络错误' })
      return Promise.reject(err)
    }).finally(() => {
      httpInstance.destroy()
    })
  }


  private requestafter<T>(path: string, method: http.RequestMethod = http.RequestMethod.GET, extraData?: Object) {
    const httpInstance = http.createHttp()

    const options: http.HttpRequestOptions = {
      method: http.RequestMethod.GET,
      // 可选，默认为60s
      connectTimeout: 60000,
      // 可选，默认为60s
      readTimeout: 60000,
      // 开发者根据自身业务需要添加header字段
      header: {
        'Content-Type': 'application/json'
      }
    }

    let fullUrl = this.baseURL + path
    if (method === http.RequestMethod.GET && extraData) {
      const strArr = Object.keys(extraData)
        .filter(key => (extraData as HdParams)[key] !== undefined)
        .map(key => `${key}=${(extraData as HdParams)[key]}`)
      fullUrl += `?${strArr.join('&')}`
    } else {
      options.extraData = extraData
    }

    return httpInstance.request(fullUrl, options).then((res) => {
      return Promise.reject(res.result)
    }).catch((err: BusinessError) => {
      logger.error(fullUrl+`Response succeeded: ${err}+${err.name}+${err.message}+${err.data}+${err.stack}`);
      // logger.error(fullUrl, err.code?.toString(), err.message)
      promptAction.showToast({ message: err.message || '网络错误' })
      return Promise.reject(err)
    }).finally(() => {
      httpInstance.destroy()
    })
  }


  get<T>(url: string, data?: Object): Promise<HdResponse<T>> {
    return this.requestafter<T>(url, http.RequestMethod.GET, data)
  }

  post<T>(url: string, data?: Object): Promise<HdResponse<T>> {
    return this.requestafter<T>(url, http.RequestMethod.POST, data)
  }

  put<T>(url: string, data?: Object): Promise<HdResponse<T>> {
    return this.requestafter<T>(url, http.RequestMethod.PUT, data)
  }

  delete<T>(url: string, data?: Object): Promise<HdResponse<T>> {
    return this.requestafter<T>(url, http.RequestMethod.DELETE, data)
  }
  posts<T>(url: string, data: HashMap<string, string>): Promise<HdResponse<T>> {
    return this.request<T>(url, http.RequestMethod.POST, data)
  }
  httpReq<T>(url: string, datas: HashMap<string, string>): Promise<HdResponse<T>> {

    // 创建httpRequest对象。
    let httpRequest = http.createHttp();
    let url1 = "https://dev-app.igandan.com/app/manager/getSystemTimeStamp";
    let promise = httpRequest.request(
      // 请求url地址
      url1,
      {
        // 请求方式
        method: http.RequestMethod.GET,
        // 可选，默认为60s
        connectTimeout: 60000,
        // 可选，默认为60s
        readTimeout: 60000,
        // 开发者根据自身业务需要添加header字段
        header: {
          'Content-Type': 'application/json'
        }
      });
    // 处理响应结果。
    return promise.then((data) => {
      if (data.responseCode === http.ResponseCode.OK) {
        logger.info('Response httpReq:' + data.result);
        let json:TimestampBean = JSON.parse(data.result.toString()) as TimestampBean;
            let tp = json.timestamp;
        datas.set("user_uuid", '');
        datas.set("client_type", 'A');
        datas.set("version",'4.0.0' );
        datas.set('timestamp',tp+'');

        return this.posts<T>(url, datas);
      }
      else
      {
        return this.posts<T>(url, datas);
      }
    }

    ).catch((err:BusinessError) => {
      logger.info('Response httpReq error:' + JSON.stringify(err));
      return Promise.reject(err);

    }).finally(() => {
      httpRequest.destroy()
    })

  }
  httpReqSimply<T>(url: string) {

    // 创建httpRequest对象。
    let httpRequest = http.createHttp();

    let promise = httpRequest.request(
      // 请求url地址
      url,
      {
        // 请求方式
        method: http.RequestMethod.POST,
        // 可选，默认为60s
        connectTimeout: 60000,
        // 可选，默认为60s
        readTimeout: 60000,
        // 开发者根据自身业务需要添加header字段
        header: {
          'Content-Type': 'application/json'
        }
      });
    // 处理响应结果。
    return promise.then((data) => {
      logger.info('Response httpReqSimply:' + JSON.stringify(data));
      const result = data.result as HdResponse<T>
      return result
    }

    ).catch((err:BusinessError) => {
      logger.info('Response httpReq error:' + JSON.stringify(err));
      return Promise.reject(err);

    }).finally(() => {
      httpRequest.destroy()
    })

  }
  getSign(extraDatas1:HashMap<string, string>): string {
    let secret= extraDatas1.get("timestamp")
    if(secret!=null) {
      let keyValueStr: string = "";
      let entriesArray: Array<string> = Array.from(extraDatas1.keys());
      entriesArray.sort();

      let sortedMap:HashMap<string, string>  = new HashMap();
      entriesArray.forEach((value: string, index: number) => {
        sortedMap.set(value,extraDatas1.get(value));
        keyValueStr +=value+extraDatas1.get(value)
      });
      keyValueStr = keyValueStr.replace(" ", "");
      keyValueStr = keyValueStr + CryptoJS.MD5(secret).toString();
      let Md5keyValueStr: string = CryptoJS.MD5(keyValueStr).toString();
      let base64Str:string=Base64Util.encodeToStrSync(Md5keyValueStr);
      return base64Str;
    }
    else
    {
      return '';
    }


}
}

export const hdHttp = new HdHttp({ baseURL: '' })




