<template>
  <div class="org-list-page">
    <a-form layout="inline" class="search-form">
      <a-form-item label="机构名称">
        <a-input v-model:value="searchForm.name" placeholder="请输入机构名称" allow-clear />
      </a-form-item>
      <a-form-item label="机构ID">
        <a-input v-model:value="searchForm.id" placeholder="请输入机构ID" allow-clear />
      </a-form-item>
      <a-form-item>
        <a-space>
          <a-button type="primary" :loading="loading" @click="handleSearch">查询</a-button>
          <a-button @click="handleReset">重置</a-button>
        </a-space>
      </a-form-item>
    </a-form>

    <div class="toolbar">
      <a-button v-permission="'org:add'" type="primary" @click="openCreateModal(null)">
        <PlusOutlined /> 新增机构
      </a-button>
    </div>

    <a-table
      :columns="columns"
      :data-source="tableData"
      :loading="loading"
      row-key="id"
      :pagination="false"
      default-expand-all-rows
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <a-space>
            <a v-permission="'org:edit'" @click="openEditModal(record)">修改</a>
            <a-popconfirm title="确定删除该机构吗?" @confirm="handleDelete(record)">
              <a v-permission="'org:delete'" class="danger-link">删除</a>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <a-modal
      v-model:open="modalOpen"
      :title="modalMode === 'create' ? '新增机构' : '修改机构'"
      :confirm-loading="submitting"
      @ok="handleSubmit"
    >
      <a-form ref="formRef" layout="vertical" :model="form" :rules="rules">
        <a-form-item label="机构名称" name="name">
          <a-input v-model:value="form.name" placeholder="请输入机构名称" />
        </a-form-item>
        <a-form-item v-if="!isRootRecord" label="上级机构" name="parentId">
          <OrgTreeSelect v-model="form.parentId" :exclude-id="form.id" />
        </a-form-item>
        <a-form-item label="备注" name="remark">
          <a-textarea v-model:value="form.remark" placeholder="请输入备注" :rows="3" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import OrgTreeSelect from '@/components/OrgTreeSelect.vue'
import { fetchOrgListApi, createOrgApi, updateOrgApi, deleteOrgApi } from '@/api/system'

const columns = [
  { title: '机构ID', dataIndex: 'id', width: 140 },
  { title: '机构名称', dataIndex: 'name' },
  { title: '机构级别', dataIndex: 'level', width: 100 },
  { title: '上级机构', dataIndex: 'parentName', width: 160 },
  { title: '备注', dataIndex: 'remark' },
  { title: '操作', dataIndex: 'action', width: 140 }
]

const searchForm = reactive({ name: '', id: '' })
const loading = ref(false)
const orgTree = ref([])

function annotateParentName(nodes, parentName) {
  return nodes.map((node) => ({
    ...node,
    parentName: parentName || '—',
    children: node.children?.length ? annotateParentName(node.children, node.name) : []
  }))
}

const tableData = computed(() => annotateParentName(orgTree.value, ''))

async function loadData() {
  loading.value = true
  try {
    const res = await fetchOrgListApi({ name: searchForm.name || undefined, id: searchForm.id || undefined })
    if (res.data.code === 200) orgTree.value = res.data.data
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  loadData()
}
function handleReset() {
  searchForm.name = ''
  searchForm.id = ''
  loadData()
}

onMounted(loadData)

// ---------------- 新增/修改弹窗 ----------------
const modalOpen = ref(false)
const modalMode = ref('create')
const submitting = ref(false)
const formRef = ref(null)
const form = reactive({ id: '', name: '', parentId: undefined, remark: '' })
const isRootRecord = computed(() => modalMode.value === 'edit' && form.id === 'org001')

const rules = {
  name: [{ required: true, message: '请输入机构名称' }],
  parentId: [{ required: true, message: '请选择上级机构' }]
}

function openCreateModal(parentRecord) {
  modalMode.value = 'create'
  form.id = ''
  form.name = ''
  form.parentId = parentRecord?.id
  form.remark = ''
  modalOpen.value = true
}

function openEditModal(record) {
  modalMode.value = 'edit'
  form.id = record.id
  form.name = record.name
  form.parentId = record.parentId || undefined
  form.remark = record.remark
  modalOpen.value = true
}

async function handleSubmit() {
  try {
    await formRef.value.validate()
  } catch {
    return
  }
  submitting.value = true
  try {
    const payload = { name: form.name, parentId: form.parentId, remark: form.remark }
    const res =
      modalMode.value === 'create'
        ? await createOrgApi(payload)
        : await updateOrgApi(form.id, payload)
    if (res.data.code === 200) {
      message.success(modalMode.value === 'create' ? '新增成功' : '修改成功')
      modalOpen.value = false
      loadData()
    }
  } finally {
    submitting.value = false
  }
}

async function handleDelete(record) {
  const res = await deleteOrgApi(record.id)
  if (res.data.code === 200) {
    message.success('删除成功')
    loadData()
  }
}
</script>

<style scoped>
.search-form {
  margin-bottom: 16px;
}
.toolbar {
  margin-bottom: 12px;
}
.danger-link {
  color: #ff4d4f;
}
</style>
