<script setup lang="ts">
import type {
  MarketingCalendarActivityBarDto,
  MarketingCalendarActivityDto,
  MarketingCalendarDayDto,
} from '#/api/marketing';

import { Empty } from 'ant-design-vue';

defineProps<{
  activities: MarketingCalendarActivityDto[];
  days: MarketingCalendarDayDto[];
  todayDay: number;
}>();

const emit = defineEmits<{
  (event: 'selectActivity', activityId: string): void;
}>();

function buildBarStyle(
  bar: MarketingCalendarActivityBarDto,
  color: string,
  dayCount: number,
) {
  const safeDayCount = Math.max(1, dayCount);
  const start = Math.max(1, bar.startDay);
  const end = Math.max(start, bar.endDay);
  const span = Math.max(1, end - start + 1);
  const left = ((start - 1) / safeDayCount) * 100;
  const width = (span / safeDayCount) * 100;

  return {
    left: `${left}%`,
    width: `${width}%`,
    background: color,
    opacity: bar.isDimmed ? '0.65' : '1',
  };
}

function buildTodayLineStyle(todayDay: number, dayCount: number) {
  const safeDayCount = Math.max(1, dayCount);
  return {
    left: `calc((${todayDay} - 0.5) / ${safeDayCount} * 100%)`,
  };
}
</script>

<template>
  <div class="mc-gantt">
    <div
      class="mc-dates"
      :style="{ gridTemplateColumns: `180px repeat(${days.length || 1}, 1fr)` }"
    >
      <div class="mc-dates-label">活动名称</div>
      <div
        v-for="item in days"
        :key="item.day"
        class="mc-date-cell"
        :class="{ weekend: item.isWeekend, today: item.isToday }"
      >
        {{ item.day }}
      </div>
    </div>

    <div v-if="activities.length === 0" class="mc-empty-row">
      <Empty description="当月暂无活动" />
    </div>

    <div
      v-for="activity in activities"
      :key="activity.activityId"
      class="mc-row"
    >
      <div class="mc-row-label">
        <span
          class="mc-type-dot"
          :style="{ background: activity.color }"
        ></span>
        <span class="mc-row-label-name">{{ activity.name }}</span>
      </div>

      <div
        class="mc-bar-area"
        :style="{ gridTemplateColumns: `repeat(${days.length || 1}, 1fr)` }"
      >
        <button
          v-for="bar in activity.bars"
          :key="bar.barId"
          type="button"
          class="mc-bar"
          :class="{ milestone: bar.isMilestone }"
          :style="buildBarStyle(bar, activity.color, days.length)"
          @click="emit('selectActivity', activity.activityId)"
        >
          {{ bar.label }}
        </button>

        <div
          v-if="todayDay > 0"
          class="mc-today-line"
          :style="buildTodayLineStyle(todayDay, days.length)"
        ></div>
      </div>
    </div>
  </div>
</template>
