import { api } from '@/utils/request.js';
import { BASE_API_URL } from '@/settings/siteSetting.js';
import { useUserStore } from '@/store/user.js';

// 微信登录
export const DiningUserWechatLogin = (params) => api.post({ url: '/dining/user/wechatLogin', params });

// 获取用户信息（GET /dining/user/getUserInfo），登录后调用以拿到头像等
export const GetUserInfo = () => api.get({ url: '/dining/user/getUserInfo' });

// 更新用户个人信息（POST /dining/user/updateProfile，body 为 dto）
export const PostUpdateProfile = (dto) =>
  api.post({ url: '/dining/user/updateProfile', params: dto });

// 文件上传（POST /file/upload，multipart，返回图片 URL/path 供 avatarUrl 使用）
function uploadFileToServerImpl(filePath) {
  const userStore = useUserStore();
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: BASE_API_URL+'/dining/file/upload',
      filePath,
      name: 'file',
      header: { Authorization: userStore.getToken || '' },
      success: (res) => {
        if (res.statusCode === 200) {
          try {
            const data = typeof res.data === 'string' ? JSON.parse(res.data) : res.data;
            const payload = data?.data ?? data;
            const url = payload?.url ?? payload?.path ?? payload?.relativePath ?? (typeof payload === 'string' ? payload : '');
            resolve(url || '');
          } catch (e) {
            reject(e);
          }
        } else {
          reject(new Error(res.data || '上传失败'));
        }
      },
      fail: reject
    });
  });
}
export const uploadFileToServer = uploadFileToServerImpl;
export const uploadFileToSever = uploadFileToServerImpl; // 兼容拼写错误

// 点餐页数据（入参 dinerCount 就餐人数、tableId 桌号）
export const DiningOrderFood = (params) => api.get({ url: '/store/dining/page-info', params });

// 门店详情（GET /store/info/detail/{storeId}，入参 storeId）
export const GetStoreDetail = (storeId) =>
  api.get({ url: `/store/info/detail/${encodeURIComponent(storeId)}` });

// 菜品种类（入参 storeId，GET /store/info/categories?storeId=）
export const GetStoreCategories = (params) => api.get({ url: '/store/info/categories', params });

// 根据菜品种类获取菜品（入参 categoryId，GET /store/info/cuisines?categoryId=）
export const GetStoreCuisines = (params) => api.get({ url: '/store/info/cuisines', params });

// 菜品详情（GET /store/dining/cuisine/{cuisineId}，入参 cuisineId 菜品ID、tableId 桌号ID 传 query）
export const GetCuisineDetail = (cuisineId, tableId) => {
  const id = cuisineId != null ? encodeURIComponent(cuisineId) : '';
  const url = id ? `/store/dining/cuisine/${id}` : '/store/dining/cuisine/0';
  const params = tableId != null && tableId !== '' ? { tableId } : {};
  return api.get({ url, params });
};

// 获取购物车（GET /store/order/cart/{tableId}，建立 SSE 连接之后调用）
export const GetOrderCart = (tableId) =>
  api.get({ url: `/store/order/cart/${encodeURIComponent(tableId)}` });

// 加入购物车（POST /store/order/cart/add，dto: { cuisineId 菜品ID, quantity 数量, tableId 桌号ID }）
export const PostOrderCartAdd = (dto) =>
  api.post({ url: '/store/order/cart/add', params: dto });

// 更新购物车（PUT /store/order/cart/update，请求类型 x-www-form-urlencoded，由 request 层 formUrlEncoded 封装）
export const PostOrderCartUpdate = (params) =>
  api.put({ url: '/store/order/cart/update', params, formUrlEncoded: true });

// 清空购物车（DELETE /store/order/cart/clear，入参 tableId：query + body 双传，兼容不同后端）
export const PostOrderCartClear = (tableId) => {
  const id = tableId != null ? String(tableId) : '';
  const url = id ? `/store/order/cart/clear?tableId=${encodeURIComponent(id)}` : '/store/order/cart/clear';
  return api.delete({ url, params: id ? { tableId: id } : {} });
};

// 创建订单（POST /store/order/create，入参 dto：tableId 桌号ID、contactPhone 联系电话、couponId 优惠券ID 默认 null、dinerCount 就餐人数、immediatePay 是否立即支付 默认 0、remark 备注信息 最多30字）
export const PostOrderCreate = (dto) =>
  api.post({ url: '/store/order/create', params: dto });

// 订单分页列表（GET /store/order/page，入参 current 页码、size 每页数量、orderStatus 订单状态、storeId 门店ID、tableId 桌号ID）
export const GetOrderPage = (params) =>
  api.get({ url: '/store/order/page', params });

// 我的订单（GET /store/order/my-orders，入参 current 页码、size 每页数量、type 订单类型 0未支付 1历史）
export const GetMyOrders = (params) =>
  api.get({ url: '/store/order/my-orders', params });

// 订单详情（GET /store/order/info/{orderId}，入参 orderId 订单ID）
export const GetOrderInfo = (orderId) =>
  api.get({ url: `/store/order/info/${encodeURIComponent(orderId)}` });

// 订单支付（POST /payment/prePay，入参 orderNo 订单号、payType 支付类型 默认 wechatPayMininProgram、payer 支付用户 openid、price 订单金额、subject 订单标题；返回微信支付调起参数）
export const PostOrderPay = (params) =>
  api.get({
    url: '/payment/prePay',
    params: {
      orderNo: params.orderNo,
      payType: 'wechatPayMininProgram',
      payer: params.payer,
      price: params.price,
      subject: params.subject ?? '订单支付'
    }
  });

// 根据第三方订单号查询支付结果（GET /payment/searchOrderByOutTradeNoPath，入参 payType、transactionId）
// 支付页调用时不显示全局 loading
export const GetSearchOrderByOutTradeNoPath = (params) =>
  api.get({
    url: '/payment/searchOrderByOutTradeNoPath',
    params: {
      payType: params.payType ?? 'wechatPayMininProgram',
      transactionId: params.transactionId
    },
    loading: false
  });

// 订单翻转/完成（POST /store/order/complete/{orderId}，入参 orderId）
// 支付页调用时不显示全局 loading
export const PostOrderComplete = (orderId) =>
  api.post({ url: `/store/order/complete/${encodeURIComponent(orderId)}`, loading: false });

/**
 * 订单 SSE 接口配置（GET /store/order/sse/{tableId}）
 * 仅提供 URL 与 header，实际连接请使用 utils/sse.js 的 createSSEConnection 封装
 */
export function getOrderSseConfig(tableId) {
  const userStore = useUserStore();
  return {
    url: `${BASE_API_URL}/store/order/sse/${encodeURIComponent(tableId)}`,
    header: { Authorization: userStore.getToken || '' },
    timeout: 0
  };
}