<template>
    <my-table
        url="/api/v1/organizations"
        rowKey="orgId"
        :addBtn="addBtn"
        ref="table"
        :formatData="formatData"
        noPage
        :rowSelection="{ type: 'radio', getCheckboxProps, selections: true }"
    >
        <template #drawer>
            <Form ref="form" :tableRef="$refs['table']" />
        </template>
        <a-table-column title="名称" data-index="orgName" />
        <a-table-column title="组织分类" #default="row">
            <a-tag color="#87d068" v-if="row.orgType === 'ORGANIZATION'"> {{ row.orgTypeName }}</a-tag>
            <a-tag color="#108ee9" v-if="row.orgType === 'DEPARTMENT'"> {{ row.orgTypeName }}</a-tag>
        </a-table-column>
        <a-table-column title="说明" data-index="remark" />
        <a-table-column title="操作">
            <template #default="row">
                <a @click="() => view(row, 1)">编辑</a>
                <a-divider type="vertical" />
                <PopconfirmDelete :url="`/api/v1/organizations/${row.orgId}`" :cb="refreshTable" />
            </template>
        </a-table-column>
    </my-table>
</template>
<script>
import Form from './form.vue';
import PopconfirmDelete from '@/components/popconfirm_delete/index.vue';
import { arrayToTree } from '@/utils';
import api from '@/api/organization';

export default {
    components: { Form, PopconfirmDelete },
    data() {
        return {
            addBtn: { width: 600, onOk: () => this.$refs['form']?.submit(), openBefore: () => {} },
            selectedRowKeys: [],
        };
    },
    methods: {
        refreshTable() {
            this.$refs['table']?.getData();
        },
        async view(data, type) {
            this.$refs['table']?.show({ type });
            const detailData = await api.getOrganizationDetails(data.orgId);
            this.$nextTick(() => {
                this.$refs['form'].setData({ ...detailData }, type);
            });
        },
        formatData(data) {
            const newArr = new arrayToTree({
                data: data,
                rootValue: 0,
                parentKey: 'parentOrgId',
                key: 'orgId',
            }).treeData;
            return newArr;
        },
        getCheckboxProps(record) {
            return {
                props: {
                    ...record,
                    disabled: record.orgType === 'DEPARTMENT',
                },
            };
        },
    },
};
</script>