<template>
  <div>
    <div style="display:flex;justify-content:space-between;margin-bottom:16px">
      <h2>组织架构管理</h2>
      <el-button type="primary" @click="openDialog()">新增公司</el-button>
    </div>
    <el-table :data="orgs" border v-loading="loading">
      <el-table-column prop="name" label="公司名称" />
      <el-table-column label="上级公司">
        <template #default="{ row }">{{ row.parent ? allOrgs.find(o=>o.id===row.parent)?.name : '（集团）' }}</template>
      </el-table-column>
      <el-table-column prop="email" label="联系邮箱" />
      <el-table-column label="状态">
        <template #default="{ row }"><el-tag :type="row.is_active?'success':'danger'">{{ row.is_active?'启用':'停用' }}</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"
        v-model:page-size="pageSize"
        :page-sizes="[20]"
        :total="total"
        layout="total, prev, pager, next"
        @current-change="handlePageChange"
      />
    </div>

    <el-dialog v-model="dialogVisible" :title="editing ? '编辑公司' : '新增公司'" width="480px">
      <el-form :model="form" label-width="90px">
        <el-form-item label="公司名称"><el-input v-model="form.name" /></el-form-item>
        <el-form-item label="上级公司">
          <el-select v-model="form.parent" clearable placeholder="不选则为集团顶级">
            <el-option v-for="o in allOrgs" :key="o.id" :value="o.id" :label="o.name" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系邮箱"><el-input v-model="form.email" /></el-form-item>
        <el-form-item label="简介"><el-input v-model="form.description" type="textarea" /></el-form-item>
        <el-form-item label="状态"><el-switch v-model="form.is_active" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="save" :loading="saving">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { manageOrganizations, createOrganization, updateOrganization, deleteOrganization } from '@/api/organizations'
import { ElMessage, ElMessageBox } from 'element-plus'

const orgs = ref([])
const allOrgs = ref([])
const dialogVisible = ref(false)
const editing = ref(null)
const saving = ref(false)
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const form = reactive({ name: '', parent: null, email: '', description: '', is_active: true })

const fetchOrgs = async (page = 1) => {
  loading.value = true
  try {
    const { data } = await manageOrganizations(page)
    orgs.value = data.results
    total.value = data.count
    currentPage.value = page
  } catch (error) {
    ElMessage.error('加载部门列表失败，请重试')
  } finally {
    loading.value = false
  }
}

const fetchAllOrgs = async () => {
  try {
    let allResults = []
    for (let i = 1; i <= 5; i++) {
      const { data } = await manageOrganizations(i)
      allResults = allResults.concat(data.results)
      if (i === Math.ceil(data.count / 20)) break
    }
    allOrgs.value = allResults
  } catch (error) {
    ElMessage.error('加载部门列表失败')
  }
}

function openDialog(org = null) {
  editing.value = org
  if (org) Object.assign(form, org)
  else Object.assign(form, { name: '', parent: null, email: '', description: '', is_active: true })
  dialogVisible.value = true
}

async function save() {
  saving.value = true
  try {
    if (editing.value) await updateOrganization(editing.value.id, form)
    else await createOrganization(form)
    ElMessage.success('保存成功')
    dialogVisible.value = false
    fetchOrgs(1)
    fetchAllOrgs()
  } catch { ElMessage.error('保存失败') } finally { saving.value = false }
}

function handlePageChange(newPage) {
  fetchOrgs(newPage)
}

async function handleDelete(id) {
  try {
    await ElMessageBox.confirm(
      '此操作将永久删除该部门，是否继续？',
      '警告',
      { confirmButtonText: '确认', cancelButtonText: '取消', type: 'warning' }
    )
    await deleteOrganization(id)
    ElMessage.success('删除成功')
    fetchOrgs(1)
    fetchAllOrgs()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

onMounted(() => {
  fetchOrgs()
  fetchAllOrgs()
})
</script>
