<template>
    <div class="app-container">
        <!-- 查询区 -->
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
            <el-form-item label="名称" prop="name">
                <el-input v-model="queryParams.name" placeholder="请输入名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="疾病大类" prop="pid">
                <el-tree-select v-model="queryParams.pid" :data="diseaseOptions" style="width: 180px;"
                    :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="请选择"
                    check-strictly />
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 按钮区 -->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button type="primary" plain icon="Plus" @click="handleAdd"
                    v-hasPermi="['biosafety:disease:add']">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
            </el-col>
            <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <!-- 表格 -->
        <el-table v-if="refreshTable" v-loading="loading" :data="diseaseList" row-key="id"
            :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
            <el-table-column label="名称" prop="name" />
            <el-table-column label="描述" align="center" prop="desc" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template #default="scope">
                    <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['biosafety:disease:edit']">修改</el-button>
                    <el-button v-if="scope.row.pid === 0" link type="primary" icon="Plus" @click="handleAdd(scope.row)"
                        v-hasPermi="['biosafety:disease:add']">新增</el-button>
                    <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['biosafety:disease:remove']">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 新增/修改弹窗 -->
        <el-dialog :title="title" v-model="open" width="500px" append-to-body>
            <el-form ref="diseaseRef" :model="form" :rules="rules" label-width="100px">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name" placeholder="请输入名称" />
                </el-form-item>
                <el-form-item label="描述" prop="desc">
                    <el-input v-model="form.desc" type="textarea" placeholder="请输入内容" />
                </el-form-item>

                <!-- 新增：是否为疾病大类 -->
                <el-form-item label="疾病大类" prop="isRoot">
                    <el-switch v-model="form.isRoot" active-text="是" inactive-text="否" @change="onRootChange" />
                </el-form-item>

                <!-- 父级选择（仅当 isRoot=false 时显示） -->
                <el-form-item v-if="!form.isRoot" label="上级疾病" prop="pid">
                    <el-tree-select v-model="form.pid" :data="diseaseOptions"
                        :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="请选择"
                        check-strictly clearable />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                    <el-button @click="cancel">取 消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="Disease">
import { listDisease, getDisease, delDisease, addDisease, updateDisease } from '@/api/biosafety/disease'

const { proxy } = getCurrentInstance()

/* 响应式数据 */
const diseaseList = ref([])
const diseaseOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref('')
const isExpandAll = ref(true)
const refreshTable = ref(true)

const data = reactive({
    form: {
        id: null,
        name: null,
        desc: null,
        pid: null,
        isRoot: true          // 新增字段：true 表示作为根节点
    },
    queryParams: {
        name: null,
        desc: null,
        pid: null
    },
    rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
    }
})

const { queryParams, form, rules } = toRefs(data)

/* 事件函数 */
function getList() {
    loading.value = true
    listDisease(queryParams.value).then(res => {
        diseaseList.value = proxy.handleTree(res.data, 'id', 'pid')
        loading.value = false
    })
}

function getTreeselect() {
    listDisease().then(res => {
        diseaseOptions.value = res.data.filter(item => item.pid === 0)
    })
}

function cancel() {
    open.value = false
    reset()
}

function reset() {
    form.value = {
        id: null,
        name: null,
        desc: null,
        pid: null,
        isRoot: true
    }
    proxy.resetForm('diseaseRef')
}

function handleQuery() {
    getList()
}

function resetQuery() {
    proxy.resetForm('queryRef')
    handleQuery()
}

function handleAdd(row) {
    reset()
    getTreeselect()
    if (row && row.id) {
        form.value.pid = row.id
        form.value.isRoot = false
    } else {
        form.value.pid = 0
        form.value.isRoot = true
    }
    open.value = true
    title.value = '添加疾病'
}

function toggleExpandAll() {
    refreshTable.value = false
    isExpandAll.value = !isExpandAll.value
    nextTick(() => (refreshTable.value = true))
}

async function handleUpdate(row) {
    reset()
    await getTreeselect()
    getDisease(row.id).then(res => {
        Object.assign(form.value, res.data)
        // 根据 pid 判断是否为根节点
        form.value.isRoot = !form.value.pid
        open.value = true
        title.value = '修改疾病'
    })
}

function onRootChange(val) {
    // 切换时清空已选 pid
    if (val) form.value.pid = 0
    else form.value.pid = null
}

function submitForm() {
    proxy.$refs.diseaseRef.validate(valid => {
        if (!valid) return
        // 若作为根节点，强制 pid=0
        if (form.value.isRoot) form.value.pid = 0
        const api = form.value.id ? updateDisease : addDisease
        api(form.value).then(() => {
            proxy.$modal.msgSuccess(form.value.id ? '修改成功' : '新增成功')
            open.value = false
            getList()
        })
    })
}

function handleDelete(row) {
    proxy.$modal.confirm(`是否确认删除疾病"${row.name}"的数据项？`)
        .then(() => delDisease(row.id))
        .then(() => {
            getList()
            proxy.$modal.msgSuccess('删除成功')
        })
        .catch(() => { })
}

/* 初始化 */
getTreeselect()
getList()
</script>