import httpApi from "@/api/indexApi";
import http from "@/api";
import { PORT_NONE } from "@/api/config/servicePort";

/** 经营统计数据 - 请求参数 */
export interface GetStatisticsParams {
  startTime: string;
  endTime: string;
  storeId: string | number;
}

/** 流量数据 */
export interface TrafficData {
  storeSearchVolume?: number;
  pageViews?: number;
  visitors?: number;
  newVisitors?: number;
  visitDuration?: number; // 秒
  avgVisitDuration?: number; // 秒
}

/** 互动数据 */
export interface InteractionData {
  storeCollectionCount?: number;
  storeShareCount?: number;
  storeCheckInCount?: number;
  consultMerchantCount?: number;
  friendsCount?: number;
  followCount?: number;
  fansCount?: number;
  postsPublishedCount?: number;
  postLikesCount?: number;
  postCommentsCount?: number;
  postSharesCount?: number;
  reportedCount?: number;
  blockedCount?: number;
}

/** 优惠券/代金券数据 */
export interface CouponVoucherData {
  giftToFriendsCount?: number;
  giftToFriendsAmount?: number;
  giftToFriendsUsedCount?: number;
  giftToFriendsUsedAmount?: number;
  giftToFriendsUsedAmountRatio?: number;
  friendsGiftCount?: number;
  friendsGiftAmount?: number;
  friendsGiftUsedCount?: number;
  friendsGiftUsedAmount?: number;
  friendsGiftUsedAmountRatio?: number;
}

/** 服务质量数据 */
export interface ServiceQualityData {
  storeRating?: number;
  scoreOne?: number;
  scoreTwo?: number;
  scoreThree?: number;
  totalReviews?: number;
  positiveReviews?: number;
  neutralReviews?: number;
  negativeReviews?: number;
  negativeReviewRatio?: number;
  negativeReviewAppealsCount?: number;
  negativeReviewAppealSuccessCount?: number;
  negativeReviewAppealSuccessRatio?: number;
}

/** 价目表排名项 */
export interface PriceListRankingItem {
  rank: number;
  priceId: number;
  priceListItemName: string;
  pageViews: number;
  visitors: number;
  shares: number;
}

/** 经营统计数据 - 响应 */
export interface GetStatisticsData {
  trafficData?: TrafficData;
  interactionData?: InteractionData;
  couponData?: CouponVoucherData;
  voucherData?: CouponVoucherData;
  serviceQualityData?: ServiceQualityData;
  priceListRanking?: PriceListRankingItem[];
}

/**
 * 获取经营统计数据（平台接口，与 getMerchantByPhone 同源：http + VITE_API_URL_PLATFORM）
 */
export const getStatistics = (params: GetStatisticsParams) => {
  return http.get<GetStatisticsData>(PORT_NONE + `/platform/operational/statistics/getPlatformStatistics`, params, {
    loading: false
  });
};

/** 经营统计对比数据 - 请求参数 */
export interface GetStatisticsComparisonParams {
  currentStartTime: string;
  currentEndTime: string;
  previousStartTime: string;
  previousEndTime: string;
  storeId: string | number;
}

/** 经营统计对比数据 - 响应（含 historyId 用于 AI 分析详情） */
export interface GetStatisticsComparisonData {
  historyId?: number;
  current?: {
    trafficData?: TrafficData;
    interactionData?: InteractionData;
    couponData?: CouponVoucherData;
    voucherData?: CouponVoucherData;
    serviceQualityData?: ServiceQualityData;
  };
  previous?: {
    trafficData?: TrafficData;
    interactionData?: InteractionData;
    couponData?: CouponVoucherData;
    voucherData?: CouponVoucherData;
    serviceQualityData?: ServiceQualityData;
  };
  change?: {
    trafficData?: Record<string, number>;
    interactionData?: Record<string, number>;
    couponData?: Record<string, number>;
    voucherData?: Record<string, number>;
    serviceQualityData?: Record<string, number>;
  };
}

/**
 * 获取经营统计对比数据
 */
export const getStatisticsComparison = (params: GetStatisticsComparisonParams) => {
  return http.get<GetStatisticsComparisonData>(
    PORT_NONE + `/platform/operational/statistics/getPlatformStatisticsComparison`,
    params,
    {
      loading: false
    }
  );
};

/** AI 分析历史详情 - 请求参数 */
export interface GetHistoryDetailParams {
  id: number | string;
}

/** AI 分析历史详情 - 响应 */
export interface GetHistoryDetailData {
  summary?: string;
  optimizationSuggestions?: string;
  aiAnalysisCompleted?: number;
  /** 对比数据 JSON 字符串，解析后结构同 StoreOperationalStatisticsComparisonVo */
  statisticsData?: string;
}

/**
 * 获取经营统计历史详情（AI 分析），调用方式同 getStatisticsComparison
 */
export const getHistoryDetail = (params: GetHistoryDetailParams) => {
  return http.get<GetHistoryDetailData>(PORT_NONE + `/platform/operational/statistics/history/platformDetail`, params, {
    loading: false
  });
};

/** 历史分析报告列表 - 请求参数 */
export interface GetHistoryReportListParams {
  storeId: string | number;
  page: number;
  size: number;
  created_time?: string; // 生成时间筛选 YYYY-MM-DD
}

/** 接口返回的历史记录项（含 queryTime） */
export interface HistoryReportRecord {
  id?: number | string;
  queryTime?: string; // 完整年月日时分秒，如 "2026-02-05 13:48:35"
  createdTime?: string;
  [key: string]: any;
}

/** 历史分析报告列表 - 接口响应 */
export interface GetHistoryReportListData {
  records?: HistoryReportRecord[];
  list?: HistoryReportRecord[];
  total?: number;
}

/**
 * 获取历史分析报告列表 /platform/operational/statistics/history/platformList
 */
export const getHistoryReportList = (params: GetHistoryReportListParams) => {
  return http.get<GetHistoryReportListData>(PORT_NONE + `/platform/operational/statistics/history/platformList`, params, {
    loading: false
  });
};

/** 批量删除历史分析报告 - 请求参数 */
export interface BatchDeleteHistoryParams {
  ids: string; // 列表中 id 用英文逗号分隔，如 "235,234,233"
}

/**
 * 批量删除历史分析报告 /platform/operational/statistics/history/batchPlatformDelete（DELETE）
 */
export const batchDeleteHistoryReport = (params: BatchDeleteHistoryParams) => {
  return http.delete<unknown>(PORT_NONE + `/platform/operational/statistics/history/batchPlatformDelete`, params, {
    loading: true
  });
};

/** 根据历史记录生成对比报告 PDF - 请求参数 */
export interface GenerateStatisticsComparisonPdfByHistoryIdParams {
  historyId: number | string;
  storeId: string | number;
}

/**
 * 根据历史记录 id 生成对比报告 PDF /platform/operational/statistics/generateStatisticsComparisonPdfByHistoryId
 * 返回 data 为 PDF 文件地址（字符串）
 */
export const generateStatisticsComparisonPdfByHistoryId = (params: GenerateStatisticsComparisonPdfByHistoryIdParams) => {
  return http.get<string>(PORT_NONE + `/platform/operational/statistics/generateStatisticsComparisonPdfByHistoryId`, params, {
    loading: true
  });
};
