import type { MainExamEvaluationVO } from '@/api/main/evaluation/types';

const placeholderImage =
  'data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><rect width="48" height="48" rx="6" fill="%23f2f3f5"/><path d="M14 32l7-8 5 5 4-4 4 7H14z" fill="%23c0c4cc"/><circle cx="19" cy="18" r="3" fill="%23c0c4cc"/></svg>';

export const getImageUrl = (row: MainExamEvaluationVO) => {
  if (row.mainImageUrl) {
    return row.mainImageUrl;
  }
  if (row.imageAlbum) {
    const firstImage = row.imageAlbum
      .split(',')
      .map((item) => item.trim())
      .find((item) => /^https?:\/\//.test(item));
    if (firstImage) {
      return firstImage;
    }
  }
  return placeholderImage;
};

export const getStatusMeta = (status?: string) => {
  if (status === '0') {
    return { label: '启用', type: 'success' as const };
  }
  if (status === '1') {
    return { label: '停用', type: 'info' as const };
  }
  return { label: status || '--', type: 'info' as const };
};

export const formatPrice = (value?: number | string) => {
  if (value === undefined || value === null || value === '') {
    return '--';
  }
  return `￥${value}`;
};

export const formatDateTime = (value?: string) => value || '--';

const toDateValue = (value?: string) => {
  if (!value) {
    return undefined;
  }
  const time = new Date(value).getTime();
  return Number.isNaN(time) ? undefined : time;
};

export const getSaleStatusMeta = (row: MainExamEvaluationVO) => {
  if (row.delFlag === '1') {
    return { label: '删除', type: 'danger' as const };
  }

  const now = Date.now();
  const onTime = toDateValue(row.onTime);
  const downTime = toDateValue(row.downTime);

  if (onTime && now < onTime) {
    return { label: '待上架', type: 'warning' as const };
  }

  if (downTime && now > downTime) {
    return { label: '已下架', type: 'info' as const };
  }

  if ((!onTime || now >= onTime) && (!downTime || now <= downTime)) {
    return { label: '在售', type: 'success' as const };
  }

  return { label: '--', type: 'info' as const };
};
