<!-- 后勤模块 - 建档审核中心 - 单位建档 -->

<template>
    <div class="MainBox">
        <el-form :model="queryForm" inline class="card-box mb-4">
            <el-form-item label="节点名称">
                <el-input v-model="queryForm.deptName" placeholder="请输入节点名称"></el-input>
            </el-form-item>

            <!-- <el-form-item label="节点类型">
                <el-select v-model="queryForm.nodeType" placeholder="请选择节点类型" clearable>
                    <el-option v-for="item in nodeTypeList" :key="item.value" :label="item.label"
                        :value="item.value"></el-option>
                </el-select>
            </el-form-item> -->
            <el-form-item label="提交时间">
                <el-date-picker v-model="queryForm.dateRange" type="daterange" value-format="yyyy-MM-dd"
                    range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
            </el-form-item>

            <el-form-item label="审核状态">
                <el-select v-model="queryForm.auditStatus" placeholder="请选择审核状态" clearable>
                    <el-option label="待审核" value="0"></el-option>
                    <el-option label="已通过" value="1"></el-option>
                    <el-option label="已拒绝" value="2"></el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button size="default" @click="resetQuery">重置</el-button>
                <el-button type="primary" size="default" @click="handleQuery">查询</el-button>
                <el-button type="primary" plain size="default">导出Excel</el-button>
                <el-button type="primary" plain size="default">打印</el-button>
            </el-form-item>
        </el-form>

        <div class="card-box">
            <el-table :data="tableData" v-loading="loading" class="mt-2">
                <el-table-column prop="deptName" label="节点名称"></el-table-column>
                <el-table-column prop="nodeType" label="节点类型">
                    <template #default="scope">
                        {{ getNodeTypeLabel(scope.row.nodeType) }}
                    </template>
                </el-table-column>
                <el-table-column prop="parentName" label="所属上级"></el-table-column>
                <el-table-column prop="createBy" label="提交人"></el-table-column>
                <el-table-column prop="createTime" label="提交时间"></el-table-column>
                <!-- <el-table-column prop="remark" label="权限说明"></el-table-column> -->
                <el-table-column prop="auditStatus" label="审核状态">
                    <template #default="scope">
                        <el-tag
                            :type="scope.row.auditStatus === '0' ? 'warning' : scope.row.auditStatus === '1' ? 'success' : 'danger'">
                            {{ scope.row.auditStatus === '0' ? '待审核' : scope.row.auditStatus === '1' ? '已通过' : '已拒绝' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="状态">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === '0' ? 'success' : 'danger'">
                            {{ scope.row.status === '0' ? '正常' : '停用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-button size="small" type="primary" link @click="handleEdit(scope.row)">审核</el-button>
                        <el-button size="small" type="primary" link v-if="scope.row.status === '0'"
                            @click="handleStatusChange(scope.row, '1')">禁用</el-button>
                        <el-button size="small" type="primary" link v-else
                            @click="handleStatusChange(scope.row, '0')">启用</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <div class="pagination-container">
                <span class="total-count">显示第 {{ (pageNum - 1) * pageSize + 1 }} 到 {{ pageNum * pageSize }} 条记录，共 {{
                    total }}
                    条</span>
                <el-pagination v-model:current-page="pageNum" v-model:page-size="pageSize" :page-sizes="[5, 10, 20]"
                    :total="total" layout="prev, pager, next" @size-change="getList"
                    @current-change="getList"></el-pagination>
            </div>
        </div>
        <!-- 节点审核弹窗 -->
        <DialogBox v-if="dialogShow" ref="dialogRef" :show="dialogShow" :CloseDialog="handleCancel" :rowData="currentRowData" />
    </div>
</template>
<script setup name="Index">
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import DialogBox from "./DialogBox.vue";
import { listDept, auditDept, updateDept } from "@/api/Logistics/filingReview.js";
import { listDept as getAllDeptList } from "@/api/system/dept.js";



// 查询表单数据
const queryForm = ref({
    dateRange: [],
    deptName: "",
    nodeType: "",
    auditStatus: ""
});






// 节点类型列表
const nodeTypeList = ref([

    {
        label: "部门",
        value: "1"
    },
    {
        label: "楼层",
        value: "2"
    },
    {
        label: "班组",
        value: "3"
    },
]);

// 表格数据
const tableData = ref([]);
const dialogShow = ref(false); // 入库审核弹窗-显示状态
const currentRowData = ref({}); // 当前选中的行数据
const pageNum = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示条数
const total = ref(0); // 总记录数
const loading = ref(false); // 加载状态
const allDeptList = ref([]); // 完整的部门列表，用于映射父级名称

// 获取节点类型标签
const getNodeTypeLabel = (value) => {
    const item = nodeTypeList.value.find(item => item.value === value);
    return item ? item.label : '部门';
}


// 获取完整的部门列表（用于映射父级名称）
const getAllDepts = async () => {
    try {
        const response = await getAllDeptList();
        if (response.code === 200) {
            allDeptList.value = response.data || response.rows || [];
        }
    } catch (error) {
        // 静默失败，不影响主流程
        console.warn('获取完整部门列表失败:', error);
    }
};

// 查询列表数据
const getList = () => {
    loading.value = true;
    const params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value
    };

    // 添加节点名称筛选
    if (queryForm.value.deptName) {
        params.deptName = queryForm.value.deptName;
    }

    // 添加节点类型筛选
    if (queryForm.value.nodeType) {
        params.nodeType = queryForm.value.nodeType;
    }

    // 处理日期范围
    if (queryForm.value.dateRange && queryForm.value.dateRange.length === 2) {
        params.startDate = queryForm.value.dateRange[0];
        params.endDate = queryForm.value.dateRange[1];
    }

    // 添加审核状态筛选
    if (queryForm.value.auditStatus !== "" && queryForm.value.auditStatus !== null && queryForm.value.auditStatus !== undefined) {
        params.auditStatus = queryForm.value.auditStatus;
    }

    listDept(params).then(response => {
        if (response.code === 200) {
            const data = response.rows || response.data || [];
            // 根据parentId映射所属上级，从完整的部门列表中查找
            tableData.value = data.map(item => {
                if (item.parentId) {
                    // 从完整的部门列表中查找父级
                    const parentItem = allDeptList.value.find(d => d.deptId === item.parentId);
                    if (parentItem) {
                        item.parentName = parentItem.deptName;
                    } else {
                        // 如果找不到，尝试从当前页数据中查找（兼容处理）
                        const currentPageParent = data.find(d => d.deptId === item.parentId);
                        if (currentPageParent) {
                            item.parentName = currentPageParent.deptName;
                        }
                    }
                }
                return item;
            });
            total.value = response.total || 0;
        }
        loading.value = false;
    }).catch(() => {
        loading.value = false;
    });
};

// 查询
const handleQuery = () => {
    pageNum.value = 1;
    getList();
};

// 重置查询
const resetQuery = () => {
    queryForm.value = {
        dateRange: [],
        deptName: "",
        nodeType: "",
        auditStatus: ""
    };
    pageNum.value = 1;
    getList();
};

// 新增签发人
const handleAdd = (row) => {
    dialogShow.value = true
}

// 编辑签发人（审核）
const handleEdit = (row) => {
    // 保存当前行数据，映射到弹窗需要的字段格式
    currentRowData.value = {
        id: row.deptId || row.id,
        deptName: row.deptName || row.deptName,
        parentNode: row.parentName || row.parentNode,
        submitter: row.createBy || row.submitter,
        phone: row.phone || '',
        createTime: row.createTime || '',
        nodeType: row.nodeType || '1',
        auditStatus: row.auditStatus ? parseInt(row.auditStatus) : 1,
        auditOpinion: row.auditOpinion || row.remark || ''
    }
    dialogShow.value = true
}

// 审核部门
const handleAudit = (row, auditStatus) => {
    auditDept({
        id: row.id,
        auditStatus: auditStatus
    }).then(response => {
        if (response.code === 200) {
            ElMessage.success('审核成功');
            getList();
        }
    });
};

// 启用/禁用状态变更
const handleStatusChange = (row, status) => {
    updateDept({
        ...row,
        status: status
    }).then(response => {
        if (response.code === 200) {
            ElMessage.success(status === '1' ? '启用成功' : '禁用成功');
            getList();
        }
    });
};

// 查看详情
const handleDetail = (row) => {
    dialogShow.value = true
}

// 关闭弹窗
const handleCancel = () => {
    console.log('关闭弹窗')
    dialogShow.value = false
    // 清空当前行数据
    currentRowData.value = {}
    // 关闭弹窗后刷新列表
    getList();
}

// 组件挂载时获取列表
onMounted(async () => {
    // 先获取完整的部门列表，用于映射父级名称
    await getAllDepts();
    // 然后获取分页列表
    getList();
});

</script>
<style scoped lang="scss">
.MainBox {
    padding: 20px;
    height: 100%;
    background: #F9FAFB;
}

.FlexBox {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    gap: 10px;
}

.TitleBox {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
}


.mt-2 {
    margin-top: 20px;
}


.card-box {
    background: #fff;
    padding: 16px;
    border-radius: 4px;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16px;
}

.total-count {
    color: #606266;
}
</style>
