import { alertError, alertInfo, getGlobalData } from './index.js';
import { getPageUrl } from './index'
// 普通函数 -> Promise函数
const promisify = (api) => {
  return (options, ...params) => {
      return new Promise((resolve, reject) => {
          api(Object.assign({}, options, { success: resolve, fail: reject }), ...params);
      });
  }
}
// 获取全局变量
const globalData = getGlobalData();  
const { api } = globalData;
const RAW_SERVER = api;
const SERVER = api;
const ok = 200;

const requestWithoutCookie = promisify(wx.request);

// 考虑了Cookie的请求
const request = async function (options, config = {}) {
  console.log('请求地址', options.url, "请求参数", options.data, 'config', config)
  let token = wx.getStorageSync('token');
  const result = wx.getAccountInfoSync();
  const { envVersion } = result.miniProgram;
  options.header = {
    Accept: 'application/json',
    'content-type': 'application/json; charset=utf-8',
    "Authorization": token,
    // "env": "trial",
    "env": envVersion,
    ...config
  };
  let response;
  try {
    response = await requestWithoutCookie(options);
    // 服务器没有返回200直接报错
    if (!response || response.statusCode !== 200) {
      alertError(response?.data?.message || "发生错误，请稍后重试")
      return;
    }
  
    // 处理cookie
    const setCookie = response.header['set-cookie'] || response.header['Set-Cookie'];
    if (setCookie) {
      const cookieMap = {};
      if (localCookieString) {
        const localCookies = localCookieString.split('; ');
        for (const localCookie of localCookies) {
          const matchResult = localCookie.match(/^([^=]+)=(.+)/);
          cookieMap[matchResult[1]] = matchResult[2];
        }
      }
  
      const matchResultSet = setCookie.match(/^([^=]+)=([^;]+);/);
      cookieMap[matchResultSet[1]] = matchResultSet[2];
  
      const cookies = [];
      for (const name in cookieMap) {
        if (!{}.hasOwnProperty.call(cookieMap, name)) {
          continue;
        }
        const value = cookieMap[name];
        cookies.push(`${name}=${value}`);
      }
  
      await setStorage({
        key: 'cookies',
        data: cookies.join('; ')
      });
    }
  } catch(err) {
    alertInfo(err.errMsg)
  }
  return response;
}

// 处理返回结果，默认直接返回数据
const parseResponse = function (response, url) {
  console.log('response', response, url)
  if (!response) {
    wx.redirectTo({
      url: '/pages/login/index',
    })
    wx.clearStorageSync()
    alertError("无响应，请重试")
    return
    
  }
  const { statusCode } = response;
  if (!statusCode) {
    alertError("服务错误")
    return
  }
  if (code === 401) {
    const currentUrl = getPageUrl()
    
    if (!['pages/home/index', 'pages/login/index'].includes(currentUrl)) {
      wx.redirectTo({
        url: '/pages/login/index',
      })
    }
    wx.clearStorageSync()
    return { code: 401, message: '未登录状态' }
  }
  if (code === 403) {
    return { code: 403, message: "非法访问" }
  }
  if (code === 404) {
    wx.redirectTo({
      url: '/pages/login/index',
    })
    wx.clearStorageSync()
    return { code: 404, message: "服务不存在" }
  }
  if (500 <= code && code < 600) {
    return { code: 500, message: "服务错误" }
  }
  const { code } = response?.data || {};

  return response.data;
}

// GET请求
const GET = async function (uri) {
  const response = await request({
    url: `${SERVER}${uri}`,
    method: 'GET',
  
  });

  return parseResponse(response, uri);
};

// 创建、更新和删除请求
const CUD = async function (method, uri, data = null) {
  // 没有CSRF Token就前往获取
  // 请求参数
  const options = {
    url: `${SERVER}${uri}`,
    method,
  };
  if (data) {
    options.data = data;
  }
  const response = await request(options);
  return parseResponse(response);
};

// 创建请求
const POST = async function (uri, data) {
  return await CUD('POST', uri, data);
}

// 修改请求
const PUT = async function (uri, data) {
  return await CUD('PUT', uri, data);
}

// 删除请求
const DELETE = async function (uri, data) {
  return await CUD('DELETE', uri, data);
}

export default {
  GET,
  POST,
  PUT,
  DELETE,
  SERVER,
  RAW_SERVER,
  api,
  OK: ok
};