<template>
    <PageWrapper contentFullHeight dense fixedHeight>
        <BasicTable @expand="handleExpand" @register="registerTable">
            <template #toolbar>
                <a-button v-auth="'department:add'" type="primary" @click="handleCreate">
                    {{ t('新增组织') }}
                </a-button>
            </template>
            <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex == 'name'">
                    <a-tag v-if="record.departmentType === 1" color="processing">公司</a-tag>
                    <a-tag v-else-if="record.departmentType === 0" color="warning">部门</a-tag>
                    &nbsp;{{ record.name }}
                </template>
                <template v-if="column.dataIndex == 'action'">
                    <TableAction
                        :actions="[
                            {
                                icon: 'ant-design:user-add-outlined',
                                auth: 'department:addUser',
                                tooltip: '添加人员',
                                onClick: handleAddUser.bind(null, record)
                            },
                            {
                                icon: 'clarity:note-edit-line',
                                auth: 'department:edit',
                                onClick: handleEdit.bind(null, record)
                            },
                            {
                                icon: 'ant-design:delete-outlined',
                                color: 'error',
                                auth: 'department:delete',
                                popConfirm: {
                                    title: t('是否确认删除'),
                                    confirm: handleDelete.bind(null, record)
                                }
                            }
                        ]"
                    />
                </template>
            </template>
        </BasicTable>
        <DeptDrawer @register="registerDrawer" @success="handleSuccess" />
        <SelectMember
            v-if="visible"
            :isShowTree="false"
            :multiple="true"
            :selectedIds="selectedUserIds"
            :visible="visible"
            @change="handleDeptUser"
            @close="
                () => {
                    visible = false;
                }
            "
        />
    </PageWrapper>
</template>
<script lang="ts">
    import { defineComponent, h, ref } from 'vue';

    import { BasicTable, useTable, TableAction, BasicColumn, FormSchema } from '/@/components/Table';

    import { useModal } from '/@/components/Modal';
    import { PageWrapper } from '/@/components/Page';
    import DeptDrawer from './components/DeptDrawer.vue';
    import { Switch } from 'ant-design-vue';
    import { useMessage } from '/@/hooks/web/useMessage';
    // import { useI18n } from 'vue-i18n';
    import { SelectMember } from '/@/components/SelectOrganizational/index';
    import { deleteDepartment, getDepartmentEnabledTree, getDepartmentTrees, getDepartmentUserList, updateDepartmentUser } from '/@/api/system/department';
    import { useI18n } from '/@/hooks/web/useI18n';

    const { t } = useI18n();
    export const columns: BasicColumn[] = [
        {
            title: t('组织名称'),
            dataIndex: 'name',
            width: 400,
            align: 'left',
            sorter: true
        },
        {
            title: '组织编码',
            dataIndex: 'code',
            sorter: true,
            align: 'left',
            width: 100
        },

        {
            title: t('状态'),
            dataIndex: 'enabledMark',
            width: 80,
            sorter: true,
            align: 'left',
            customRender: ({ record }) => {
                const enabledMark = record.enabledMark == 1 ? true : false;

                return h(Switch, { checked: enabledMark });
            }
        },
        {
            title: t('主页'),
            dataIndex: 'website',
            width: 200,
            align: 'left',
            sorter: true
        },
        {
            title: t('地址'),
            dataIndex: 'address',
            width: 200,
            align: 'left',
            sorter: true
        },
        {
            title: t('备注'),
            dataIndex: 'remark',
            align: 'left',
            width: 150,
            sorter: true
        }
    ];

    export const searchFormSchema: FormSchema[] = [
        {
            field: 'name',
            label: t('组织名称'),
            component: 'Input'
        },
        {
            field: 'code',
            label: t('组织编码'),
            component: 'Input'
        },
        {
            field: 'enabledMark',
            label: t('状态'),
            component: 'Select',
            componentProps: {
                options: [
                    { label: t('启用'), value: 1 },
                    { label: t('停用'), value: 0 }
                ]
            }
        }
    ];

    export default defineComponent({
        name: 'DeptManagement',
        components: { BasicTable, TableAction, DeptDrawer, PageWrapper, SelectMember },
        setup() {
            const { notification } = useMessage();
            const [registerDrawer, { openModal }] = useModal();
            const [registerTable, { reload }] = useTable({
                title: t('组织列表'),
                api: getDepartmentTrees,
                columns,
                formConfig: {
                    rowProps: {
                        gutter: 16
                    },
                    schemas: searchFormSchema,
                    actionColOptions: { span: 16 },
                    showResetButton: false
                },
                beforeFetch: (params) => {
                    return {
                        ...params,
                        isOrg: 1
                    };
                },
                pagination: {
                    pageSize: 20
                },
                striped: false,
                useSearchForm: true,
                showTableSetting: true,
                showIndexColumn: false,
                actionColumn: {
                    width: 100,
                    title: t('操作'),
                    dataIndex: 'action',
                    slots: { customRender: 'action' }
                },
                tableSetting: {
                    size: false,
                    setting: false
                }
            });

            const visible = ref<boolean>(false);
            const selectedUserIds = ref<string[]>([]);
            const deptId = ref('');

            function handleCreate() {
                openModal(true, {
                    isUpdate: false
                });
            }

            function handleEdit(record: Recordable) {
                openModal(true, {
                    record,
                    isUpdate: true
                });
            }

            function handleDelete(record: Recordable) {
                deleteDepartment([record.id]).then((_) => {
                    reload();
                    notification.success({
                        message: t('提示'),
                        description: t('删除成功')
                    }); //提示消息
                });
            }

            function handleAddUser(record: Recordable) {
                deptId.value = record.id;
                getDepartmentUserList({ id: record.id }).then((res) => {
                    selectedUserIds.value = res.map((it) => {
                        return it.id;
                    });
                    visible.value = true;
                });
            }

            function handleDeptUser(v) {
                updateDepartmentUser({ id: deptId.value, userIds: v }).then(() => {
                    notification.success({
                        message: '添加人员',
                        description: t('成功')
                    });
                });
            }

            function handleSuccess() {
                reload();
            }

            function handleExpand(expanded, record) {
                if (!expanded) {
                    return;
                }
                const { id } = record;
                if (record?.children.length || record._loaded) {
                    return;
                }
                getDepartmentTrees({ id }).then((result) => {
                    const node = result[0];
                    if (node?.children.length) {
                        node.children.forEach((item) => {
                            item.children = [];
                            item.key = item.id;
                        });
                        record.children = node.children;
                    }
                    record._loaded = true;
                });
            }

            return {
                registerTable,
                registerDrawer,
                handleCreate,
                handleEdit,
                handleDelete,
                handleAddUser,
                handleDeptUser,
                handleSuccess,
                handleExpand,
                visible,
                selectedUserIds,
                t
            };
        }
    });
</script>
