<template>
    <div class="page">
        <el-form :inline="true" class="query-form m-b-10" v-if="searchVisible" ref="searchForm" :model="searchForm"
            @keyup.enter="refreshList()" @submit.prevent>
            <!-- 搜索框-->
            <el-form-item prop="fileName" label="部门名称:">
                <el-input style="width: 200px;" v-model="searchForm.name" placeholder="请输入部门名称" clearable></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="refreshList()" icon="search">查询</el-button>
                <el-button type="default" @click="resetSearch()" icon="refresh-right">重置</el-button>
            </el-form-item>
        </el-form>

        <div class="jp-table">
            <vxe-toolbar ref="dataSetToolbar" :refresh="{ query: refreshList }" export print custom>
                <template #buttons>
                    <el-button v-if="hasPermission('attachment:add')" type="primary" icon="plus"
                        @click="add()">新增部门</el-button>
                </template>
                <template #tools>
                    <vxe-button type="text" :title="searchVisible ? '收起检索' : '展开检索'" icon="vxe-icon-search"
                        class="tool-btn" @click="searchVisible = !searchVisible"></vxe-button>
                </template>
            </vxe-toolbar>
            <div class="jp-table-body">
                <vxe-table border="inner" :row-config="{ keyField: 'deptId' }" :column-config="{ resizable: true }"
                    :tree-config="treeConfig" auto-resize resizable height="auto" :loading="loading" size="small"
                    ref="dataSetTable" show-header-overflow show-overflow highlight-hover-row :menu-config="{}"
                    :print-config="{}" :import-config="{}" :export-config="{}" @sort-change="sortChangeHandle"
                    :sort-config="{ remote: true }" :data="dataList" :checkbox-config="{}">
                    <vxe-column type="seq" width="40"></vxe-column>
                    <vxe-column tree-node field="name" title="部门名称">
                    </vxe-column>
                    <vxe-column fixed="right" align="center" width="320" title="操作">
                        <template #default="scope">
                            <el-button type="success" text @click="handleEdit(scope.row)">修改</el-button>
                            <el-button type="danger" text @click="handleDel(scope.row)">删除</el-button>
                        </template>
                    </vxe-column>
                </vxe-table>
                <vxe-pager background size="small" :current-page="tablePage.currentPage" :page-size="tablePage.pageSize"
                    :total="tablePage.total" :page-sizes="[
                        10,
                        20,
                        100,
                        1000,
                        { label: '全量数据', value: 1000000 },
                    ]" :layouts="[
                        'PrevPage',
                        'JumpNumber',
                        'NextPage',
                        'FullJump',
                        'Sizes',
                        'Total',
                    ]" @page-change="currentChangeHandle">
                </vxe-pager>
            </div>
        </div>


        <DeptForm ref="deptRef" @refreshList="refreshList"></DeptForm>
    </div>
</template>

<script>
import ddService from "@/api/test/dd/dd.js"
import DeptForm from "./DeptForm.vue"
import { ElMessage } from "element-plus";
const treeConfig = {
    transform: true,
    rowField: 'deptId',
    parentField: 'parentId',
    lazy: true,
    hasChild: 'hasChild',
    loadMethod({ row }) {
        // 异步加载子节点
        return fetchChildListApi(row)
    }
}
// 模拟后台
const fetchChildListApi = (parentRow) => {
    return new Promise(resolve => {
        ddService.deptList({
            deptId: parentRow.deptId
        }).then(res => {
            res.result.forEach(item => {
                item.hasChild = true
            })
            if (res.result.length == 0) {
                ElMessage({
                    message: `当前部门下暂无子部门`,
                    type: "warning",
                });
            }
            resolve(res.result)
        })
    })
}
export default {
    components: {
        DeptForm
    },
    data() {
        return {
            treeConfig,
            url: "",
            showViewer: false,
            activeName: "",
            searchVisible: true,
            searchForm: {
                companyId: '',
                officeId: '',
                createById: '',
            },
            dataList: [],
            tablePage: {
                total: 0,
                currentPage: 1,
                pageSize: 10,
                orders: [],
            },
            isImportCollapse: false,
            dialogInterfaceVisible: false,
            interfaceTable: [],
            loading: false,
            userInfo: {},
            dictList: [],

        };
    },
    activated() {
        this.userInfo = this.$TOOL.data.get("USER_INFO");
        this.searchForm.createById = this.userInfo.id
        this.$nextTick(() => {
            // 将表格和工具栏进行关联
            const $table = this.$refs.dataSetTable;
            const $toolbar = this.$refs.dataSetToolbar;
            $table.connect($toolbar);
        });
        this.refreshList();
    },
    methods: {
        // 获取数据列表
        refreshList() {
            this.loading = true;
            ddService
                .deptList()
                .then((data) => {
                    this.dataList = data.result;
                    this.dataList.forEach(item => {
                        item.hasChild = true
                    })
                    // this.tablePage.total = data.total;
                    this.loading = false;
                    // 获取分类去重的数据
                });
        },
        // 当前页
        currentChangeHandle({ currentPage, pageSize }) {
            this.tablePage.currentPage = currentPage;
            this.tablePage.pageSize = pageSize;
            this.refreshList();
        },
        // 排序
        sortChangeHandle(column) {
            this.tablePage.orders = [];
            if (column.order != null) {
                this.tablePage.orders.push({
                    column: this.$utils.toLine(column.property),
                    asc: column.order === "asc",
                });
            }
            this.refreshList();
        },
        handleDel(row) {
            this.$confirm(`确定删除当前部门吗?`, "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                this.loading = true;
                ddService
                    .delDept({
                        deptId: row.deptId
                    }).then(res => {
                        console.log(res);

                        this.$message.success("操作成功");
                        this.loading = false;
                        this.refreshList();
                    })
            });
        },
        // 新增
        add() {
            this.$refs.deptRef.init("add")
        },
        // 编辑
        edit(id) {
            console.log(id);
            this.$refs.workCollectAccessoryRef.init("edit", id)
        },
        handleEdit(row) {
            this.$refs.deptRef.init("edit", row.deptId)
        },
        // 查看
        view(id) {
            id =
                id ||
                this.$refs.dataSetTable.getCheckboxRecords().map((item) => {
                    return item.id;
                })[0];
            this.$router.push({
                path: `/database/datamodel/DataSetForm`,
                query: { method: "view", id: id, title: "数据模型配置" },
            });
        },
        resetSearch() {
            this.$refs.searchForm.resetFields();
            this.refreshList();
        },
    },
};
</script>
