import axios from "axios";
import { PORT_NONE } from "@/api/config/servicePort";
import { localGet } from "@/utils";
import { ResultEnum } from "@/enums/httpEnum";
import { useUserStore } from "@/stores/modules/user";
import { ElMessage } from "element-plus";
import { LOGIN_URL } from "@/config";
import router from "@/routers";

// 创建专门用于价目表（STORE）接口的 axios 实例，前缀使用 alienStore
const priceListAxios = axios.create({
  baseURL: import.meta.env.VITE_API_URL_STORE as string, // /api/alienStore
  timeout: ResultEnum.TIMEOUT as number,
  withCredentials: true
});

// 请求拦截：补充 token
priceListAxios.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    if (config.headers) {
      (config.headers as any).Authorization = userStore.token;
    }
    return config;
  },
  error => Promise.reject(error)
);

// 响应拦截：与平台 http 保持一致的基础处理
priceListAxios.interceptors.response.use(
  response => {
    const data = response.data;
    const userStore = useUserStore();

    // 登录失效
    if (data.code == ResultEnum.OVERDUE) {
      userStore.setToken("");
      router.replace(LOGIN_URL);
      ElMessage.error(data.msg);
      return Promise.reject(data);
    }

    // 全局错误信息拦截
    if (data.code && data.code !== ResultEnum.SUCCESS) {
      ElMessage.error(data.msg);
      return Promise.reject(data);
    }

    return data;
  },
  error => {
    ElMessage.error("请求失败，请稍后重试");
    return Promise.reject(error);
  }
);

// 后端状态：0=审核中, 1=审核通过, 2=审核拒绝（根据商家端价目表说明推断）
export const AUDIT_STATUS_LABEL: Record<number, string> = {
  0: "审核中",
  1: "审核通过",
  2: "审核拒绝"
};

// 经营板块对应的模块类型（与商家端保持一致）
export const MODULE_TYPES = {
  FOOD: "food",
  GENERAL_PACKAGE: "generalPackage"
} as const;

export type ModuleType = (typeof MODULE_TYPES)[keyof typeof MODULE_TYPES];

export interface RawPriceItem {
  id: number | string;
  // 通用字段
  name?: string;
  prodName?: string;
  totalPrice?: number;
  images?: string;
  status?: number;
  shelfStatus?: number;
  rejectionReason?: string;
  // 美食特有字段
  cuisineType?: number;
  // 兼容旧版 storeProductItem 结构
  subList?: Array<{
    price?: number;
    unit?: string;
    quantity?: number;
  }>;
  prodType?: number;
}

export interface PriceListRow {
  id: number | string;
  // 名称
  dishName: string;
  // 展示价格
  dishPrice: string;
  // 单位
  dishUnit: string;
  // 列表首图
  imgUrl: string;
  // 审核状态
  auditStatus: number | null;
  // 上下架状态：1=上架,2=下架
  shelfStatus: number;
  // 审核拒绝原因
  auditReason: string;
  // 业务类型
  prodType?: number;
  cuisineType?: number;
}

export interface PriceListQuery {
  pageNum?: number;
  pageSize?: number;
  storeId?: number | string;
  prodName?: string;
  status?: number | string;
  shelfStatus?: number | string;
  origin?: number | string;
  businessSection?: string | number;
  /** 提交时间起（提交时间段搜索） */
  startCreatedTime?: string;
  /** 提交时间止（提交时间段搜索） */
  endCreatedTime?: string;
}

// 根据经营板块获取模块类型（与商家端 config.js 保持一致）
export const getModuleTypeByBusinessSection = (businessSection?: string | number): ModuleType => {
  const section = businessSection !== undefined && businessSection !== null ? String(businessSection) : "";
  return section === "1" ? MODULE_TYPES.FOOD : MODULE_TYPES.GENERAL_PACKAGE;
};

// 获取当前模块类型（通过本地缓存的 businessSection）
export const getCurrentModuleType = (): ModuleType => {
  const businessSection = localGet("businessSection");
  return getModuleTypeByBusinessSection(businessSection);
};

// 获取价目表分页列表
// 不同经营板块调不同接口：
// - 美食板块：/store/cuisine/getPage
// - 通用板块：/store/price/getPage
export const getPriceListPage = (params: PriceListQuery) => {
  const moduleType = getModuleTypeByBusinessSection(params.businessSection ?? localGet("businessSection") ?? "1");
  const storeId = params.storeId ?? (localGet("createdId") as string) ?? "";
  const pageNum = params.pageNum ?? 1;
  const pageSize = params.pageSize ?? 10;

  if (moduleType === MODULE_TYPES.FOOD) {
    const query: any = {
      pageNum,
      pageSize,
      storeId,
      type: 1, // 1-美食
      origin: params.origin !== undefined && params.origin !== null && params.origin !== "" ? params.origin : 0
    };

    if (params.prodName) query.name = params.prodName;
    if (params.status !== undefined && params.status !== null && params.status !== "") {
      query.status = params.status;
    }
    if (params.startCreatedTime) query.startCreatedTime = params.startCreatedTime;
    if (params.endCreatedTime) query.endCreatedTime = params.endCreatedTime;

    return priceListAxios.get<any>(PORT_NONE + "/store/cuisine/getPage", { params: query });
  }

  const query: any = {
    pageNum,
    pageSize,
    storeId,
    origin: params.origin !== undefined && params.origin !== null && params.origin !== "" ? params.origin : 0
  };

  if (params.prodName) query.name = params.prodName;
  if (params.status !== undefined && params.status !== null && params.status !== "") {
    query.status = params.status;
  }
  if (params.startCreatedTime) query.startCreatedTime = params.startCreatedTime;
  if (params.endCreatedTime) query.endCreatedTime = params.endCreatedTime;

  return priceListAxios.get<any>(PORT_NONE + "/store/price/getPage", { params: query });
};

// 删除价目表条目（按经营板块走不同接口）
export const deletePriceItem = (id: number | string): Promise<any> => {
  const moduleType = getCurrentModuleType();
  if (moduleType === MODULE_TYPES.FOOD) {
    return priceListAxios.post(PORT_NONE + `/store/cuisine/delete?id=${id}`);
  }
  return priceListAxios.post(PORT_NONE + `/store/price/delete?id=${id}`);
};

// 上架/下架价目表条目（按经营板块走不同接口）
// @param id - 价目表ID
// @param shelfStatus - 上下架状态：1-上架，2-下架
export const updateShelfStatus = (id: number | string, shelfStatus: number): Promise<any> => {
  const moduleType = getCurrentModuleType();
  if (moduleType === MODULE_TYPES.FOOD) {
    return priceListAxios.post(PORT_NONE + `/store/cuisine/changeShelfStatus?id=${id}&shelfStatus=${shelfStatus}`);
  }
  return priceListAxios.post(PORT_NONE + `/store/price/changeShelfStatus?id=${id}&shelfStatus=${shelfStatus}`);
};

// 美食类型：1-单品(菜品)，2-套餐
export const CUISINE_TYPE = { SINGLE: 1, COMBO: 2 } as const;

// 获取价目表详情（美食板块用 cuisineType，通用板块不传）
export const getPriceListDetail = (id: string, businessSection?: string, cuisineType?: number): Promise<any> => {
  const moduleType = getModuleTypeByBusinessSection(businessSection ?? localGet("businessSection") ?? "1");
  const storeId = localGet("createdId") as string;
  if (moduleType === MODULE_TYPES.FOOD) {
    const type = cuisineType !== undefined && cuisineType !== null ? cuisineType : 1;
    return priceListAxios.get<any>(PORT_NONE + "/store/cuisine/getByCuisineType", {
      params: { id, cuisineType: type }
    });
  }
  return priceListAxios.get<any>(PORT_NONE + "/store/price/getById", { params: { id } });
};

// 新增价目表（与商家端 addPriceListItem 一致：美食 addCuisineCombo，通用 save）
export const addPriceItem = (params: any): Promise<any> => {
  const moduleType = getCurrentModuleType();
  if (moduleType === MODULE_TYPES.FOOD) {
    return priceListAxios.post(PORT_NONE + "/store/cuisine/addCuisineCombo", params);
  }
  return priceListAxios.post(PORT_NONE + "/store/price/save", params);
};

// 更新价目表（与商家端 addPriceListItem 一致：美食 updateCuisineCombo，通用 update）
export const updatePriceItem = (params: any): Promise<any> => {
  const moduleType = getCurrentModuleType();
  if (moduleType === MODULE_TYPES.FOOD) {
    return priceListAxios.post(PORT_NONE + "/store/cuisine/updateCuisineCombo", params);
  }
  return priceListAxios.post(PORT_NONE + "/store/price/update", params);
};

// 获取美食单品名称列表（套餐编辑时选择菜品用）
export const getCuisineSingleNameList = (): Promise<any> => {
  const storeId = localGet("createdId") as string;
  return priceListAxios.get<any>(PORT_NONE + "/store/cuisine/getSingleName", {
    params: { storeId }
  });
};

// 推荐价格（根据原料成本，可选使用）
export const getRecommendedPrice = (dishName: string, location?: string): Promise<any> => {
  return priceListAxios.post<any>(PORT_NONE + "/store/cuisine/getPrice", null, {
    params: { dish_name: dishName, location: location || "" }
  });
};

// 根据接口返回结构转换为表格展示行
// 兼容：
// - /store/cuisine/getPage 返回的美食价目
// - /store/price/getPage 返回的通用价目
export const transformListItem = (item: RawPriceItem): PriceListRow => {
  const imgUrl = item.images ? item.images.split(",")[0] : "";

  // 名称字段兼容 prodName/name
  const name = item.prodName || item.name || "";

  // 价格：
  // - 优先使用 totalPrice
  // - 兼容旧版 storeProductItem.subList[0].price
  let displayPrice: number | string | undefined = item.totalPrice;
  if (
    (displayPrice === undefined || displayPrice === null || (typeof displayPrice === "string" && displayPrice === "")) &&
    Array.isArray(item.subList)
  ) {
    displayPrice = item.subList[0]?.price;
  }

  return {
    id: item.id,
    dishName: name,
    dishPrice: displayPrice !== undefined && displayPrice !== null && String(displayPrice) !== "" ? String(displayPrice) : "",
    dishUnit: "份",
    imgUrl: imgUrl || "",
    // 审核状态：0=审核中, 1=审核通过, 2=审核拒绝
    auditStatus: typeof item.status === "number" ? item.status : null,
    // 上下架状态：1-上架，2-下架；默认 1
    shelfStatus: typeof item.shelfStatus === "number" ? item.shelfStatus : 1,
    auditReason: item.rejectionReason || "",
    prodType: item.prodType,
    cuisineType: item.cuisineType
  };
};
