import { type Ref, computed, markRaw } from 'vue';
import { useAuthStore } from '@/store/modules/auth';
import { canReportTaskWorklog } from '../shared';
import { useTaskPermissions } from './use-task-permissions';
import IconMdiCheckCircleOutline from '~icons/mdi/check-circle-outline';
import IconMdiClipboardEditOutline from '~icons/mdi/clipboard-edit-outline';
import IconMdiCloseCircleOutline from '~icons/mdi/close-circle-outline';
import IconMdiDeleteOutline from '~icons/mdi/delete-outline';
import IconMdiPause from '~icons/mdi/pause';
import IconMdiPencilOutline from '~icons/mdi/pencil-outline';
import IconMdiRestart from '~icons/mdi/restart';
import IconMdiSync from '~icons/mdi/sync';

export interface TaskAction {
  key: string;
  tooltip: string;
  icon: object;
  type: 'primary' | 'success' | 'danger' | 'warning';
  onClick: () => void;
}

export interface TaskActionEmits {
  edit: (row: Api.Project.ProjectTask) => void;
  report: (row: Api.Project.ProjectTask) => void;
  remove: (row: Api.Project.ProjectTask) => void;
  statusAction: (
    row: Api.Project.ProjectTask,
    action: Api.Project.LifecycleAction<Api.Project.ProjectTaskActionCode>
  ) => void;
}

const STATUS_ACTION_ICON_MAP: Record<string, object> = {
  pause: markRaw(IconMdiPause),
  complete: markRaw(IconMdiCheckCircleOutline),
  resume: markRaw(IconMdiRestart),
  cancel: markRaw(IconMdiCloseCircleOutline)
};

// 状态推进按钮 type 映射（对齐执行 execution-list-panel.vue 同源语义）：
// cancel 破坏性=红，pause 中断=橙，complete 完结=绿，resume 主动作=蓝
const STATUS_ACTION_TYPE_MAP: Record<string, TaskAction['type']> = {
  cancel: 'danger',
  pause: 'warning',
  complete: 'success',
  resume: 'primary'
};

// 同一状态下多个推进按钮的展示顺序，与执行侧保持一致：暂停 → 取消 → 完成 → 恢复
const STATUS_ACTION_ORDER: Record<string, number> = {
  pause: 1,
  cancel: 2,
  complete: 3,
  resume: 4
};

/**
 * 任务行操作按钮的集中装配。
 *
 * 表格操作列与看板卡片操作区共用同一份语义：填报 / 编辑 / 删除 / 状态推进按钮，
 * 含 auto_start 过滤、complete 进度 100% 兜底、按钮排序与 icon/type 映射。
 *
 * dataRef 用于填报按钮的"叶子"判定（canReportTaskWorklog 需要全量行集合）。
 */
export function useTaskActions(dataRef: Ref<Api.Project.ProjectTask[]>, emits: TaskActionEmits) {
  const authStore = useAuthStore();
  const currentUserId = computed(() => authStore.userInfo.userId || '');
  const { canEditTask, canDeleteTask, canReportTaskWorklog: hasReportWorklogPermission } = useTaskPermissions();

  function createActions(row: Api.Project.ProjectTask): TaskAction[] {
    const actions: TaskAction[] = [];

    // 填报：权限码门槛 AND 业务规则（叶子/身份/状态）双重判定
    if (hasReportWorklogPermission() && canReportTaskWorklog(row, dataRef.value, currentUserId.value)) {
      actions.push({
        key: 'report',
        tooltip: '填报',
        icon: markRaw(IconMdiClipboardEditOutline),
        type: 'primary',
        onClick: () => emits.report(row)
      });
    }

    if (canEditTask(row)) {
      actions.push({
        key: 'edit',
        tooltip: '编辑',
        icon: markRaw(IconMdiPencilOutline),
        type: 'primary',
        onClick: () => emits.edit(row)
      });
    }

    if (canDeleteTask(row)) {
      actions.push({
        key: 'delete',
        tooltip: '删除',
        icon: markRaw(IconMdiDeleteOutline),
        type: 'danger',
        onClick: () => emits.remove(row)
      });
    }

    if (!row.availableActions.length) {
      return actions;
    }

    // 排序：暂停 → 取消 → 完成 → 恢复（对齐执行）
    const sortedActions = [...row.availableActions].sort(
      (a, b) => (STATUS_ACTION_ORDER[a.actionCode] ?? 99) - (STATUS_ACTION_ORDER[b.actionCode] ?? 99)
    );

    sortedActions.forEach(action => {
      // auto_start 由后端在填工时时自动触发，无手工开始通道；防御后端误下发，前端不渲染
      if (action.actionCode === 'auto_start') {
        return;
      }
      // 完成任务至少要求任务进度达到 100%；父级提交入口仍保留同样兜底校验
      if (action.actionCode === 'complete' && row.progressRate < 100) {
        return;
      }
      actions.push({
        key: `status-${action.actionCode}`,
        tooltip: action.actionName,
        icon: markRaw(STATUS_ACTION_ICON_MAP[action.actionCode] ?? IconMdiSync),
        type: STATUS_ACTION_TYPE_MAP[action.actionCode] ?? 'primary',
        onClick: () => emits.statusAction(row, action)
      });
    });

    return actions;
  }

  return { createActions };
}
