import type { Login } from "@/api/interface";
import httpLogin from "@/api/indexApi";
import { Upload } from "@/api/interface/index";
import { uploadFormDataSimpleCompat } from "@/api/upload.js";
// 获取图片验证码
export const getImgCode = () => {
  return httpLogin.get(
    `/alienStorePlatform/storePlatformLogin/generateCaptcha`,
    {},
    {
      responseType: "blob",
      loading: false
    }
  ); // 正常 post json 请求  ==>  application/json
};
// 获取手机验证码
export const getPhoneCode = params => {
  return httpLogin.get(`/alienStore/ali/sendSms`, params, { loading: false });
};
// 注册账号
export const registerAccount = params => {
  return httpLogin.get(`/alienStorePlatform/storePlatformLogin/register`, params, { loading: false });
};
//注册校验
export const registerCheck = params => {
  return httpLogin.get(`/alienStorePlatform/storePlatformLogin/checkRegister`, params, { loading: false });
};
//登录账号 /storePlatformLogin/login
export const loginAccount = params => {
  return httpLogin.get(`/alienStorePlatform/storePlatformLogin/login`, params, { loading: false });
};
// 拉黑用户
export const blockUser = (params: {
  blockerType: number; // 拉黑者类型：1表示商家
  blockedType: number; // 被拉黑者类型：1表示商家
  blockerId: number | string; // 拉黑者ID
  blockedId: number | string; // 被拉黑者ID
}) => {
  return httpLogin.post("/alienStore/life-blacklist/blackList", params);
};
// 忘记密码 /storePlatformLogin/updatePassword
export const forgetPassword = params => {
  return httpLogin.get(`/alienStorePlatform/storePlatformLogin/updatePassword`, params, { loading: false });
};

//经营板块
export const getBusinessSection = () => {
  return httpLogin.get(`/alienStore/store/info/getBusinessSection`);
};

//经营种类
export const getBusinessSectionTypes = (params: { parentId: string }) => {
  return httpLogin.get(`/alienStore/store/info/getBusinessSectionTypes`, params);
};

//经纬度查询
export const getInputPrompt = params => {
  return httpLogin.get(`/alienStore/gaode/getInputPrompt`, params);
};

//所在地区
export const getDistrict = params => {
  return httpLogin.get(`/alienStore/gaode/getDistrict`, params);
};
// 文件上传（统一走 @/api/upload.js → /upload/simple）
export const uploadImg = (params: FormData) => uploadFormDataSimpleCompat(params);
// 发布/更新动态（新接口）
export const addOrUpdateDynamic = (params: {
  address?: string; // 经纬度
  addressName?: string; // 地址名称
  addressProvince?: string; // 省市
  context: string; // 正文内容
  createId: number | string; // 创建者ID
  draft: number; // 0表示发布，1表示草稿
  imagePath: string; // 图片/视频路径（多个用逗号分隔）
  phoneId: string; // 店铺ID
  title: string; // 标题
  type: string; // "2" 表示动态类型
  id?: number | string; // 动态ID（更新时需要）
}) => {
  return httpLogin.post(`/alienStore/userDynamics/addOrUpdate`, params);
};
//验证验证码
export const getCheckSmsCode = params => {
  return httpLogin.get(`/alienStore/ali/checkSmsCode`, params);
};

//ocr
export const ocrRequestUrl = params => {
  return httpLogin.post<Upload.ResFileUrl>(`/alienStore/ali/ocrRequestUrl`, params);
};
//ai入驻审核
export const getAiapprovestoreInfo = params => {
  return httpLogin.post<Upload.ResFileUrl>(`/alienStore/store/info/aiApproveStoreInfo`, params);
};
//门店头图ocr识别
export const getStoreOcrData = params => {
  return httpLogin.get(`/alienStore/store/info/getStoreOcrData`, params);
};
// 获取好友优惠券列表
export const getFriendCouponList = (params: any) => {
  return httpLogin.get(`/alienStore/life-discount-coupon-store-friend/getReceivedSendFriendCouponList`, params);
};
// 获取好友代金券列表
export const getCouponDetail = (params: any) => {
  return httpLogin.get(`/alienStore/coupon/getCouponDetail`, params);
};
// 获取好友优惠券列表
export const getFriendCouponDetail = (params: any) => {
  return httpLogin.get(`/alienStore/life-discount-coupon/getCounponDetailById`, params);
};

// 好友列表
export const getMutualAttention = (params: any) => {
  return httpLogin.get(`/alienStore/stores/getMutualAttention`, params);
};

//关注列表
export const getMyFollowed = (params: any) => {
  return httpLogin.get(`/alienStore/stores/getMyFollowed`, params);
};

//粉丝列表
export const getMyStoreFans = (params: any) => {
  return httpLogin.get(`/alienStore/stores/getMyStoreFans`, params);
};
export const getMyUserFans = (params: any) => {
  return httpLogin.get(`/alienStore/stores/getMyUserFans`, params);
};

// 优惠券列表
export const getCouponList = (params: any) => {
  return httpLogin.get(`/alienStore/life-discount-coupon/getStoreAllCouponListPaginateNot`, params);
};

// 赠送好友优惠券
export const setFriendCoupon = (params: any) => {
  return httpLogin.post(`/alienStore/life-discount-coupon-store-friend/setFriendCoupon`, params);
};

//好友关系管理列表
export const getRuleList = (params: any) => {
  return httpLogin.get(`/alienStore/life-discount-coupon-store-friend/getRuleList`, params);
};

//添加活动-选择商家
export const getReceivedFriendCouponList = (params: any) => {
  return httpLogin.get(`/alienStore/life-discount-coupon-store-friend/getReceivedFriendCouponList`, params);
};

//保存活动
export const saveFriendCouponRule = (params: any) => {
  return httpLogin.post(`/alienStore/life-discount-coupon-store-friend/saveFriendCouponRule`, params);
};
//删除活动
export const delFriendCouponRule = (params: any) => {
  return httpLogin.get(`/alienStore/life-discount-coupon-store-friend/delFriendCouponRule`, params);
};

//编辑回显
export const getRuleById = (params: any) => {
  return httpLogin.get(`/alienStore/life-discount-coupon-store-friend/getRuleById`, params);
};

/** 代金券列表（好友关系管理-折扣券用）与 group_merchant couponList 参数一致 */
export const getVoucherList = (params: { storeId: string; status?: number; size?: number; page?: number }) => {
  return httpLogin.get(`/alienStore/coupon/getCouponList`, params);
};

/** 满减券列表（好友关系管理-满减券用）与 group_merchant issueCouponList 参数一致 */
export const getIssueCouponList = (params: {
  storeId: string;
  tab?: number;
  size?: number;
  page?: number;
  couponName?: string;
  couponsFromType?: number;
  couponType?: number;
}) => {
  return httpLogin.get(`/alienStore/life-discount-coupon/getStoreAllCouponList`, params);
};

//查询评价列表
export const getList = (params: any) => {
  // return httpLogin.get(`/alienStore/storeComment/getList`, params);
  return httpLogin.get(`/alienStore/commonRating/getList`, params);
};

//查询评价数量
export const getRatingCount = (params: any) => {
  return httpLogin.get(`/alienStore/commonRating/getRatingCount`, params);
};

//申诉历史
export const getAppealHistory = (params: any) => {
  return httpLogin.get(`/alienStore/storeCommentAppeal/getAppealHistory`, params);
};

//申诉详情
export const getAppealDetail = (params: any) => {
  return httpLogin.get(`/alienStore/storeCommentAppeal/getAppealDetail`, params);
};

// 申诉删除（与商家端一致：FormData 含 appealReason、storeId、commentId、file_0/file_1...）
export const addAppealNew = (params: FormData | Record<string, unknown>) => {
  return httpLogin.post(`/alienStore/storeCommentAppeal/addAppealNew`, params);
};

// 动态-------------------------------------------------------------------------------------
/** commonComment/addComment 请求体（与接口模型一致；新增评论一般只传部分字段） */
export interface AddCommonCommentBody {
  auditReason?: string;
  /** 0-待审核 1-通过 2-驳回 */
  auditStatus?: number;
  /** 1-用户评论 2-商户评论（仅回复） */
  commentType?: number;
  content?: string;
  createdTime?: string;
  /** 0-未删除 1-已删除 */
  deleteFlag?: number;
  extInfo?: string;
  id?: number;
  imageUrls?: string;
  /** 0-否 1-是（仅用户评论生效） */
  isAnonymous?: number;
  /** 0-隐藏 1-展示 */
  isShow?: number;
  likeCount?: number;
  /** commentType=2 时必填 */
  merchantId?: number;
  /** 0=根评论，>0=回复某条评论 */
  parentId?: number;
  replyCount?: number;
  /** sourceType=1 rating.id；=2 动态ID；=3 打卡；=4 二手商品 */
  sourceId?: number;
  /** 1-评价的评论 2-动态 3-打卡 4-二手商品 */
  sourceType?: number;
  updatedTime?: string;
  /** 用户=用户ID，商户=商户运营账号ID */
  userId?: number;
}

function omitUndefinedRecord(obj: Record<string, unknown>): Record<string, unknown> {
  return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined && v !== null));
}

/** 将可转为整型的 id 字段转为 number，无法转换则返回 undefined */
function toInt64(v: unknown): number | undefined {
  if (v === undefined || v === null || v === "") return undefined;
  const n = Number(v);
  return Number.isFinite(n) ? Math.trunc(n) : undefined;
}

function buildSaveCommentBody(params: any): AddCommonCommentBody {
  const businessType = Number(params.businessType ?? 2);
  const isRating = businessType === 1;
  const sourceType = isRating ? 1 : 2;
  const sourceIdRaw = isRating ? (params.replyId ?? params.businessId) : (params.businessId ?? params.sourceId);
  const parentId = isRating ? 0 : Number(params.replyId || 0);
  const merchantRaw = params.merchantId ?? params.storeId ?? (isRating ? params.businessId : undefined);

  const body: AddCommonCommentBody = {
    userId: toInt64(params.userId ?? params.phoneId),
    sourceType,
    sourceId: toInt64(sourceIdRaw),
    parentId,
    content: String(params.commentContent ?? params.content ?? ""),
    commentType: Number(params.commentType ?? 2),
    merchantId: toInt64(merchantRaw),
    isAnonymous: params.isAnonymous !== undefined ? Number(params.isAnonymous) : 0
  };

  if (params.auditReason != null && params.auditReason !== "") body.auditReason = String(params.auditReason);
  if (params.auditStatus !== undefined) body.auditStatus = Number(params.auditStatus);
  if (params.createdTime) body.createdTime = String(params.createdTime);
  if (params.deleteFlag !== undefined) body.deleteFlag = Number(params.deleteFlag);
  if (params.extInfo != null && params.extInfo !== "") body.extInfo = String(params.extInfo);
  if (params.id !== undefined && params.id !== null && params.id !== "") {
    const idNum = toInt64(params.id);
    if (idNum !== undefined) body.id = idNum;
  }
  if (params.imageUrls != null && params.imageUrls !== "") body.imageUrls = String(params.imageUrls);
  if (params.isShow !== undefined) body.isShow = Number(params.isShow);
  if (params.likeCount !== undefined) body.likeCount = Number(params.likeCount);
  if (params.replyCount !== undefined) body.replyCount = Number(params.replyCount);
  if (params.updatedTime) body.updatedTime = String(params.updatedTime);

  return body;
}

/** 商家端 commonComment/addComment，请求体字段与接口一致 */
export const addComment = (data: AddCommonCommentBody) => {
  const raw: Record<string, unknown> = { ...data };
  return httpLogin.post(`/alienStore/commonComment/addComment`, omitUndefinedRecord(raw));
};

/**
 * 发表评论/回复（兼容旧入参：businessId、replyId、commentContent、phoneId/userId、businessType、storeId）
 * - businessType=1：评价相关，sourceType=1，sourceId 取 replyId/businessId，parentId=0
 * - businessType=2：动态，sourceType=2，sourceId=动态 id，parentId=回复的评论 id 或 0
 */
export const saveComment = (params: any) => {
  return addComment(buildSaveCommentBody(params));
};

// 评价-------------------------------------------------------------------------------------
export const addComment2 = (data: AddCommonCommentBody) => addComment(data);

export const saveComment2 = (params: any) => saveComment(params);

/** 评论列表查询（getListBySourceType） */
export interface CommentListParams {
  pageNum: number;
  pageSize: number;
  /** 来源 id，如动态 id */
  sourceId: number | string;
  /** 1-评价 2-动态 3-打卡 4-二手商品 */
  sourceType: number;
  /** 可选，评论发布者/当前用户 id */
  userId?: number;
}

export const commentList = (params: CommentListParams) => {
  return httpLogin.get(`/alienStore/commonComment/getListBySourceType`, params);
};

//我的动态
export const getUserDynamics = (params: any) => {
  return httpLogin.get(`/alienStore/userDynamics/getUserDynamics`, params);
};
// 点赞动态（新接口）- 表单方式提交
export const likeDynamicNew = (params: {
  userId: string; // 当前用户phoneId
  huifuId: number; // 动态ID
  type: number; // 类型：2表示点赞
}) => {
  const formData = new FormData();
  formData.append("userId", params.userId);
  formData.append("huifuId", String(params.huifuId));
  formData.append("type", String(params.type));
  return httpLogin.post("/alienStore/comment/like", formData);
};
// 取消点赞动态（新接口）- 表单方式提交
export const unlikeDynamicNew = (params: {
  userId: string; // 当前用户phoneId
  huifuId: number; // 动态ID
  type: number; // 类型：2表示点赞
}) => {
  const formData = new FormData();
  formData.append("userId", params.userId);
  formData.append("huifuId", String(params.huifuId));
  formData.append("type", String(params.type));
  return httpLogin.post("/alienStore/comment/cancelLike", formData);
};
//本地草稿
export const getUserDraftDynamics = (params: any) => {
  return httpLogin.get(`/alienStore/userDynamics/getUserDraftDynamics`, params);
};
//我的动态   好友   关注    粉丝
export const getHomePageInfo = (params: any) => {
  return httpLogin.get(`/alienStore/stores/getHomePageInfo`, params);
};

//我的动态   赞过列表
export const getDianZanList = (params: any) => {
  return httpLogin.get(`/alienStore/userDynamics/getDianZanList`, params);
};

//确认分享好友
export const addTransferCount = (params: any) => {
  return httpLogin.get(`/alienStore/userDynamics/addTransferCount`, params);
};
//删除草稿
export const deleteDynamicsById = (params: any) => {
  return httpLogin.get(`/alienStore/userDynamics/deleteDynamicsById`, params);
};

/** 数据字典（如银行名称 type: bankName） */
export const getDict = (params: { dictType: string }) => {
  return httpLogin.get(`/alienStore/dict/getDict`, params);
};

//入驻   根据店铺用户ID查询支付配置（设置收款账号）
export const getPaymentStoreUserId = (params: any) => {
  return httpLogin.get(`/alienStore/store/payment/config/getByStoreUserId`, params);
};

/**
 * 保存微信收款配置（multipart/form-data，仅三字段）
 * storeUserId：店铺用户ID；storeWechatId：商家微信 appid；storeWechatName：商家微信名称
 */
export const saveWechatWithFiles = (params: { storeUserId: string | number; storeWechatId: string; storeWechatName: string }) => {
  const fd = new FormData();
  fd.append("storeUserId", String(params.storeUserId));
  fd.append("storeWechatId", params.storeWechatId.trim());
  fd.append("storeWechatName", params.storeWechatName.trim());
  return httpLogin.post(`/alienStore/store/payment/config/saveWechatByStoreUserId`, fd);
};

/**
 * 保存支付宝收款配置（multipart/form-data，仅三字段）
 * storeUserId：店铺用户ID；storeAliId：商家支付宝 appId；storeAliName：商家支付宝名称
 */
export const saveAlipayWithFiles = (params: { storeUserId: string | number; storeAliId: string; storeAliName: string }) => {
  const fd = new FormData();
  fd.append("storeUserId", String(params.storeUserId));
  fd.append("storeAliId", params.storeAliId.trim());
  fd.append("storeAliName", params.storeAliName.trim());
  return httpLogin.post(`/alienStore/store/payment/config/saveAlipayByStoreUserId`, fd);
};

/**
 * 以 multipart/form-data 保存银行账户收款配置
 * 字段：storeUserId、bankName、bankCardNo（与后端 @RequestParam / Multipart 对齐时可按需改名）
 */
export const saveBankAccountConfig = (params: { storeUserId: string | number; bankName: string; bankCardNo: string }) => {
  const fd = new FormData();
  fd.append("storeUserId", String(params.storeUserId));
  fd.append("bankName", params.bankName);
  fd.append("bankCardNo", params.bankCardNo);
  return httpLogin.post(`/alienStore/store/payment/config/saveBankByStoreUserId`, fd);
};

// 根据手机号获取用户ID
export const getUserByPhone = (params: {
  phone: string; // 手机号
}) => {
  return httpLogin.get(`/alienStore/store/user/getUserByPhone`, params);
};
// 举报动态（新接口）
export const reportUserViolation = (params: {
  dynamicsId: number | string;
  otherReasonContent: string;
  reportContextType: string;
  reportEvidenceImg: string;
  reportedUserId: string | number;
  reportedUserType: number;
  reportingUserId: string | number;
  reportingUserType: number;
  violationType: number;
}) => {
  return httpLogin.post(`/alienStore/user-violation/reporting`, params);
};

// 关注/取消关注用户（新接口）
export const toggleFollowUser = (params: {
  followedId: string | number; // 被关注用户phoneId
  fansId: string; // 当前用户phoneId
  fansType: number; // 2表示关注
}) => {
  return httpLogin.post(`/alienStore/user/addFans`, params);
};

// 获取他人动态列表
export const getUserDynamicsList = (params: {
  myselfPhoneId: string; // 当前登录用户的phoneId
  phoneId: string; // 目标用户的phoneId
  type: number; // 2 表示动态类型
  page: number;
  size: number;
}) => {
  return httpLogin.get(`/alienStore/userDynamics/getUserDynamicsList`, params);
};

// 取消关注用户
export const cancelFollewed = (params: {
  followedId: string; // 被关注用户phoneId
  fansId: string; // 当前用户phoneId
}) => {
  return httpLogin.post(`/alienStore/user/cancelFollewed`, params);
};

// 搜索用户和店铺（根据手机号或昵称）
export const getStoreAndUserByName = (params: {
  page: number;
  size: number;
  phoneId: string; // store_手机号
  userId: string | number;
  searchName: string; // 搜索关键词（手机号或昵称）
}) => {
  return httpLogin.post(`/alienStore/user/getStoreAndUserByName`, params);
};
