<template>
  <div class="a2-print-page">
    <div class="a2-header">
      <h1>아우디 공식딜러 고진모터스 영업사원 명단</h1>
    </div>

    <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="/img/audi_logo.png" alt="Audi 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 { get } = useApi()
const { getImageUrl } = useImage()

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

// 직책 이름 가져오기
const getPositionName = (positionCode) => {
  const positions = {
    10: '팀장',
    15: '마스터',
    20: '차장',
    30: '과장',
    40: '대리',
    60: '사원'
  }
  return positions[positionCode] || '-'
}

// 팀 이름 가져오기
const getTeamName = (teamId) => {
  if (teamId === 0 || teamId === '0') {
    return '마스터팀'
  }
  return teamId ? `${teamId}팀` : '기타'
}

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

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

    // 지점 초기화
    if (!branches[branchId]) {
      const showroom = showrooms.value.find(s => s.id === branchId)
      branches[branchId] = {
        id: branchId,
        name: showroom ? 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) => {
        // 마스터(15) 먼저
        if (a.position === 15 && b.position !== 15) return -1
        if (a.position !== 15 && b.position === 15) return 1
        // 그 다음 직급 순서대로 (10, 20, 30, 40, 60)
        return a.position - b.position
      })
    })).sort((a, b) => a.id - b.id)
  })).sort((a, b) => a.id - b.id)
})

// 데이터 로드
const loadData = async () => {
  // 전시장 목록 로드
  const { data: branchData } = await get('/branch/list', { per_page: 1000 })
  if (branchData?.success && branchData?.data) {
    showrooms.value = branchData.data.items || []
  }

  // 전체 영업사원 목록 로드
  const { data: salesData } = await get('/staff/sales', { per_page: 1000 })
  if (salesData?.success && salesData?.data) {
    salesList.value = salesData.data.items || []
  }
}

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 {
  .a2-print-page {
    padding: 10mm;
  }

  .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: 10mm;
  }
}
</style>
