<template>
  <div>
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">
      <h2>职位管理</h2>
      <div style="display:flex;gap:8px">
        <el-button @click="handleDownloadTemplate">
          <el-icon style="margin-right:4px"><Download /></el-icon>下载模板
        </el-button>
        <el-upload
          ref="uploadRef"
          :auto-upload="false"
          :show-file-list="false"
          accept=".xlsx,.xls"
          :on-change="handleImportExcel"
        >
          <el-button type="success">
            <el-icon style="margin-right:4px"><Upload /></el-icon>导入Excel
          </el-button>
        </el-upload>
        <el-button type="primary" @click="openDialog()">发布职位</el-button>
      </div>
    </div>
    <el-table :data="jobs" v-loading="loading" border>
      <el-table-column label="职位名称">
        <template #default="{ row }">
          <el-button type="primary" link @click="$router.push({ name: 'JobDetail', params: { id: row.id } })">
            {{ row.title }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="organization_name" label="所属公司" />
      <el-table-column prop="location" label="地点" />
      <el-table-column prop="salary" label="薪资" />
      <el-table-column label="发布时间" width="160">
        <template #default="{ row }">
          {{ row.created_at ? new Date(row.created_at).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' }) : '-' }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态">
        <template #default="{ row }">
          <el-tag :type="row.status === 'published' ? 'success' : row.status === 'draft' ? 'info' : 'danger'">
            {{ { draft:'草稿', published:'已发布', closed:'已关闭' }[row.status] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button size="small" @click="openDialog(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top: 16px; text-align: right;">
      <el-pagination
        v-model:current-page="currentPage"
        :page-size="pageSize"
        :total="total"
        @current-change="handlePageChange"
        layout="total, prev, pager, next, jumper"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="editingJob ? '编辑职位' : '发布职位'" width="600px">
      <el-form :model="form" label-width="90px">
        <!-- 超管才需要选择公司 -->
        <el-form-item v-if="auth.isSuperAdmin" label="所属公司">
          <el-select v-model="form.organization_id" placeholder="请选择公司" style="width:100%" filterable>
            <template v-for="org in allOrgs" :key="org.id">
              <el-option :label="org.name" :value="org.id" />
              <el-option
                v-for="child in org.children"
                :key="child.id"
                :label="'└ ' + child.name"
                :value="child.id"
              />
            </template>
          </el-select>
        </el-form-item>
        <el-form-item label="职位名称"><el-input v-model="form.title" /></el-form-item>
        <el-form-item label="职位类别"><el-input v-model="form.category" /></el-form-item>
        <el-form-item label="学历要求">
          <el-select v-model="form.education" placeholder="请选择学历要求" style="width:100%">
            <el-option value="博士" label="博士" />
            <el-option value="硕士" label="硕士" />
            <el-option value="本科及以下" label="本科及以下" />
          </el-select>
        </el-form-item>
        <el-form-item label="工作地点"><el-input v-model="form.location" /></el-form-item>
        <el-form-item label="薪资范围"><el-input v-model="form.salary" /></el-form-item>
        <el-form-item label="职位描述"><el-input v-model="form.description" type="textarea" :rows="5" /></el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status">
            <el-option value="draft" label="草稿" />
            <el-option value="published" label="立即发布" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Download, Upload } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { manageJobs, getManageJob, createJob, updateJob, deleteJob, downloadJobTemplate, importJobsExcel } from '@/api/jobs'
import { getOrganizations } from '@/api/organizations'
import { ElMessage, ElMessageBox } from 'element-plus'

const auth = useAuthStore()
const jobs = ref([])
const allOrgs = ref([])
const loading = ref(false)
const saving = ref(false)
const dialogVisible = ref(false)
const editingJob = ref(null)
const form = reactive({
  title: '', category: '', education: '本科及以下', location: '', salary: '',
  description: '', status: 'draft', organization_id: null
})
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

const fetchJobs = async (page = 1) => {
  loading.value = true
  try {
    const { data } = await manageJobs(page)
    jobs.value = data.results
    total.value = data.count
    currentPage.value = page
  } catch (error) {
    ElMessage.error('加载职位列表失败，请重试')
  } finally {
    loading.value = false
  }
}

const fetchOrgs = async () => {
  const { data } = await getOrganizations()
  allOrgs.value = data.results
}

async function openDialog(job = null) {
  if (job) {
    // 从详情接口获取完整数据（含 description）
    try {
      const { data } = await getManageJob(job.id)
      editingJob.value = data
      Object.assign(form, {
        title: data.title,
        category: data.category,
        education: data.education || '本科及以下',
        location: data.location,
        salary: data.salary,
        description: data.description || '',
        status: data.status,
        organization_id: data.organization?.id ?? data.organization ?? null,
      })
    } catch {
      ElMessage.error('获取职位详情失败')
      return
    }
  } else {
    editingJob.value = null
    Object.assign(form, {
      title: '', category: '', education: '本科及以下', location: '', salary: '',
      description: '', status: 'draft', organization_id: null
    })
  }
  dialogVisible.value = true
}

function handlePageChange(newPage) {
  fetchJobs(newPage)
}

async function handleSave() {
  const isEdit = !!editingJob.value
  if (auth.isSuperAdmin && !isEdit && !form.organization_id) {
    return ElMessage.warning('请选择所属公司')
  }
  saving.value = true
  try {
    const payload = { ...form }
    if (!auth.isSuperAdmin) {
      payload.organization_id = auth.user?.organization ?? undefined
    }
    // 编辑时如果没改公司，不传 organization_id 避免校验问题
    if (isEdit && !payload.organization_id) {
      delete payload.organization_id
    }
    if (isEdit) await updateJob(editingJob.value.id, payload)
    else await createJob(payload)
    ElMessage.success('保存成功')
    dialogVisible.value = false
    fetchJobs(currentPage.value)
  } catch (e) {
    const errData = e.response?.data
    const msg = typeof errData === 'object'
      ? errData.detail || Object.values(errData).flat().join('；')
      : '保存失败'
    ElMessage.error(msg)
  } finally {
    saving.value = false
  }
}

async function handleDelete(id) {
  await ElMessageBox.confirm('确认删除该职位？', '提示', { type: 'warning' })
  await deleteJob(id)
  ElMessage.success('已删除')
  fetchJobs(1)
}

const uploadRef = ref(null)

async function handleDownloadTemplate() {
  try {
    const { data } = await downloadJobTemplate()
    const url = URL.createObjectURL(data)
    const a = document.createElement('a')
    a.href = url
    a.download = 'job_import_template.xlsx'
    a.click()
    URL.revokeObjectURL(url)
    ElMessage.success('模板下载成功')
  } catch {
    ElMessage.error('模板下载失败')
  }
}

async function handleImportExcel(uploadFile) {
  const file = uploadFile.raw
  if (!file) return
  try {
    const { data } = await importJobsExcel(file)
    const msg = `成功导入 ${data.created} 个职位`
    if (data.errors?.length) {
      ElMessageBox.alert(
        `${msg}，但有 ${data.errors.length} 条错误：\n\n${data.errors.join('\n')}`,
        '导入结果',
        { type: 'warning', confirmButtonText: '知道了' }
      )
    } else {
      ElMessage.success(msg)
    }
    fetchJobs(1)
  } catch (e) {
    const detail = e.response?.data
    if (detail?.errors?.length) {
      ElMessageBox.alert(detail.errors.join('\n'), '导入失败', { type: 'error', confirmButtonText: '知道了' })
    } else {
      ElMessage.error(detail?.detail || '导入失败，请检查文件格式')
    }
  }
  // 清除上传组件状态，允许重复上传同一文件
  uploadRef.value?.clearFiles()
}

onMounted(() => {
  fetchJobs()
  if (auth.isSuperAdmin) fetchOrgs()
})
</script>
