import dayjs from 'dayjs';
import { getStatusTagType } from '@/constants/status-tag';

export const overtimeApplicationStatusOptions: Array<{
  label: string;
  value: Api.OvertimeApplication.OvertimeApplicationStatusCode;
}> = [
  { label: '待审批', value: 'pending' },
  { label: '已通过', value: 'approved' },
  { label: '已退回', value: 'rejected' }
];

export const overtimeApplicationActionNameMap: Record<Api.OvertimeApplication.OvertimeApplicationActionType, string> = {
  submit: '提交',
  resubmit: '重新提交',
  approve: '通过',
  reject: '退回'
};

export function getOvertimeApplicationStatusLabel(statusCode?: string | null, statusName?: string | null) {
  if (statusName) {
    return statusName;
  }

  return overtimeApplicationStatusOptions.find(item => item.value === statusCode)?.label || statusCode || '--';
}

export function resolveOvertimeApplicationStatusTagType(statusCode?: string | null) {
  return getStatusTagType('overtimeApplication', statusCode);
}

export function getOvertimeApplicationActionLabel(actionType?: string | null) {
  if (!actionType) {
    return '--';
  }

  return (
    overtimeApplicationActionNameMap[actionType as Api.OvertimeApplication.OvertimeApplicationActionType] || actionType
  );
}

export function formatOvertimeDate(value?: string | null) {
  if (!value) {
    return '--';
  }

  const target = dayjs(value);

  return target.isValid() ? target.format('YYYY-MM-DD') : value;
}

export function formatOvertimeDateTime(value?: string | null) {
  if (!value) {
    return '--';
  }

  const target = dayjs(value);

  return target.isValid() ? target.format('YYYY-MM-DD HH:mm:ss') : value;
}

export function formatEmptyText(value?: string | null) {
  return value?.trim() || '--';
}

export function downloadBlob(blob: Blob, fileName: string) {
  const url = URL.createObjectURL(blob);
  const link = document.createElement('a');

  link.href = url;
  link.download = fileName;
  link.click();

  URL.revokeObjectURL(url);
}
