<template>
  <div class="two-panel">

    <!-- ── 左栏：公司列表 ── -->
    <aside class="panel-left">
      <div class="left-header">
        <span class="left-title">全部企业</span>
        <span class="left-count">{{ totalOrgs }}</span>
      </div>
      <!-- 查看全部按钮 -->
      <div
        class="org-row org-all"
        :class="{ active: !selectedOrg }"
        @click="clearOrg"
      >
        <div class="org-avatar all-avatar">
          <span>全</span>
        </div>
        <div class="org-meta">
          <span class="org-name">全部职位</span>
          <span class="org-stat">查看所有企业岗位</span>
        </div>
      </div>
      <div class="left-body">
        <template v-if="orgsLoading">
          <div v-for="i in 4" :key="i" class="skeleton-row" />
        </template>
        <template v-else-if="orgsError">
          <div class="state-tip">加载失败，请刷新重试</div>
        </template>
        <template v-else-if="orgs.length === 0">
          <div class="state-tip">暂无公司数据</div>
        </template>
        <template v-else>
          <template v-for="org in orgs" :key="org.id">
            <div
              class="org-row"
              :class="{ active: selectedOrg?.id === org.id }"
              @click="selectOrg(org)"
            >
              <div class="org-avatar parent-avatar">
                <img v-if="org.logo" :src="org.logo" :alt="org.name" />
                <span v-else>{{ org.name[0] }}</span>
              </div>
              <div class="org-meta">
                <span class="org-name">{{ org.name }}</span>
                <span class="org-stat">在招 <em>{{ org.job_count }}</em> 个岗位</span>
              </div>
            </div>
            <div
              v-for="child in org.children"
              :key="child.id"
              class="org-row org-child"
              :class="{ active: selectedOrg?.id === child.id }"
              @click="selectOrg(child)"
            >
              <div class="child-indent">
                <span class="child-line"></span>
              </div>
              <div class="org-avatar child-avatar">
                <img v-if="child.logo" :src="child.logo" :alt="child.name" />
                <span v-else>{{ child.name[0] }}</span>
              </div>
              <div class="org-meta">
                <span class="org-name child-name">{{ child.name }}</span>
                <span class="org-stat">在招 <em>{{ child.job_count }}</em> 个岗位</span>
              </div>
            </div>
          </template>
        </template>
      </div>
    </aside>

    <!-- ── 右栏 ── -->
    <section class="panel-right">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <div class="search-row">
          <div class="search-field">
            <el-input
              v-model="filters.search"
              placeholder="职位名称 / 关键词"
              clearable
              :prefix-icon="SearchIcon"
              @keyup.enter="doSearch"
              @clear="doSearch"
            />
          </div>
          <div class="search-field">
            <el-input
              v-model="filters.location"
              placeholder="城市"
              clearable
              @keyup.enter="doSearch"
              @clear="doSearch"
            />
          </div>
          <div class="search-field">
            <el-input
              v-model="filters.category"
              placeholder="职位类别"
              clearable
              @keyup.enter="doSearch"
              @clear="doSearch"
            />
          </div>
          <div class="search-field">
            <el-select
              v-model="filters.education"
              placeholder="学历要求"
              clearable
              @change="doSearch"
            >
              <el-option value="博士" label="博士" />
              <el-option value="硕士" label="硕士" />
              <el-option value="本科及以下" label="本科及以下" />
            </el-select>
          </div>
          <el-button type="primary" class="search-btn" @click="doSearch">
            搜索
          </el-button>
        </div>
        <div class="search-context" v-if="selectedOrg">
          <span class="context-label">当前企业：</span>
          <el-tag size="small" closable @close="clearOrg">{{ selectedOrg.name }}</el-tag>
        </div>
      </div>

      <!-- 结果头 -->
      <div class="right-header">
        <span class="right-title">
          {{ selectedOrg ? selectedOrg.name + ' · 职位列表' : '全部职位' }}
        </span>
        <span class="right-count">共 {{ totalJobs }} 个</span>
      </div>

      <!-- 职位列表 -->
      <div class="right-body" v-loading="jobsLoading">
        <template v-if="!jobsLoading && !jobsError && jobs.length === 0">
          <div class="state-tip">
            {{ hasFilters ? '未找到匹配的职位，请调整筛选条件' : '暂无职位数据' }}
          </div>
        </template>
        <template v-else-if="jobsError">
          <div class="state-tip">加载失败，请刷新重试</div>
        </template>
        <template v-else>
          <div
            v-for="job in jobs"
            :key="job.id"
            class="job-row"
            @click="goToJobDetail(job)"
          >
            <div class="job-row-top">
              <div class="job-row-title">{{ job.title }}</div>
              <div class="job-row-salary">{{ job.salary }}</div>
            </div>
            <div class="job-row-meta">
              <span class="job-org">{{ job.organization_name || job.organization?.name }}</span>
              <span class="meta-dot">·</span>
              <span>{{ job.location }}</span>
              <span class="meta-dot" v-if="job.education">·</span>
              <span v-if="job.education">{{ job.education }}</span>
            </div>
            <div class="job-row-tags">
              <span class="tag tag-cat" v-if="job.category">{{ job.category }}</span>
              <span class="tag tag-edu" v-if="job.education">{{ job.education }}</span>
              <span class="tag tag-loc">{{ job.location }}</span>
            </div>
          </div>
        </template>
        <!-- 分页 -->
        <div class="pagination-wrap" v-if="totalJobs > pageSize">
          <el-pagination
            layout="prev, pager, next"
            :total="totalJobs"
            :page-size="pageSize"
            v-model:current-page="currentPage"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </section>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { getOrganizations } from '@/api/organizations'
import { getJobs } from '@/api/jobs'
import { Search as SearchIcon } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const auth = useAuthStore()

const orgs = ref([])
const orgsLoading = ref(false)
const orgsError = ref(false)
const selectedOrg = ref(null)

const jobs = ref([])
const jobsLoading = ref(false)
const jobsError = ref(false)
const totalJobs = ref(0)
const currentPage = ref(1)
const pageSize = 20

const filters = reactive({ search: '', location: '', category: '', education: '' })

const totalOrgs = computed(() => {
  return orgs.value.reduce((n, o) => n + 1 + (o.children?.length || 0), 0)
})

const hasFilters = computed(() => {
  return filters.search || filters.location || filters.category || filters.education
})

async function fetchJobs(page = 1) {
  jobsLoading.value = true
  jobsError.value = false
  try {
    const params = { page }
    if (selectedOrg.value) params.organization = selectedOrg.value.id
    if (filters.search) params.search = filters.search
    if (filters.location) params.location = filters.location
    if (filters.category) params.category = filters.category
    if (filters.education) params.education = filters.education
    const { data } = await getJobs(params)
    jobs.value = data.results
    totalJobs.value = data.count
    currentPage.value = page
  } catch (err) {
    console.error('Failed to fetch jobs:', err)
    jobsError.value = true
  } finally {
    jobsLoading.value = false
  }
}

function doSearch() {
  currentPage.value = 1
  fetchJobs(1)
}

function handlePageChange(page) {
  fetchJobs(page)
}

async function selectOrg(org) {
  selectedOrg.value = org
  currentPage.value = 1
  fetchJobs(1)
}

function clearOrg() {
  selectedOrg.value = null
  currentPage.value = 1
  fetchJobs(1)
}

function goToJobDetail(job) {
  router.push({ name: 'JobDetail', params: { id: job.id } })
}

onMounted(async () => {
  orgsLoading.value = true
  try {
    const { data } = await getOrganizations()
    orgs.value = data.results
    const targetOrgId = route.query.org ? Number(route.query.org) : null
    if (targetOrgId) {
      for (const org of orgs.value) {
        if (org.id === targetOrgId) { selectedOrg.value = org; break }
        const child = org.children?.find(c => c.id === targetOrgId)
        if (child) { selectedOrg.value = child; break }
      }
    }
  } catch { orgsError.value = true }
  finally { orgsLoading.value = false }
  fetchJobs(1)
})
</script>

<style scoped>
.two-panel {
  --gold: #B8860B;
  --gold-lt: #D4AF37;
  --dark: #1A1A1A;
  --cream: #F7F8FA;
  --border: #E5E6EB;
  --text: #1D2129;
  --muted: #86909C;

  display: flex;
  height: calc(100vh - 97px);
  min-height: 520px;
  overflow: hidden;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

/* ── 左栏 ── */
.panel-left {
  width: 280px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
  background: var(--dark);
  border-right: 1px solid rgba(255,255,255,0.07);
}
.left-header {
  padding: 16px 18px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid rgba(255,255,255,0.08);
  flex-shrink: 0;
}
.left-title {
  font-size: 13px;
  font-weight: 700;
  color: rgba(255,255,255,0.9);
  letter-spacing: 0.1em;
}
.left-count {
  background: var(--gold);
  color: #fff;
  font-size: 11px;
  font-weight: 700;
  padding: 2px 8px;
  border-radius: 10px;
  min-width: 24px;
  text-align: center;
}
.left-body { flex: 1; overflow-y: auto; }
.left-body::-webkit-scrollbar { width: 4px; }
.left-body::-webkit-scrollbar-track { background: transparent; }
.left-body::-webkit-scrollbar-thumb { background: rgba(255,255,255,0.12); border-radius: 2px; }

/* 全部按钮 */
.org-all {
  border-bottom: 1px solid rgba(255,255,255,0.1) !important;
}
.all-avatar {
  background: linear-gradient(135deg, #4A90D9, #357ABD) !important;
}

/* 公司行 */
.org-row {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px 16px;
  border-left: 3px solid transparent;
  border-bottom: 1px solid rgba(255,255,255,0.05);
  cursor: pointer;
  transition: background 0.15s;
}
.org-row:hover { background: rgba(255,255,255,0.06); }
.org-row.active {
  border-left-color: var(--gold);
  background: rgba(184,134,11,0.1);
}
.org-avatar {
  width: 34px; height: 34px;
  border-radius: 6px;
  background: linear-gradient(135deg, #B8860B, #8B6407);
  display: flex; align-items: center; justify-content: center;
  font-size: 15px; font-weight: 900; color: #fff;
  flex-shrink: 0; overflow: hidden;
}
.org-avatar img { width: 100%; height: 100%; object-fit: cover; }
.child-avatar {
  width: 28px; height: 28px; font-size: 12px;
  background: linear-gradient(135deg, #A67C07, #7D5A05);
}
.org-meta { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.org-name {
  font-size: 13px; font-weight: 600;
  color: rgba(255,255,255,0.88);
  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
}
.child-name { font-size: 12px; color: rgba(255,255,255,0.7); }
.org-row.active .org-name { color: var(--gold-lt); }
.org-stat { font-size: 11px; color: rgba(255,255,255,0.38); }
.org-stat em { font-style: normal; color: var(--gold); font-weight: 700; }
.org-child { padding-left: 12px; background: rgba(0,0,0,0.12); }
.child-indent {
  display: flex; align-items: center; flex-shrink: 0;
  padding-left: 6px;
}
.child-line {
  display: block; width: 10px; height: 1px;
  background: rgba(184,134,11,0.35);
}

/* ── 右栏 ── */
.panel-right {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: var(--cream);
  min-width: 0;
}

/* 搜索栏 */
.search-bar {
  flex-shrink: 0;
  background: #fff;
  padding: 14px 20px;
  border-bottom: 1px solid var(--border);
}
.search-row {
  display: flex;
  gap: 10px;
  align-items: center;
}
.search-field {
  flex: 1;
  min-width: 0;
}
.search-field :deep(.el-input__wrapper),
.search-field :deep(.el-select .el-input__wrapper) {
  border-radius: 6px;
}
.search-btn {
  flex-shrink: 0;
  padding: 8px 24px;
  border-radius: 6px;
  font-weight: 600;
  background: var(--gold) !important;
  border-color: var(--gold) !important;
}
.search-btn:hover {
  background: var(--gold-lt) !important;
  border-color: var(--gold-lt) !important;
}
.search-context {
  margin-top: 10px;
  display: flex;
  align-items: center;
  gap: 6px;
}
.context-label {
  font-size: 12px;
  color: var(--muted);
}

/* 结果头 */
.right-header {
  padding: 12px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid var(--border);
  flex-shrink: 0;
  background: #fff;
}
.right-title { font-size: 14px; font-weight: 600; color: var(--text); }
.right-count {
  font-size: 12px; color: var(--muted);
}

/* 职位列表 */
.right-body { flex: 1; overflow-y: auto; }

.job-row {
  padding: 14px 20px;
  border-bottom: 1px solid var(--border);
  cursor: pointer;
  transition: background 0.15s;
  background: #fff;
}
.job-row:hover { background: #FAFBFC; }
.job-row-top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 6px;
}
.job-row-title {
  font-size: 14px; font-weight: 600;
  color: var(--text);
}
.job-row-salary {
  font-size: 14px; font-weight: 700;
  color: #E63329;
  flex-shrink: 0;
  margin-left: 16px;
}
.job-row-meta {
  font-size: 12px; color: var(--muted); margin-bottom: 8px;
  display: flex; align-items: center; gap: 4px;
}
.job-org { color: var(--gold); font-weight: 500; }
.meta-dot { color: #D9D9D9; }
.job-row-tags { display: flex; gap: 6px; flex-wrap: wrap; }
.tag {
  font-size: 11px; padding: 2px 8px;
  border-radius: 3px; font-weight: 500;
}
.tag-loc { background: #E8EEF8; color: #2C5282; }
.tag-cat { background: #E8F5E9; color: #2E7D32; }
.tag-edu { background: #F3E5F5; color: #7B1FA2; }

/* 分页 */
.pagination-wrap {
  padding: 16px 20px;
  display: flex;
  justify-content: center;
  background: #fff;
  border-top: 1px solid var(--border);
}

/* 空状态 / 骨架 */
.state-tip {
  display: flex; align-items: center; justify-content: center;
  height: 200px;
  color: var(--muted); font-size: 13px;
}
.skeleton-row {
  height: 14px; background: linear-gradient(90deg, #E8E8E8 25%, #F0F0F0 50%, #E8E8E8 75%);
  background-size: 200% 100%;
  border-radius: 3px; margin-bottom: 10px;
  animation: shimmer 1.5s infinite;
}
@keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
</style>
