<template>
    <div class="zhiwei p-4">
        <div class="left-tree-box">
            <div class="tree-title">部门列表</div>
            <div class="tree-box">
                <div class="search-input">
                    <a-input-search v-model:value="treeSearchValue" placeholder="搜索关键字" style="width: 100%;height:100%;" />
                </div>
                <div class="tree-container">
                    <a-directory-tree :tree-data="treeData" :expandedKeys="expandedKeys" class="tree-list" :showIcon="false"
                        :auto-expand-parent="autoExpandParent" @expand="onExpand" :replaceFields="replaceFields"
                        @select="nodeSelect">
                        <template #switcherIcon>
                            <div class="self-switcher-icon"></div>
                        </template>
                        <template #title="{ name, selected, dataRef }">
                            <span v-if="name.indexOf(treeSearchValue) > -1">
                                {{ name.substr(0, name.indexOf(treeSearchValue)) }}
                                <span style="color: #f50">{{ treeSearchValue }}</span>
                                {{ name.substr(name.indexOf(treeSearchValue) + treeSearchValue.length) }}
                            </span>
                            <span v-else>{{ name }}</span>
                        </template>
                    </a-directory-tree>
                </div>
            </div>
        </div>
        <div class="right-table-box">
            <BasicTable @register="registerTable" class="basic-table">
                <template #toolbar>
                    <Button type="primary" @click="handleAdd">
                        新增
                    </Button>
                </template>
                <template #action="{ record }">
                    <TableAction :actions="[
                        {
                            label: '编辑',
                            tooltip: '编辑',
                            onClick: handleEdit.bind(null, record),
                        },
                        {
                            label: '删除',
                            tooltip: '删除',
                            color: 'error',
                            onClick: handleDelete.bind(null, record.departid),
                        },
                    ]" />
                </template>
            </BasicTable>
        </div>
        <ZhiweiModalVue v-if="ifShowModal" :title="modalTitle" :formData="formData" @closeModal="ifShowModal = false"
            @onSubmit="onSubmit" />
    </div>
</template>

<script>
import { defineComponent, reactive, ref, toRefs, computed, onMounted, watch, createVNode } from 'vue';
// 导入接口
import { structureList, getPostsList, delPosts } from '/@/api/sys/zhiwei';
// 导入表格组件，表格事件
import { BasicTable, useTable, TableAction } from '/@/components/Table';
import { Button } from 'ant-design-vue';
import { message, Modal } from 'ant-design-vue';
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';

import ZhiweiModalVue from './ZhiweiModal.vue';

export default defineComponent({
    name: 'zhiwei',
    components: { BasicTable, TableAction, Button, ZhiweiModalVue, ExclamationCircleOutlined },
    setup(props, { emit }) {
        // 机构树所用的数据
        const data = reactive({
            replaceFields: {
                children: 'children',
                title: 'name',
                key: 'id'
            },
            treeData: [],//单位列表树
            treeSearchValue: '',
            //用于树状结构搜索的dataList
            dataList: [],
            expandedKeys: [],
            autoExpandParent: true,
        });
        watch(
            () => data.treeSearchValue,
            (value) => {
                if (value) {
                    let expanded = data.dataList
                        .map(item => {
                            if (item.title.indexOf(value) > -1) {
                                return getParentKey(item.key, data.treeData);
                            }
                            return null;
                        })
                        .filter((item, i, self) => item && self.indexOf(item) === i);
                    data.expandedKeys = expanded;
                } else {
                    data.expandedKeys = [];
                }
                data.treeSearchValue = value;
                data.autoExpandParent = true;
            }
        )
        //生成用于树搜索的dataList
        const generateList = (treeData) => {
            for (let i = 0; i < treeData.length; i++) {
                const node = treeData[i];
                const key = node.id;
                data.dataList.push({
                    key,
                    title: node.name,
                });
                if (node.children) {
                    generateList(node.children);
                }
            }
        }
        //获取所有父节点key
        const getParentKey = (key, tree) => {
            let parentKey;
            for (let i = 0; i < tree.length; i++) {
                const node = tree[i];
                if (node.children) {
                    if (node.children.some(item => item.id === key)) {
                        parentKey = node.id;
                    } else if (getParentKey(key, node.children)) {
                        parentKey = getParentKey(key, node.children);
                    }
                }
            }
            return parentKey;
        }
        //树结构展开时触发
        const onExpand = (keys) => {
            data.expandedKeys = keys;
            data.autoExpandParent = false;
        }
        const departmentId = ref(null)
        const nodeSelect = (selectedKeys, { selectedNode, node }) => {
            if (departmentId.value === node.dataRef.id) {
                return;
            } else {
                departmentId.value = node.dataRef.id
                reload();
            }
        }
        //根据部门ID获取职位列表
        const getAllData = (id) => {
            return new Promise((resolve) => {
                if (departmentId.value) {
                    let params = {
                        departmentId: departmentId.value
                    }
                    getPostsList(params).then(res => {
                        if (res.datas && res.datas?.length) {
                            resolve(res.datas)
                        } else {
                            message.info('该部门下无职位数据')
                            resolve([])
                        }
                    })
                } else {
                    resolve([])
                }
            })
        }
        const columns = [
            {
                title: '职位名称',
                dataIndex: 'departName',
                key: 'departName',
                align: 'center'
            },
            // {
            //     title: '职位id',
            //     dataIndex: 'departid',
            //     key: 'departid',
            //     align: 'center'
            // },
            {
                title: '排序',
                dataIndex: 'orderId',
                key: 'orderId',
                align: 'center'
            },
        ]
        //注册职位表格
        const [
            registerTable,
            { reload, getDataSource },
        ] = useTable({
            title: '职位列表', //'菜单列表'
            api: getAllData, //加载数据
            columns: columns,
            useSearchForm: false,     //开启搜索区域
            bordered: false,
            showTableSetting: true,  // 显示表格设置
            tableSetting: {
                redo: true,
                size: true,
                setting: false,
                fullScreen: false
            },
            // canResize: false,
            showIndexColumn: true,
            pagination: {
                // pageSize: 10,
                hideOnSinglePage: false
            },
            actionColumn: {
                width: 100,
                title: '操作',
                dataIndex: 'action',
                slots: { customRender: 'action' },
            }
        });
        const formData = ref(null)
        const modalTitle = ref('新增职位')
        const ifShowModal = ref(false)
        //新增职位
        const handleAdd = () => {
            if (!departmentId.value) {
                message.error('没有选择部门');
                return;
            }
            let tempData = getDataSource();
            formData.value = {
                departid: "",
                parentId: "",
                departName: "",
                orderId: tempData.length + 1,
                orgId: departmentId.value
            }
            modalTitle.value = '新增职位'
            ifShowModal.value = true
        }
        //修改职位
        const handleEdit = (item) => {
            formData.value = {
                departid: item.departid,
                parentId: item.parentId,
                departName: item.departName,
                orderId: item.orderId
            }
            modalTitle.value = '编辑职位'
            ifShowModal.value = true
        }
        //删除职位
        const handleDelete = (id) => {
            Modal.confirm({
                title: '删除提示',
                icon: createVNode(ExclamationCircleOutlined),
                content: '确定删除该职位？',
                centered: true,
                okText: '确定',
                okType: 'danger',
                cancelText: '取消',
                onOk: (() => {
                    let params = {
                        orgId: departmentId.value,
                        departid: id
                    }
                    delPosts(params).then(res => {
                        if (res.resp_code === 0) {
                            message.success('操作成功')
                            onSubmit(true)
                        } else if(res.resp_code === 1) {
                            message.info(res.resp_msg)
                        } else{
                            message.error('操作失败')
                        }
                    })
                })
            });
        }
        const onSubmit = (e) => {
            if (e) {
                reload();
            }
        }
        onMounted(() => {
            //初始化时获取所有机构
            structureList().then(res => {
                if (res.length) {
                    data.treeData = res
                    data.dataList = []
                    generateList(data.treeData)
                }
            })
        });
        return {
            formData,
            modalTitle,
            ifShowModal,
            ...toRefs(data),
            //func
            onExpand,
            nodeSelect,
            registerTable,
            reload,
            handleAdd,
            handleEdit,
            handleDelete,
            onSubmit
        };
    },
});
</script>

<style lang="less" scoped>
.zhiwei {
    height: 100%;
    display: flex;

    .left-tree-box {
        width: 300px;
        // height: 960px;
        height: 100%;
        background-color: #fff;
        border-radius: 6px;

        .tree-title {
            height: 50px;
            line-height: 50px;
            text-align: center;
            font-family: Source Han Sans CN;
            font-size: 16px;
            font-weight: bold;
            color: #333333;
            border-bottom: 1px solid #DEDEDE;
        }

        .tree-box {
            margin-top: 14px;
            padding: 0 10px;

            .search-input {
                height: 34px;
            }

            .tree-container {
                max-height: 680px;
                overflow: auto;

                &::-webkit-scrollbar {
                    width: 3px;
                }

                &::-webkit-scrollbar-thumb {
                    border-radius: 2px;
                    background: #ccd5df;
                }

                &::-webkit-scrollbar-track {
                    display: none;
                }

                .tree-list {
                    font-family: Alibaba PuHuiTi 2.0;

                    ::v-deep .ant-tree-switcher_close {
                        .ant-tree-switcher-icon {
                            margin-top: 5px;
                            border-left: 12px solid #888888;
                            border-top: 7px solid transparent;
                            border-bottom: 7px solid transparent;
                            transform: rotate(0);
                            border-radius: 3px;
                        }
                    }

                    ::v-deep .ant-tree-switcher_open {
                        .ant-tree-switcher-icon {
                            margin-top: 5px;
                            border-left: 12px solid #888888;
                            border-top: 7px solid transparent;
                            border-bottom: 7px solid transparent;
                            transform: rotate(90deg);
                            border-radius: 3px;
                        }
                    }

                    ::v-deep .ant-tree-treenode-selected {

                        .ant-tree-node-content-wrapper.ant-tree-node-content-wrapper-normal.ant-tree-node-selected::before {
                            background: #e6f0fb !important;
                        }

                        .ant-tree-node-content-wrapper.ant-tree-node-content-wrapper-open.ant-tree-node-selected::before {
                            background: #e6f0fb !important;
                        }

                        .ant-tree-node-content-wrapper.ant-tree-node-content-wrapper-close.ant-tree-node-selected::before {
                            background: #e6f0fb !important;
                        }

                        .ant-tree-node-content-wrapper.ant-tree-node-content-wrapper-normal.ant-tree-node-selected {
                            color: #0671DD;
                        }

                        .ant-tree-node-content-wrapper.ant-tree-node-content-wrapper-open.ant-tree-node-selected {
                            color: #0671DD;
                        }

                        .ant-tree-node-content-wrapper.ant-tree-node-content-wrapper-close.ant-tree-node-selected {
                            color: #0671DD;
                        }
                    }
                }
            }
        }
    }

    .right-table-box {
        padding: 0 20px;
        margin-left: 8px;
        width: calc(100% - 308px);
        height: 100%;
        background-color: #fff;
        border-radius: 6px;

        .basic-table {
            height: 100%;

            ::v-deep .ant-table-title {
                padding: 0 !important;
                .vben-basic-title {
                    font-family: '阿里巴巴普惠体 2.0';
                    font-size: 16px;
                    font-weight: bold;
                    color: #333333;
                }
            }
        }

    }
}
</style>