import emptyImage from "@/assets/nodata.svg";

export enum MailStatus {
  PENDING = 0,
  SENT = 1,
  FAILED = 2,
}

export interface Mail {
  id: number;
  orderNumber: string;
  recipient: string;
  content: string;
  sendTime: string;
  submitTime: string;
  status: MailStatus;
  price: number;
  isNew: boolean;
}

export const MAIL_DETAIL_PAGE = "/pages/mailbox/detail";

export const MAIL_TABS = [
  { name: "全部" },
  { name: "待发送" },
  { name: "已发送" },
  { name: "发送失败" },
];

export const MAIL_EMPTY_IMAGE = emptyImage;

export const MAIL_STATUS_META: Record<MailStatus, { text: string; className: string }> = {
  [MailStatus.PENDING]: {
    text: "待发送",
    className: "status-pending",
  },
  [MailStatus.SENT]: {
    text: "已发送",
    className: "status-sent",
  },
  [MailStatus.FAILED]: {
    text: "发送失败",
    className: "status-failed",
  },
};

export const MOCK_MAIL_CONTENTS = [
  "有些话想认真说一次，不打扰你，只希望你知道我的歉意。",
  "之前没有照顾好你的感受，对不起。愿你之后都能轻松一点。",
  "如果还有机会，我想把没说好的话认真补上。",
  "这条短信只是想把心意说清楚，不给你压力。",
];

export const MOCK_PHONE_PREFIXES = ["135", "136", "138", "151", "166", "171", "188", "199"];

export const maskRecipient = (recipient: string): string => {
  if (!recipient) return "";

  const value = String(recipient).trim();

  if (value.length <= 7) {
    return value.replace(/^(.{2}).*(.{1})$/, "$1****$2");
  }

  return `${value.slice(0, 3)}****${value.slice(-4)}`;
};

export const formatMailTime = (timeString: string): string => {
  if (!timeString || typeof timeString !== "string") {
    return String(timeString || "");
  }

  const date = new Date(timeString.replace(" ", "T"));

  if (Number.isNaN(date.getTime())) {
    return timeString;
  }

  const now = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");

  if (year === now.getFullYear()) {
    return `${month}月${day}日 ${hours}:${minutes}`;
  }

  return `${year}年${month}月${day}日 ${hours}:${minutes}`;
};

export const serializeMail = (mail: Mail): string => encodeURIComponent(JSON.stringify(mail));

export const deserializeMail = (payload?: string): Mail | null => {
  if (!payload) return null;

  try {
    return JSON.parse(decodeURIComponent(payload)) as Mail;
  } catch (error) {
    console.error("解析短信详情失败", error);
    return null;
  }
};
