// 银行端小程序API服务层
const API_BASE_URL = 'https://ad.ningmuyun.com/bank/api';

// 获取存储的token
const getToken = () => {
  return wx.getStorageSync('bank_token') || '';
};

// 设置token
const setToken = (token) => {
  wx.setStorageSync('bank_token', token);
};

// 清除token
const clearToken = () => {
  wx.removeStorageSync('bank_token');
  wx.removeStorageSync('bank_user');
};

// 创建请求头
const createHeaders = (headers = {}) => {
  const token = getToken();
  const defaultHeaders = {
    'Content-Type': 'application/json',
  };
  
  if (token) {
    defaultHeaders['Authorization'] = `Bearer ${token}`;
  }
  
  return { ...defaultHeaders, ...headers };
};

// 处理API响应
const handleResponse = (response) => {
  return new Promise((resolve, reject) => {
    if (response.statusCode === 401) {
      clearToken();
      wx.showToast({
        title: '登录已过期，请重新登录',
        icon: 'none'
      });
      reject(new Error('认证已过期'));
      return;
    }
    
    if (response.statusCode >= 400) {
      wx.showToast({
        title: response.data?.message || '请求失败',
        icon: 'none'
      });
      reject(new Error(response.data?.message || '请求失败'));
      return;
    }
    
    if (response.data && !response.data.success) {
      wx.showToast({
        title: response.data.message || '操作失败',
        icon: 'none'
      });
      reject(new Error(response.data.message || '操作失败'));
      return;
    }
    
    resolve(response.data);
  });
};

// 发起请求
const request = (options) => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${API_BASE_URL}${options.url}`,
      method: options.method || 'GET',
      data: options.data || {},
      header: createHeaders(options.headers),
      success: (response) => {
        handleResponse(response).then(resolve).catch(reject);
      },
      fail: (error) => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        reject(error);
      }
    });
  });
};

// API服务
const apiService = {
  // 认证相关
  auth: {
    // 登录
    login: (username, password) => {
      return request({
        url: '/auth/login',
        method: 'POST',
        data: { username, password }
      });
    },
    
    // 获取当前用户信息
    getCurrentUser: () => {
      return request({
        url: '/auth/me',
        method: 'GET'
      });
    },
    
    // 登出
    logout: () => {
      return request({
        url: '/auth/logout',
        method: 'POST'
      });
    },
    
    // 修改密码
    changePassword: (passwordData) => {
      return request({
        url: '/auth/change-password',
        method: 'POST',
        data: passwordData
      });
    }
  },
  
  // 项目相关
  projects: {
    // 获取项目列表
    getList: (params = {}) => {
      return request({
        url: '/projects',
        method: 'GET',
        data: params
      });
    },
    
    // 获取项目详情
    getById: (id) => {
      return request({
        url: `/projects/${id}`,
        method: 'GET'
      });
    },
    
    // 创建项目
    create: (data) => {
      return request({
        url: '/projects',
        method: 'POST',
        data
      });
    },
    
    // 更新项目
    update: (id, data) => {
      return request({
        url: `/projects/${id}`,
        method: 'PUT',
        data
      });
    },
    
    // 删除项目
    delete: (id) => {
      return request({
        url: `/projects/${id}`,
        method: 'DELETE'
      });
    },
    
    // 获取项目统计
    getStats: () => {
      return request({
        url: '/projects/stats',
        method: 'GET'
      });
    }
  },
  
  // 监管任务相关
  supervisionTasks: {
    // 获取监管任务列表
    getList: (params = {}) => {
      return request({
        url: '/supervision-tasks',
        method: 'GET',
        data: params
      });
    },
    
    // 获取监管任务详情
    getById: (id) => {
      return request({
        url: `/supervision-tasks/${id}`,
        method: 'GET'
      });
    }
  },

  // 贷款商品相关
  loanProducts: {
    // 获取贷款商品列表
    getList: (params = {}) => {
      return request({
        url: '/loan-products',
        method: 'GET',
        data: params
      });
    },
    
    // 获取贷款商品详情
    getById: (id) => {
      return request({
        url: `/loan-products/${id}`,
        method: 'GET'
      });
    },
    
    // 获取贷款商品统计
    getStats: () => {
      return request({
        url: '/loan-products/stats',
        method: 'GET'
      });
    },
    
    // 获取贷款商品详情（别名）
    getDetail: (id) => {
      return request({
        url: `/loan-products/${id}`,
        method: 'GET'
      });
    },
    
    // 创建贷款商品
    create: (data) => {
      return request({
        url: '/loan-products',
        method: 'POST',
        data: data
      });
    },
    
    // 更新贷款商品
    update: (id, data) => {
      return request({
        url: `/loan-products/${id}`,
        method: 'PUT',
        data: data
      });
    },
    
    // 删除贷款商品（下架）
    delete: (id) => {
      return request({
        url: `/loan-products/${id}`,
        method: 'DELETE'
      });
    },
    
    // 上架/下架商品
    toggleStatus: (id, status) => {
      return request({
        url: `/loan-products/${id}/status`,
        method: 'PATCH',
        data: { onSaleStatus: status }
      });
    }
  },

  // 贷款申请相关
  loanApplications: {
    // 获取贷款申请列表
    getList: (params = {}) => {
      return request({
        url: '/loan-applications',
        method: 'GET',
        data: params
      });
    },
    
    // 获取贷款申请详情
    getById: (id) => {
      return request({
        url: `/loan-applications/${id}`,
        method: 'GET'
      });
    },
    
    // 获取申请统计
    getStats: () => {
      return request({
        url: '/loan-applications/stats',
        method: 'GET'
      });
    }
  },

  // 贷款合同相关
  loanContracts: {
    // 获取贷款合同列表
    getList: (params = {}) => {
      return request({
        url: '/loan-contracts',
        method: 'GET',
        data: params
      });
    },
    
    // 获取贷款合同详情
    getById: (id) => {
      return request({
        url: `/loan-contracts/${id}`,
        method: 'GET'
      });
    },
    
    // 获取合同统计
    getStats: () => {
      return request({
        url: '/loan-contracts/stats',
        method: 'GET'
      });
    },
    
    // 更新合同
    update: (id, data) => {
      return request({
        url: `/loan-contracts/${id}`,
        method: 'PUT',
        data: data
      });
    },
    
    // 删除合同
    delete: (id) => {
      return request({
        url: `/loan-contracts/${id}`,
        method: 'DELETE'
      });
    }
  },

  // 贷款解押相关
  loanReleases: {
    // 获取贷款解押列表
    getList: (params = {}) => {
      return request({
        url: '/loan-releases',
        method: 'GET',
        data: params
      });
    },
    
    // 获取贷款解押详情
    getById: (id) => {
      return request({
        url: `/loan-releases/${id}`,
        method: 'GET'
      });
    },
    
    // 获取解押统计
    getStats: () => {
      return request({
        url: '/loan-releases/stats',
        method: 'GET'
      });
    }
  }
};

module.exports = {
  apiService,
  setToken,
  clearToken,
  getToken
};
