<script setup lang="ts">
import { computed } from 'vue';
import { Edit, Flag, User } from '@element-plus/icons-vue';
import { formatDate, getProgressText, getTaskStatusName } from '../shared';
import { useTaskPermissions } from '../composables/use-task-permissions';

defineOptions({ name: 'ProjectExecutionTaskBoardView' });

interface Props {
  data: Api.Project.ProjectTask[];
  loading: boolean;
  statusBoard: Api.Project.StatusBoard | null;
}

const { canEditTask } = useTaskPermissions();

interface Emits {
  (e: 'detail', row: Api.Project.ProjectTask): void;
  (e: 'edit', row: Api.Project.ProjectTask): void;
  (
    e: 'status-action',
    row: Api.Project.ProjectTask,
    action: Api.Project.LifecycleAction<Api.Project.ProjectTaskActionCode> | null
  ): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

const groupedTasks = computed(() => {
  const map = new Map<string, Api.Project.ProjectTask[]>();
  const items = props.statusBoard?.items ?? [];

  items.forEach(item => {
    map.set(item.statusCode, []);
  });

  props.data.forEach(task => {
    const list = map.get(task.statusCode);

    if (list) {
      list.push(task);
    }
  });

  return items.map(item => ({
    statusCode: item.statusCode,
    title: item.statusName,
    count: item.count,
    tasks: map.get(item.statusCode) || []
  }));
});

function getFirstAction(row: Api.Project.ProjectTask) {
  // auto_start 由后端在填工时时自动触发，无手工开始通道；防御后端误下发，前端不渲染按钮
  return row.availableActions.find(item => item.actionCode !== 'auto_start') || null;
}
</script>

<template>
  <ElCard class="task-board-card" body-class="task-board-card__body">
    <ElSkeleton v-if="loading" :rows="6" animated />
    <div v-else class="task-board">
      <section v-for="column in groupedTasks" :key="column.statusCode" class="task-board-column">
        <header class="task-board-column__header">
          <strong>{{ column.title }}</strong>
          <ElTag effect="plain" size="small">{{ column.count }}</ElTag>
        </header>

        <ElScrollbar class="task-board-column__scrollbar">
          <ElEmpty v-if="column.tasks.length === 0" :description="`暂无${column.title}任务`" />
          <template v-else>
            <article
              v-for="task in column.tasks"
              :key="task.id"
              class="task-board-card-item"
              @click="emit('detail', task)"
            >
              <div class="task-board-card-item__top">
                <strong class="task-board-card-item__title">{{ task.taskTitle || '未命名任务' }}</strong>
                <ElTag effect="plain" size="small">{{ getTaskStatusName(task) }}</ElTag>
              </div>

              <div class="task-board-card-item__meta">
                <span>
                  <ElIcon><User /></ElIcon>
                  {{ task.ownerNickname || task.ownerId || '未设置负责人' }}
                </span>
                <span>
                  <ElIcon><Flag /></ElIcon>
                  计划结束 {{ formatDate(task.plannedEndDate) }}
                </span>
              </div>

              <div class="task-board-card-item__progress">
                <span>进度 {{ getProgressText(task.progressRate) }}</span>
                <ElProgress :percentage="task.progressRate" :stroke-width="6" :show-text="false" />
              </div>

              <div class="task-board-card-item__actions" @click.stop>
                <ElButton v-if="canEditTask(task)" size="small" plain :icon="Edit" @click="emit('edit', task)">
                  编辑
                </ElButton>
                <ElButton
                  v-if="getFirstAction(task)"
                  size="small"
                  type="primary"
                  plain
                  @click="emit('status-action', task, getFirstAction(task)!)"
                >
                  {{ getFirstAction(task)!.actionName }}
                </ElButton>
                <ElButton
                  v-else-if="task.availableActions.length === 0 && task.statusCode !== 'cancelled'"
                  size="small"
                  type="primary"
                  plain
                  @click="emit('status-action', task, null)"
                >
                  状态
                </ElButton>
              </div>
            </article>
          </template>
        </ElScrollbar>
      </section>
    </div>
  </ElCard>
</template>

<style scoped lang="scss">
.task-board-card {
  min-height: 0;
  flex: 1;
}

:deep(.task-board-card__body) {
  display: flex;
  min-height: 0;
  height: 100%;
}

.task-board {
  display: grid;
  grid-template-columns: repeat(5, minmax(220px, 1fr));
  gap: 12px;
  width: 100%;
  min-height: 0;
  overflow-x: auto;
}

.task-board-column {
  display: flex;
  min-width: 220px;
  min-height: 0;
  flex-direction: column;
  border: 1px solid rgb(226 232 240 / 92%);
  border-radius: 8px;
  background-color: rgb(248 250 252 / 82%);
}

.task-board-column__header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
  min-height: 42px;
  padding: 10px 12px;
  border-bottom: 1px solid rgb(226 232 240 / 92%);
  color: rgb(15 23 42 / 94%);
}

.task-board-column__scrollbar {
  min-height: 0;
  flex: 1;
  padding: 10px;
}

.task-board-card-item {
  padding: 10px;
  border: 1px solid rgb(226 232 240 / 92%);
  border-radius: 6px;
  margin-bottom: 10px;
  background-color: #fff;
  cursor: pointer;
  transition:
    border-color 0.16s ease,
    box-shadow 0.16s ease;
}

.task-board-card-item:hover {
  border-color: rgb(148 163 184 / 76%);
  box-shadow: 0 6px 18px rgb(15 23 42 / 8%);
}

.task-board-card-item__top {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 8px;
}

.task-board-card-item__title {
  min-width: 0;
  color: rgb(15 23 42 / 94%);
  font-size: 14px;
  line-height: 1.5;
  word-break: break-word;
}

.task-board-card-item__meta {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-top: 10px;
  color: rgb(100 116 139 / 94%);
  font-size: 12px;
}

.task-board-card-item__meta span {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  min-width: 0;
}

.task-board-card-item__progress {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-top: 10px;
  color: rgb(71 85 105 / 96%);
  font-size: 12px;
}

.task-board-card-item__actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  margin-top: 12px;
}

.task-board-card-item__actions :deep(.el-button + .el-button) {
  margin-left: 0;
}
</style>
