/**
 * 演出模块 API（商家端 store 接口）
 * 与 group_merchant barPerformance 接口保持一致
 */
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";

const performanceAxios = axios.create({
  baseURL: import.meta.env.VITE_API_URL_STORE as string,
  timeout: ResultEnum.TIMEOUT as number,
  withCredentials: true
});

performanceAxios.interceptors.request.use(
  config => {
    const userStore = useUserStore();
    if (config.headers) {
      (config.headers as any).Authorization = userStore.token;
    }
    return config;
  },
  error => Promise.reject(error)
);

performanceAxios.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: "已驳回"
};

// 在线状态：0=下线 1=上线
export const ONLINE_STATUS_LABEL: Record<number, string> = {
  0: "下线",
  1: "上线"
};

// 演出类型：0=特邀演出 1=常规演出
export const PERFORMANCE_TYPE_LABEL: Record<number, string> = {
  0: "特邀演出",
  1: "常规演出"
};

// 演出频次："0"=单次 "1"=每天定时进行 "2"=每周定时进行
export const FREQUENCY_LABEL: Record<string, string> = {
  "0": "单次",
  "1": "每天定时进行",
  "2": "每周定时进行"
};

export interface PerformanceRow {
  id: number | string;
  name: string;
  performanceType: number;
  performanceTypeLabel: string;
  frequency: string;
  frequencyLabel: string;
  shelfStatus: number;
  onlineStatusLabel: string;
  auditStatus: number | null;
  auditStatusLabel: string;
  submitTime: string;
  auditReason: string;
}

export interface PerformanceListQuery {
  page?: number;
  pageNum?: number;
  pageSize?: number;
  size?: number;
  storeId?: string | number;
  performanceName?: string;
  reviewStatus?: number;
  onlineStatus?: number;
  performanceType?: number;
  submitTimeStart?: string;
  submitTimeEnd?: string;
  /** 演出开始时间（起止时间筛选） 格式 YYYY-MM-DD HH:mm:ss */
  startCreatedTime?: string;
  /** 演出结束时间（起止时间筛选） 格式 YYYY-MM-DD HH:mm:ss */
  endCreatedTime?: string;
}

function transformListItem(item: any): PerformanceRow {
  const performanceType = item.performanceType ?? 0;
  const frequency = item.performanceFrequency ?? item.frequency ?? "0";
  const auditStatus = item.reviewStatus ?? item.statusReview ?? item.auditStatus ?? 0;
  const shelfStatus = item.onlineStatus ?? item.shelfStatus ?? 0;
  return {
    id: item.id,
    name: item.performanceName ?? item.name ?? "",
    performanceType: Number(performanceType),
    performanceTypeLabel: PERFORMANCE_TYPE_LABEL[Number(performanceType)] ?? "--",
    frequency: String(frequency),
    frequencyLabel: FREQUENCY_LABEL[String(frequency)] ?? "单次",
    shelfStatus: Number(shelfStatus),
    onlineStatusLabel: shelfStatus === 1 ? "上线" : "--",
    auditStatus,
    auditStatusLabel: AUDIT_STATUS_LABEL[auditStatus] ?? "--",
    submitTime: item.createdTime ?? item.submitTime ?? item.createTime ?? "--",
    auditReason: item.rejectReason ?? item.rejectionReason ?? item.auditReason ?? ""
  };
}

/** 分页查询演出列表 */
export const getPerformancePage = (params: PerformanceListQuery) => {
  const storeId = params.storeId ?? (localGet("createdId") as string) ?? "";
  const page = params.page ?? params.pageNum ?? 1;
  const size = params.size ?? params.pageSize ?? 10;
  const query: any = {
    page,
    size,
    storeId
  };
  if (params.performanceName != null && params.performanceName !== "") query.performanceName = params.performanceName;
  if (params.reviewStatus !== undefined && params.reviewStatus !== null) query.reviewStatus = params.reviewStatus;
  if (params.onlineStatus !== undefined && params.onlineStatus !== null) query.onlineStatus = params.onlineStatus;
  if (params.performanceType !== undefined && params.performanceType !== null) query.performanceType = params.performanceType;
  if (params.submitTimeStart) query.submitTimeStart = params.submitTimeStart;
  if (params.submitTimeEnd) query.submitTimeEnd = params.submitTimeEnd;
  if (params.startCreatedTime) query.startCreatedTime = params.startCreatedTime;
  if (params.endCreatedTime) query.endCreatedTime = params.endCreatedTime;

  return performanceAxios.get<any>(PORT_NONE + "/store/bar/performance/listByStoreId", { params: query });
};

/** 演出列表接口返回转 ProTable 所需 { list, total } */
export const transformPerformanceListResponse = (payload: any) => {
  const records = payload?.records ?? payload?.list ?? (Array.isArray(payload) ? payload : []);
  const total = payload?.total ?? records.length;
  return {
    list: records.map((item: any) => transformListItem(item)),
    total
  };
};

/** 演出详情 */
export const getPerformanceDetail = (id: number | string) => {
  return performanceAxios.get<any>(PORT_NONE + "/store/bar/performance/detail", { params: { id } });
};

/** 新增/更新演出 */
export const saveOrUpdatePerformance = (data: any) => {
  return performanceAxios.post(PORT_NONE + "/store/bar/performance/saveOrUpdate", data);
};

/** 删除演出 */
export const deletePerformance = (id: number | string) => {
  return performanceAxios.delete(PORT_NONE + "/store/bar/performance/delete", { params: { id } });
};

/** 设置上线状态 */
export const setPerformanceOnlineStatus = (id: number | string, onlineStatus: number) => {
  return performanceAxios.post(PORT_NONE + "/store/bar/performance/setOnlineStatus", { id, onlineStatus });
};

/** 表演嘉宾列表（员工/嘉宾可选列表，用于新建编辑时选择） */
export const getGuestListPage = (params: {
  pageNum?: number;
  pageSize?: number;
  onlineStatus?: number;
  status?: number;
  storeId?: string;
  staffName?: string;
}) => {
  const storeId = params.storeId ?? (localGet("createdId") as string) ?? "";
  const pageNum = params.pageNum ?? 1;
  const pageSize = params.pageSize ?? 20;
  const onlineStatus = params.onlineStatus ?? 0;
  const status = params.status ?? 1;
  const query: any = { pageNum, pageSize, storeId, onlineStatus, status };
  if (params.staffName) query.staffName = params.staffName;
  return performanceAxios.get<any>(PORT_NONE + "/storeStaffConfig/getStaffConfigList", { params: query });
};

/** 周几文本与数字映射 */
const WEEKDAY_MAP: Record<string, number> = { 周一: 0, 周二: 1, 周三: 2, 周四: 3, 周五: 4, 周六: 5, 周日: 6 };
const WEEKDAY_KEYS = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"];

/**
 * 将表单数据转为后端 saveOrUpdate 所需格式（与商家端 dataConverter 一致）
 */
export function buildPerformanceBackendPayload(form: any, storeId?: string): any {
  const sid = storeId ?? (localGet("createdId") as string) ?? "";
  const payload: any = {
    storeId: sid,
    performanceName: form.name ?? "",
    performancePoster: Array.isArray(form.posterUrls) ? form.posterUrls[0] : (form.imgUrl ?? ""),
    performanceType: form.performanceType === "特邀演出" ? 0 : 1,
    performanceFrequency: form.frequency === "单次" ? "0" : form.frequency === "每天定时进行" ? "1" : "2",
    performanceStyle: Array.isArray(form.style) ? form.style.join(",") : form.style || "",
    performanceContent: form.detailDescription ?? "",
    performanceNotice: form.notes ?? "",
    performanceDetail: Array.isArray(form.detailPicUrl) ? form.detailPicUrl.slice(0, 9).join(",") : (form.detailPicUrl ?? ""),
    staffConfigIds:
      Array.isArray(form.guests) && form.guests.length
        ? form.guests
            .map((g: any) => (typeof g === "object" ? g.id : g))
            .filter(Boolean)
            .join(",")
        : ""
  };
  if (form.id) payload.id = form.id;

  const fmtDt = (date: string, time: string) => (date && time ? `${date} ${time}:00` : "");

  if (payload.performanceFrequency === "0") {
    const pt = form.performanceTime || {};
    payload.singleStartDatetime = fmtDt(pt.startDate, pt.startTime);
    payload.singleEndDatetime = fmtDt(pt.endDate, pt.endTime);
    payload.performanceWeek = "";
  } else if (payload.performanceFrequency === "1") {
    const dr = form.dailyPerformanceDateRange || {};
    const tr = form.dailyPerformanceTimeRange || {};
    payload.dailyStartDate = dr.start ?? "";
    payload.dailyEndDate = dr.end ?? "";
    payload.singleStartDatetime = tr.start ? `2000-01-01 ${tr.start}:00` : "";
    payload.singleEndDatetime = tr.end ? `2000-01-01 ${tr.end}:00` : "";
    payload.performanceWeek = "";
  } else {
    const dr = form.weeklyPerformanceDateRange || {};
    const tr = form.weeklyPerformanceTimeRange || {};
    const weekdays = form.weeklyPerformanceWeekdays || [];
    payload.dailyStartDate = dr.start ?? "";
    payload.dailyEndDate = dr.end ?? "";
    payload.singleStartDatetime = tr.start ? `2000-01-01 ${tr.start}:00` : "";
    payload.singleEndDatetime = tr.end ? `2000-01-01 ${tr.end}:00` : "";
    payload.performanceWeek = weekdays
      .map((d: string) => WEEKDAY_MAP[d])
      .filter((n: number) => n !== undefined)
      .sort((a: number, b: number) => a - b)
      .join(",");
  }
  return payload;
}

/** 后端详情转表单模型（用于编辑回显） */
export function detailToFormModel(d: any): Record<string, any> {
  if (!d) return getDefaultFormModel();
  const freq = d.performanceFrequency ?? "0";
  const typeLabel = PERFORMANCE_TYPE_LABEL[Number(d.performanceType)] ?? "特邀演出";
  const freqLabel = FREQUENCY_LABEL[String(freq)] ?? "单次";
  const style = d.performanceStyle
    ? String(d.performanceStyle)
        .split(",")
        .map((s: string) => s.trim())
        .filter(Boolean)
    : [];
  const detailPicUrl = d.performanceDetail
    ? String(d.performanceDetail)
        .split(",")
        .map((u: string) => u.trim())
        .filter(Boolean)
    : [];
  let guests: any[] = [];
  if (d.performers && Array.isArray(d.performers)) {
    guests = d.performers.map((p: any) => ({
      id: p.id,
      name: p.name ?? "",
      nickname: p.name ?? "",
      avatar: p.avatar ?? "",
      position: p.style ?? p.tag ?? ""
    }));
  } else if (d.staffConfigIds) {
    guests = String(d.staffConfigIds)
      .split(",")
      .map(id => ({ id: id.trim(), name: "", position: "" }))
      .filter((g: any) => g.id);
  }
  const model: Record<string, any> = {
    id: d.id,
    name: d.performanceName ?? "",
    imgUrl: d.performancePoster ?? "",
    posterUrls: d.performancePoster ? [d.performancePoster] : [],
    style,
    performanceType: typeLabel,
    frequency: freqLabel,
    detailDescription: d.performanceContent ?? "",
    notes: d.performanceNotice ?? "",
    detailPicUrl,
    guests
  };
  if (freq === "0") {
    let startDate = "",
      startTime = "",
      endDate = "",
      endTime = "";
    if (d.singleStartDatetime) {
      const [sd, st] = String(d.singleStartDatetime).split(" ");
      startDate = sd ?? "";
      startTime = st ? st.substring(0, 5) : "";
    }
    if (d.singleEndDatetime) {
      const [ed, et] = String(d.singleEndDatetime).split(" ");
      endDate = ed ?? "";
      endTime = et ? et.substring(0, 5) : "";
    }
    model.performanceTime = { startDate, startTime, endDate, endTime };
  } else if (freq === "1") {
    model.dailyPerformanceDateRange = { start: d.dailyStartDate ?? "", end: d.dailyEndDate ?? "" };
    let startTime = "",
      endTime = "";
    if (d.singleStartDatetime) startTime = String(d.singleStartDatetime).split(" ")[1]?.substring(0, 5) ?? "";
    if (d.singleEndDatetime) endTime = String(d.singleEndDatetime).split(" ")[1]?.substring(0, 5) ?? "";
    model.dailyPerformanceTimeRange = { start: startTime, end: endTime };
  } else {
    model.weeklyPerformanceDateRange = { start: d.dailyStartDate ?? "", end: d.dailyEndDate ?? "" };
    let startTime = "",
      endTime = "";
    if (d.singleStartDatetime) startTime = String(d.singleStartDatetime).split(" ")[1]?.substring(0, 5) ?? "";
    if (d.singleEndDatetime) endTime = String(d.singleEndDatetime).split(" ")[1]?.substring(0, 5) ?? "";
    model.weeklyPerformanceTimeRange = { start: startTime, end: endTime };
    const weekStr = d.performanceWeek ?? "";
    const nums = weekStr
      ? weekStr
          .split(",")
          .map((n: string) => parseInt(n.trim(), 10))
          .filter((n: number) => !isNaN(n))
      : [];
    const weekLabels: Record<number, string> = { 0: "周一", 1: "周二", 2: "周三", 3: "周四", 4: "周五", 5: "周六", 6: "周日" };
    model.weeklyPerformanceWeekdays = nums.map((n: number) => weekLabels[n]).filter(Boolean);
  }
  return model;
}

export function getDefaultFormModel(): Record<string, any> {
  return {
    name: "",
    imgUrl: "",
    posterUrls: [],
    style: ["民谣"],
    performanceType: "特邀演出",
    frequency: "单次",
    performanceTime: { startDate: "", startTime: "", endDate: "", endTime: "" },
    dailyPerformanceDateRange: { start: "", end: "" },
    dailyPerformanceTimeRange: { start: "", end: "" },
    weeklyPerformanceWeekdays: [],
    weeklyPerformanceDateRange: { start: "", end: "" },
    weeklyPerformanceTimeRange: { start: "", end: "" },
    detailPicUrl: [],
    detailDescription: "",
    notes: "",
    guests: []
  };
}
