import axios from 'axios';
import config from './config';

// 微信配置
const WECHAT_CONFIG = {
  appId: 'wx10561f0e5ea2951f', // 需要配置你的微信公众号AppID
  scope: {
    BASE: 'snsapi_base', // 静默授权，获取openid
    USERINFO: 'snsapi_userinfo' // 用户授权，获取用户信息
  }
};

/**
 * 微信授权相关方法
 */
const WechatAuth = {
  /**
   * 检查是否在微信浏览器中
   */
  isWechatBrowser() {
    const ua = navigator.userAgent.toLowerCase();
    return ua.includes('micromessenger');
  },

  /**
   * 获取URL参数
   */
  getUrlParam(name) {
    const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
    const r = window.location.search.substr(1).match(reg);
    return r ? decodeURIComponent(r[2]) : null;
  },

  /**
   * 微信网页授权登录
   * @param {string} redirectUri - 授权后重定向的回调地址
   * @param {string} scope - 授权作用域 'snsapi_base' | 'snsapi_userinfo'
   * @param {string} state - 重定向后会带上state参数
   */
  authorize(redirectUri, scope = WECHAT_CONFIG.scope.BASE, state = 'STATE') {
    if (!this.isWechatBrowser()) {
      console.warn('当前不在微信浏览器环境中');
      return false;
    }

    const encodedUri = encodeURIComponent(redirectUri);
    const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WECHAT_CONFIG.appId}&redirect_uri=${encodedUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;

    window.location.href = authUrl;
    return true;
  },

  /**
   * 处理授权回调，获取code
   */
  handleAuthCallback() {
    const code = this.getUrlParam('code');
    const state = this.getUrlParam('state');

    if (code) {
      return { code, state };
    }
    return null;
  },

  /**
   * 通过code获取access_token和用户信息
   * @param {string} code - 授权码
   */
  async getAccessToken(code) {
    try {
      const urlParams = new URLSearchParams(window.location.search);
      const friend_account_id = urlParams.get('friend_account_id');
      const accountId = urlParams.get('accountId');
      const from = urlParams.get('from');

      const response = service.post('/auto/login', {
        code: code,
        friend_account_id,
        accountId,
        from
      });

      const result = await response;
      console.log('获取access_token成功:', result.data);
      if(result.data&&result.data.Authorization){
        localStorage.setItem('token', result.data.Authorization);
      }


      // 保存token到本地存储
      // if (result.access_token) {
      //   localStorage.setItem('token', result.access_token);
      //   localStorage.setItem('wechat_openid', result.openid);
      //   if (result.refresh_token) {
      //     localStorage.setItem('refresh_token', result.refresh_token);
      //   }
      // }
      

      return result;
    } catch (error) {
      console.error('获取access_token失败:', error);
      throw error;
    }
  },

  /**
   * 自动处理微信授权流程
   */
  async autoAuth() {
    // 检查是否有授权回调的code
    const authCallback = this.handleAuthCallback();
    if (authCallback && authCallback.code) {
      try {
        await this.getAccessToken(authCallback.code);
        // 清除URL中的code参数
        const url = new URL(window.location);
        url.searchParams.delete('code');
        url.searchParams.delete('state');
        window.history.replaceState({}, document.title, url.toString());
        return true;
      } catch (error) {
        console.error('自动授权失败:', error);
        return false;
      }
    }
    return false;
  },

  /**
   * 重新授权
   */
  reAuth() {
    // 清除本地token
    localStorage.removeItem('token');
    localStorage.removeItem('wechat_openid');
    localStorage.removeItem('refresh_token');

    // 重新发起授权
    const currentUrl = window.location.href.split('?')[0].split('#')[0];
    console.log("配置信息:",WECHAT_CONFIG);
    this.authorize(currentUrl);
  }
};

// 创建axios实例，使用config中的基础配置
const service = axios.create({
  baseURL: config.baseURL,
  timeout: config.timeout,
  headers: config.commonHeaders
});

// 请求拦截器：添加认证信息等
service.interceptors.request.use(
  (config) => {
    // 示例：从localStorage获取token并添加到请求头
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.Authorization = `${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器：处理状态码和错误
let isAuthing = false; // 授权标记位

service.interceptors.response.use(
   (response) => {
    // 直接返回响应数据（根据后端接口规范调整）
    // console.log(response.data.code);
    if (response.data.code === 403) {
      // 如果在微信浏览器中，自动重新授权
      if (WechatAuth.isWechatBrowser() && !isAuthing) {
        localStorage.removeItem("token");
        const urlParams = new URLSearchParams(window.location.search);
        const friend_account_id = urlParams.get('friend_account_id');
        const accountId = urlParams.get('accountId');
        wechatAPI.checkAndLogin(window.location.href, accountId ? accountId : undefined,friend_account_id ? friend_account_id : undefined);
        if(localStorage.getItem("token")){
          window.location.reload();
        }
        // return Promise.reject(new Error('正在重新授权，请稍候...'));
      }
    }
    return response.data;
  },
  async (error) => {
    const { response } = error;

    // 处理401未认证和400错误，重新进行微信授权
    if (response && (response.status === 401 || response.status === 400)) {
      console.warn('认证失败，准备重新授权:', response.status);

      // 如果在微信浏览器中，自动重新授权
      if (WechatAuth.isWechatBrowser() && !isAuthing) {
        isAuthing = true;
        try {
          await WechatAuth.reAuth();
          // 授权成功后刷新页面
          window.location.reload();
        } finally {
          isAuthing = false;
        }
        return Promise.reject(new Error('正在重新授权，请稍候...'));
      } else {
        console.error('不在微信浏览器环境中，无法自动重新授权');
      }
    }

    // 处理其他HTTP错误状态码
    console.error('API请求失败:', response?.status);
    return Promise.reject(error);
  }
);

// 微信相关API方法
const wechatAPI = {
  /**
   * 获取微信appid
   * GET /auto/config/wechat
   */
  getWechatAppId() {
    return service.get('/auto/config/wechat?url='+encodeURIComponent(location.href));
  },

  /**
   * 微信授权登录获取token
   * GET /auto/login
   * @param {string} code - 微信授权code
   * @param {number} friend_account_id - 分享用户id（可选）
   * @param {number} accountId - 渠道用户id（可选）
   */
  wechatLogin(code, accountId,friend_account_id) {
    const params = { code };
    if (accountId) {
      params.accountId = accountId;
    }
    if (friend_account_id) {
      params.friend_account_id = friend_account_id;
    }
    return service.post('/auto/login', params);
  },

  /**
   * 经纬度解析转换城市编码
   * GET /auto/config/city
   * @param {number} latitude - 纬度
   * @param {number} longitude - 经度
   */
  getLocationCity(latitude, longitude) {
    return service.get('/auto/config/city', {
      params: {
        latitude,
        longitude
      }
    });
  },

  /**
   * 获取产品详情
   * GET /auto/car/product/detail
   * @param {number} id - 产品id
   */
  getProductDetail(id) {
    return service.get('/auto/car/product/detail', {
      params: {
        id
      }
    });
  },

  /**
   * 检查并处理微信登录
   * 如果没有token，自动进行微信授权登录
   * @param {string} redirectUri - 授权回调地址
   * @param {number} accountId - 渠道用户id（可选）
   * @param {number} friend_account_id - 分享用户id（可选）
   */
  async checkAndLogin(redirectUri, accountId,friend_account_id) {
    const token = localStorage.getItem('token');

    // 如果已有token，直接返回
    if (token) {
      return { success: true, token };
    }

    // 检查URL中是否有微信授权返回的code
    const urlParams = new URLSearchParams(window.location.search);
    const code = urlParams.get('code');

    if (code) {
      try {
        // 使用code获取token
        const result = await this.wechatLogin(code, accountId,friend_account_id);
        if (result.code === 200 && result.data?.Authorization) {
          localStorage.setItem('token', result.data.Authorization);
          // 清除URL中的code参数
          const newUrl = window.location.pathname + window.location.hash;
          window.history.replaceState({}, document.title, newUrl);
          return { success: true, token: result.data.Authorization, userInfo: result.data };
        } else {
          throw new Error(result.message || '登录失败');
        }
      } catch (error) {
        console.error('微信登录失败:', error);
        return { success: false, error: error.message };
      }
    } else {
      // 没有code，需要跳转到微信授权页面
      try {
        const appIdResult = await this.getWechatAppId();
        console.log('获取微信AppID成功111:', appIdResult);
        if (appIdResult.code === 200 && appIdResult.data?.appId) {
          const appId = appIdResult.data.appId;
          const encodedUri = encodeURIComponent(redirectUri);
          const state = accountId || 'STATE';
          const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodedUri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
          localStorage.setItem('w_c', JSON.stringify(appIdResult.data));
          localStorage.setItem('app_id', appId);
          window.location.href = authUrl;
          return { success: false, redirecting: true };
        } else {
          throw new Error('获取微信AppID失败');
        }
      } catch (error) {
        console.error('获取微信AppID失败:', error);
        return { success: false, error: error.message };
      }
    }
  }
};

// 导出常用请求方法
// 获取微信配置
async function getWechatConfig() {
  try {
    const response = await service.get('/auto/config/wechat?url='+encodeURIComponent(location.href));
    const config = await response.data;
    if (config.appid) {
      WECHAT_CONFIG.appId = config.appid;
      console.log('微信AppID配置成功:', config.appid);
    }
    return config;
  } catch (error) {
    console.error('获取微信配置失败:', error);
    return null;
  }
}

// 初始化微信授权
if (WechatAuth.isWechatBrowser()) {
  // 先获取微信配置，再处理授权回调
  getWechatConfig().then(() => {
    WechatAuth.autoAuth();
  });
} else {
  // 非微信环境也获取配置，以备后用
  getWechatConfig();
}

// 导出常用请求方法和微信授权工具
export default {
  get: (url, params) => service.get(url, { params }),
  post: (url, data) => service.post(url, data),
  put: (url, data) => service.put(url, data),
  delete: (url) => service.delete(url),
  upload: (data) => service.post('/auto/upload', data, { headers: { 'Content-Type': 'multipart/form-data' } }),
  
  // 微信相关方法
  wechatAPI: wechatAPI,

  // 微信授权相关方法
  wechatAuth: WechatAuth,
  // 设置微信AppID
  setWechatAppId: (appId) => {
    WECHAT_CONFIG.appId = appId;
  },

  // 手动触发微信授权
  triggerWechatAuth: (redirectUri, scope) => {
    return WechatAuth.authorize(redirectUri, scope);
  }
};
