<template>
  <div class="a2-print-page">
    <div v-for="branch in groupedData" :key="branch.id" class="branch-section">
      <h2 class="branch-name">{{ branch.name }}</h2>

      <div v-for="team in branch.teams" :key="team.id" class="team-section">
        <h3 class="team-name">{{ team.name }}</h3>

        <div class="staff-grid">
          <div v-for="staff in team.staff" :key="staff.id" class="staff-card">
            <div class="staff-photo">
              <img
                v-if="staff.photo_url"
                :src="getImageUrl(staff.photo_url)"
                :alt="staff.name"
              />
              <img
                v-else
                :src="getMediaUrl('/img/FORDKOREA_logo.png')"
                alt="FORDKOREA Logo"
                class="logo-placeholder"
              />
            </div>
            <div class="staff-info">
              <div class="staff-position">
                {{ getPositionName(staff.position) }} {{ staff.name }}
              </div>
              <div class="staff-phone">{{ staff.direct_phone || staff.main_phone }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
  import { ref, onMounted, computed } from "vue";

  definePageMeta({
    layout: false,
  });

  const config = useRuntimeConfig();
  const { get } = useApi();
  const { getMediaUrl } = useImage();
  const { getImageUrl } = useImage();
  const { getTeamName, getPositionName } = useSalesData();

  const salesList = ref([]);
  const showrooms = ref([]);

  // 지점별, 팀별로 그룹화
  const groupedData = computed(() => {
    const branches = {};

    salesList.value.forEach((staff) => {
      const branchId = staff.showroom || 0;
      const teamId = staff.team ?? 0;

      // 지점 정보 찾기
      const showroom = showrooms.value.find((s) => s.id === branchId);

      // 지점이 없으면 건너뛰기 (미지정 제외)
      if (!showroom) {
        return;
      }

      // 지점 초기화
      if (!branches[branchId]) {
        branches[branchId] = {
          id: branchId,
          name: showroom.name,
          teams: {},
        };
      }

      // 팀 초기화
      if (!branches[branchId].teams[teamId]) {
        branches[branchId].teams[teamId] = {
          id: teamId,
          name: getTeamName(teamId),
          staff: [],
        };
      }

      // 직원 추가
      branches[branchId].teams[teamId].staff.push(staff);
    });

    // 배열로 변환 및 정렬
    return Object.values(branches)
      .map((branch) => ({
        ...branch,
        teams: Object.values(branch.teams)
          .map((team) => ({
            ...team,
            staff: team.staff.sort((a, b) => {
              // company가 'w'인 경우: position 내림차순
              // 그 외: position 오름차순
              if (a.position !== b.position) {
                if (config.public.company === "w") {
                  return b.position - a.position; // 내림차순
                } else {
                  return a.position - b.position; // 오름차순
                }
              }
              // 2. 같은 직급이면 display_order 오름차순
              return a.display_order - b.display_order;
            }),
          }))
          .sort((a, b) => a.id - b.id),
      }))
      .sort((a, b) => a.id - b.id);
  });

  // 데이터 로드
  const loadData = async () => {
    // 전시장 목록 로드 (is_active=1인 활성화된 지점만)
    const { data: branchData } = await get("/branch/list", {
      params: { per_page: 1000, is_active: 1 },
    });
    console.log("[PrintA2] 지점 데이터:", branchData);
    if (branchData?.success && branchData?.data) {
      showrooms.value = branchData.data.items || [];
    }

    // 전체 영업사원 목록 로드 (is_act=1인 활성화된 영업사원만)
    const { data: salesData } = await get("/staff/sales", {
      params: { per_page: 1000, is_act: 1 },
    });
    console.log("[PrintA2] 영업사원 데이터:", salesData);
    if (salesData?.success && salesData?.data) {
      salesList.value = salesData.data.items || [];
    }
    console.log("[PrintA2] 최종 salesList (활성화만):", salesList.value);
  };

  onMounted(async () => {
    await loadData();
    // 데이터 로드 후 자동 출력
    setTimeout(() => {
      window.print();
    }, 500);
  });
</script>

<style scoped>
  .a2-print-page {
    padding: 20px;
    background: white;
  }

  .a2-header {
    text-align: center;
    margin-bottom: 30px;
    padding-bottom: 20px;
    border-bottom: 3px solid #000;
  }

  .a2-header h1 {
    font-size: 28px;
    font-weight: bold;
    margin: 0;
  }

  .branch-section {
    margin-bottom: 40px;
    page-break-inside: avoid;
  }

  .branch-name {
    font-size: 24px;
    font-weight: bold;
    color: #333;
    margin-bottom: 20px;
    padding: 10px;
    background: #f0f0f0;
    border-left: 5px solid #000;
  }

  .team-section {
    margin-bottom: 30px;
    page-break-inside: avoid;
  }

  .team-name {
    font-size: 20px;
    font-weight: bold;
    color: #555;
    margin-bottom: 15px;
    padding: 8px;
    background: #f8f8f8;
    border-left: 3px solid #666;
  }

  .staff-grid {
    display: grid;
    grid-template-columns: repeat(8, 1fr);
    gap: 20px;
    margin-bottom: 20px;
  }

  .staff-card {
    border: 1px solid #ddd;
    padding: 15px;
    text-align: center;
    background: white;
    page-break-inside: avoid;
  }

  .staff-photo {
    width: 100%;
    height: 150px;
    margin-bottom: 10px;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #ddd;
  }

  .staff-photo img {
    max-width: 100%;
    max-height: 100%;
    object-fit: cover;
  }

  .staff-photo .logo-placeholder {
    max-width: 80%;
    max-height: 80%;
    object-fit: contain;
  }

  .staff-info {
    margin-top: 10px;
  }

  .staff-position {
    font-size: 16px;
    font-weight: bold;
    color: #333;
    margin-bottom: 5px;
  }

  .staff-phone {
    font-size: 13px;
    color: #888;
  }

  /* 인쇄 스타일 */
  @media print {
    * {
      margin: 0;
      padding: 0;
    }

    body {
      margin: 0 !important;
      padding: 0 !important;
    }

    .a2-print-page {
      padding: 5mm;
      margin: 0;
    }

    .a2-header {
      margin-top: 0;
      padding-top: 0;
      margin-bottom: 20px;
    }

    .staff-grid {
      grid-template-columns: repeat(8, 1fr);
      gap: 10px;
    }

    .staff-card {
      padding: 10px;
    }

    .staff-photo {
      height: 120px;
    }

    .staff-position {
      font-size: 14px;
    }

    .staff-phone {
      font-size: 11px;
    }

    @page {
      size: A2;
      margin: 5mm;
    }
  }
</style>
