const sm4 = require('../js/SM4');
const SM4Exten = require('../js/SM4Exten');
const miniprogramsm4 = require("../miniprogram_npm/miniprogram-sm-crypto/index").sm4;
const secretId = "D2BCF8DE-AA24-4BF6-9C34-C8DD325E412B"; //小程序应用ID
const Secret = "6C680A47B87740138DFB299FC69A64E1"; //小程序应用密钥
const api_root = 'https://www.hsfuel.com/'
// const api_root = 'http://47.97.120.160:5007/'
// const api_root = 'http://172.31.2.202:5006/'
// const api_root = 'http://192.168.0.202:5006/'
const CurrentBuId = '12345678-9abc-def0-1234-56789abcdef0';

function request(path, method = 'GET', data = null) {
  var WachatID = wx.getStorageSync('WachatID')
  return new Promise((resolve, reject) => {
    var sign_method = "HMAC_SM4";
    var url = api_root + path;
    var nonce = generateRandomString();
    const timestamp = Date.now();
    console.log('data :' + JSON.stringify(data));
    let jsonString = (data != null && method != 'GET') ? JSON.stringify(data) : '';
    console.log('request :' + jsonString);
    var stringToSign = "sign_method=" + sign_method +
      "&secret_id=" + secretId +
      "&nonce=" + nonce +
      "&timestamp=" + timestamp;
    if (jsonString != '') {
      stringToSign += "&" + jsonString
    }
    const resultArray = path.split('?');
    if (resultArray.length == 2) {
      stringToSign += "&" + resultArray[1]
    }
    console.log('加密串 :' + stringToSign);
    if(path == 'api/Site/GetSiteInfo') console.log('获取站点信息加密串 :' + stringToSign);
    let key = stringToHex(Secret); //key转16进制
    key = getFirst32Chars(key); //截取前16位
    let signature = miniprogramsm4.encrypt(stringToSign, key) //sm4加密
    //signature = signature.toUpperCase();
    signature = stringToBase64(signature); //加密字符串转base64
    console.log('signature :' + signature);
    wx.request({
      header: {
        "sign_method": sign_method,
        "secret_id": secretId,
        "nonce": nonce,
        "timestamp": timestamp,
        "signature": signature,
        "CurrentBuId": CurrentBuId,
        "WachatID": WachatID
      },
      url: url,
      method: method,
      data: data,
      success: res => {
        console.log("success");
        resolve(res);
      },
      fail: res => {
        console.log("request fail");
        resolve(res);
      },
    })

  });

}
//字符串转base64
function stringToBase64(str) {
  // 定义Base64字符集
  const base64Chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';

  // 将字符串转换为UTF-8字节数组
  let utf8Bytes = [];
  for (let i = 0; i < str.length; i++) {
    let charCode = str.charCodeAt(i);

    if (charCode < 128) { // 1字节字符
      utf8Bytes.push(charCode);
    } else if (charCode < 2048) { // 2字节字符
      utf8Bytes.push((charCode >> 6) | 192);
      utf8Bytes.push((charCode & 63) | 128);
    } else if (charCode < 65536) { // 3字节字符
      utf8Bytes.push((charCode >> 12) | 224);
      utf8Bytes.push(((charCode >> 6) & 63) | 128);
      utf8Bytes.push((charCode & 63) | 128);
    } else { // 4字节字符
      utf8Bytes.push((charCode >> 18) | 240);
      utf8Bytes.push(((charCode >> 12) & 63) | 128);
      utf8Bytes.push(((charCode >> 6) & 63) | 128);
      utf8Bytes.push((charCode & 63) | 128);
    }
  }

  let base64Str = '';
  let paddingCount = 0;

  // 处理每3个字节（24位），转换为4个Base64字符
  for (let i = 0; i < utf8Bytes.length; i += 3) {
    let byte1 = utf8Bytes[i];
    let byte2 = i + 1 < utf8Bytes.length ? utf8Bytes[i + 1] : 0;
    let byte3 = i + 2 < utf8Bytes.length ? utf8Bytes[i + 2] : 0;

    let chunk = (byte1 << 16) | (byte2 << 8) | byte3;

    let char1 = base64Chars[(chunk >> 18) & 63];
    let char2 = base64Chars[(chunk >> 12) & 63];
    let char3 = i + 1 < utf8Bytes.length ? base64Chars[(chunk >> 6) & 63] : '=';
    let char4 = i + 2 < utf8Bytes.length ? base64Chars[chunk & 63] : '=';

    base64Str += char1 + char2 + char3 + char4;

    // 计算需要填充的'='号数量
    if (i + 2 >= utf8Bytes.length) {
      paddingCount = (utf8Bytes.length - i) % 3;
    }
  }

  return base64Str;
}
//截取字符串
function getFirst32Chars(str) {
  if (typeof str !== 'string') {
    throw new Error('Input must be a string');
  }

  // 如果字符串长度小于等于32，则返回整个字符串；否则返回前32个字符
  return str.length <= 32 ? str : str.slice(0, 32);
}

//字符串转16进制
function stringToHex(str) {
  let hex = '';
  for (let i = 0; i < str.length; i++) {
    // 获取字符的字符编码
    const charCode = str.charCodeAt(i);
    // 将字符编码转换为16进制，并确保始终为两位数（不足两位前面补0）
    const hexValue = charCode.toString(16).padStart(2, '0');
    hex += hexValue;
  }
  return hex;
}

function generateRandomString(minLength = 6, maxLength = 10) {
  // 定义字符集
  const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  // 生成随机长度
  const length = Math.floor(Math.random() * (maxLength - minLength + 1)) + minLength;

  let result = '';
  for (let i = 0; i < length; i++) {
    // 随机选择一个字符
    const randomIndex = Math.floor(Math.random() * charset.length);
    result += charset[randomIndex];
  }

  return result;
}

// //获取站点信息
// function request_getSite(data) {
//   return request('api/Nozzle/GetNozzleInfo?Nozzleid='+ data, "GET",data);
// }
//支付
function request_wechatPay(data) {
  return request('api/Transactions/UnifiedOrder?trxid=' + data, "POST", data);
}

//获取站点信息与用户信息
function request_GetSiteInfo() {
  return request('api/Site/GetSiteInfo', "GET");
}

//小程序用户查询未支付订单
function request_GetMiniProgramTransactionsUnpaidQuery(data) {
  return request('api/Transactions/GetMiniProgramTransactionsUnpaidQuery', "GET", data);
}

//小程序用户根据抢号查询未支付订单
function request_GetMiniProgramTransactionsUnpaidNozzle(data) {
  return request('api/Transactions/GetMiniProgramTransactionsUnpaidNozzle?NozzleId=' + data, "GET", data);
}
//小程序登录
function request_Wechatlogin(data) {
  return request('api/Auth/Wechatlogin?code=' + data, "GET", data);
}

//获取历史订单
function request_WXFindOrders(dateTime,pageNum,lineCount) {
  return request('api/Transactions/WXFindOrders?dateTime='+ dateTime + '&pageNum='+ pageNum+ '&lineCount='+ lineCount, "GET");
}

//添加用户信息
function request_AddMiniprogramUser(data) {
  return request('api/Site/AddMiniprogramUser', "POST", data);
}

//向fcc发起油枪授权
function request_NozzleAuthorization(data) {
  return request('api/Nozzle/NozzleAuthorization?trxid=' + data, "GET", data);
}

//向fcc发起取消油枪授权
function request_CancelNozzleAuthorization(data) {
  return request('api/Nozzle/CancelNozzleAuthorization?trxid=' + data, "GET", data);
}
//退款
function request_RefundTrx(data) {
  return request('api/Transactions/RefundTrx', "POST", data);
}

//根据油枪id获取油枪信息
function request_GetNozzleInfo(data) {
  return request('api/Nozzle/GetFuelNozzleInfoById?nozzleid='+data, 'GET', data)
}

//发送消息模板
function request_sendMessage(data) {
  return request('api/Transactions/SendMessage','POST',data)
}

//创建订单
function request_createOrder(data) {
  return request('api/Transactions/CreateTransactions','POST',data)
}
export default {
  request_GetSiteInfo,
  request_wechatPay,
  request_Wechatlogin,
  request_AddMiniprogramUser,
  request_NozzleAuthorization,
  request_CancelNozzleAuthorization,
  request_GetMiniProgramTransactionsUnpaidQuery,
  request_GetMiniProgramTransactionsUnpaidNozzle,
  request_AddMiniprogramUser,
  request_RefundTrx,
  request_GetNozzleInfo,
  request_WXFindOrders,
  request_sendMessage,
  request_createOrder
}