<template>
    <el-card>
        <el-row justify="space-between" align="middle" class="mb-2">
            <el-col>
                <el-button type="primary" @click="openAddDialog" v-if="operationPermissions['c-3']">新增机构</el-button>
            </el-col>
        </el-row>
        <el-table :data="orgList" style="width: 100%" row-key="id"
            :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
            <el-table-column prop="name" label="机构名称" />
            <el-table-column prop="manager" label="管理员" />
            <el-table-column prop="phone" label="管理员电话" />
            <el-table-column label="操作" width="180">
                <template #default="scope">
                    <el-button size="small" @click="openEditDialog(scope.row)"
                        v-if="operationPermissions['c-4']">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(scope.row)"
                        v-if="operationPermissions['c-5']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增/编辑机构对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" @close="resetForm">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
                <el-form-item label="机构名称" prop="name">
                    <el-input v-model="form.name" />
                </el-form-item>
                <el-form-item label="父级机构" prop="parent_id">
                    <el-tree-select v-model="form.parent_id" :data="orgList"
                        :props="{ label: 'name', value: 'id', children: 'children' }" placeholder="不选则为一级机构" clearable
                        check-strictly style="width: 100%;" />
                </el-form-item>
                <el-form-item label="负责人" prop="manager">
                    <el-input v-model="form.manager" />
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="form.phone" />
                </el-form-item>
                <!-- <el-form-item label="管理员账号" prop="adminAccount">
                    <el-select v-model="form.adminAccount" placeholder="请选择管理员账号" filterable>
                        <el-option
                            v-for="user in adminList"
                            :key="user.id"
                            :label="`${user.username} (${user.email})`"
                            :value="user.id"
                        />
                    </el-select>
                </el-form-item> -->
            </el-form>
            <template #footer>
                <el-button @click="handleCancel">取消</el-button>
                <el-button type="primary" @click="handleSubmit">确定</el-button>
            </template>
        </el-dialog>
    </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useMenuStore } from "@/stores/menu.js"
const { operationPermissions } = useMenuStore();
const { proxy } = getCurrentInstance()

// 模拟接口
const fetchOrgList = async () => {
    const { records } = await proxy.$http.get('/open-platform/organ/loadData')
    orgList.value = records
}
const fetchAdminList = async () => {
    const { records } = await proxy.$http.get('/open-platform/user/users', {
        params: {
            userName: '',
            pageNo: 1,
            pageSize: 100,
        }
    })
    return records
}


// 真实接口请替换上面两个函数

const orgList = ref([])
const adminList = ref([])

const dialogVisible = ref(false)
const dialogTitle = ref('新增机构')
const formRef = ref()
const form = reactive({
    id: null,
    name: '',
    manager: '',
    phone: '',
    parent_id: null,
})
const rules = {
    name: [{ required: true, message: '请输入机构名称', trigger: 'blur' }],
    // adminAccount: [{ required: true, message: '请选择管理员账号', trigger: 'change' }]
}

const defaultForm = {
    id: null,
    name: '',
    manager: '',
    phone: '',
    parent_id: null,
}

function resetForm() {
    Object.assign(form, defaultForm)
    formRef.value && formRef.value.clearValidate()
}

function handleCancel() {
    dialogVisible.value = false
    resetForm()
}

const openAddDialog = () => {
    dialogTitle.value = '新增机构'
    Object.assign(form, { id: null, name: '', adminAccount: '' })
    dialogVisible.value = true
}
const openEditDialog = (row) => {
    dialogTitle.value = '编辑机构'
    Object.assign(form, row)
    dialogVisible.value = true
}
const handleSubmit = () => {
    formRef.value.validate(async (valid) => {
        if (!valid) return
        console.log('提交的表单数据:', form)
        // const admin = adminList.value.find(u => u.account === form.adminAccount)
        if (form.id) {
            // 编辑
            proxy.$http.post('/open-platform/organ/update', form)
                .then((res) => {
                    if (res.code === 200) {
                        fetchOrgList()
                        ElMessage.success('编辑成功')
                    } else {
                        ElMessage.error('编辑失败')
                    }
                })
                .catch(() => {
                    ElMessage.error('编辑失败')
                })
        } else {
            // 新增
            proxy.$http.post('/open-platform/organ/insert', form)
                .then((res) => {
                    if (res.code === 200) {
                        fetchOrgList()
                        ElMessage.success('新增成功')
                    } else {
                        ElMessage.error('新增失败')
                    }
                })
                .catch(() => {
                    ElMessage.error('新增失败')
                })
        }
        dialogVisible.value = false
    })
}
const handleDelete = (row) => {
    ElMessageBox.confirm('确定删除该机构吗？', '提示', { type: 'warning' })
        .then(() => {
            proxy.$http.post('/open-platform/organ/delete/' + row.id,)
                .then((res) => {
                    if (res.code === 200) {
                        fetchOrgList()
                        ElMessage.success('删除成功')
                    } else {
                        ElMessage.error('删除失败')
                    }
                })
                .catch(() => {
                    ElMessage.error('删除失败')
                })
        })
}

onMounted(async () => {
    fetchOrgList()
    adminList.value = await fetchAdminList()
})
</script>

<style scoped>
.mb-2 {
    margin-bottom: 16px;
}
</style>