import { transformRecordToOption } from '@/utils/common';

/** 项目状态编码与中文标签映射 */
export const projectStatusRecord: Record<Api.Project.ProjectStatusCode, string> = {
  pending: '待开始',
  active: '进行中',
  paused: '已暂停',
  completed: '已完成',
  cancelled: '已取消',
  archived: '已归档'
};

export const projectStatusOptions = transformRecordToOption(projectStatusRecord);

/** 项目状态动作编码与中文标签映射 */
export const projectStatusActionRecord: Record<Api.Project.ProjectStatusActionCode, string> = {
  auto_start: '开始推进',
  pause: '暂停项目',
  resume: '恢复项目',
  complete: '完成项目',
  cancel: '取消项目',
  reopen: '重新开启',
  archive: '归档项目'
};

/** 状态编码来自状态机动态下发，未配置的新状态回退编码本身（展示名优先用后端 statusName） */
export function getProjectStatusLabel(status: string) {
  return (projectStatusRecord as Record<string, string>)[status] ?? status;
}

/** 根据项目状态返回对应的 Tag 类型，用于 ElTag 组件的颜色映射；未配置的新状态回退 info */
export function getProjectStatusTagType(status: string): UI.ThemeColor {
  const statusTagTypeMap: Record<string, UI.ThemeColor> = {
    pending: 'info',
    active: 'success',
    paused: 'warning',
    completed: 'success',
    cancelled: 'info',
    archived: 'info'
  };

  return statusTagTypeMap[status] ?? 'info';
}

/** 判断项目是否可编辑：pending / active / paused 状态允许编辑 */
export function isProjectEditable(status: Api.Project.ProjectStatusCode) {
  return status === 'active' || status === 'pending';
}

/** 判断项目编辑是否受限：paused / completed 状态只能编辑部分字段 */
export function isProjectEditLimited(status: Api.Project.ProjectStatusCode) {
  return status === 'paused' || status === 'completed';
}

/** 根据当前状态获取允许的状态动作列表 */
export function getAllowedProjectStatusActions(
  status: Api.Project.ProjectStatusCode
): Array<Exclude<Api.Project.ProjectStatusActionCode, 'auto_start'>> {
  const actionMap: Record<
    Api.Project.ProjectStatusCode,
    Array<Exclude<Api.Project.ProjectStatusActionCode, 'auto_start'>>
  > = {
    pending: ['cancel'],
    active: ['pause', 'complete', 'cancel'],
    paused: ['resume', 'cancel'],
    completed: ['reopen', 'archive'],
    cancelled: [],
    archived: []
  };

  return actionMap[status];
}

export function getProjectStatusActionLabel(actionCode: Api.Project.ProjectStatusActionCode) {
  return projectStatusActionRecord[actionCode];
}

export function getProjectStatusActionOptions(status: Api.Project.ProjectStatusCode) {
  return getAllowedProjectStatusActions(status).map(actionCode => ({
    value: actionCode,
    label: getProjectStatusActionLabel(actionCode)
  }));
}

/** 判断状态动作是否必须填写原因：resume 和 auto_start 不需要原因 */
export function isProjectActionReasonRequired(actionCode: Api.Project.ProjectStatusActionCode) {
  return actionCode !== 'resume' && actionCode !== 'auto_start';
}
