<template>
    <div>
        <my-card>
            <a-row :gutter="[16, 16]">
                <a-col :span="24">
                    <a-select
                        show-search
                        v-model="searchValue"
                        placeholder="input search text"
                        style="width: 100%"
                        :default-active-first-option="false"
                        :show-arrow="false"
                        :filter-option="false"
                        :not-found-content="null"
                        :options="dataSource"
                        @search="onSearch"
                        @change="onChange"
                    />
                </a-col>
                <a-col :span="24" class="tw-text-right">
                    <a-button-group>
                        <a-dropdown>
                            <a-menu slot="overlay">
                                <a-menu-item key="1" @click="addOrg">新增组织 </a-menu-item>
                                <a-menu-item key="2" @click="addEqu">新增设备 </a-menu-item>
                            </a-menu>
                            <a-button type="primary" ghost>新增 <a-icon type="down" /></a-button>
                        </a-dropdown>
                        <a-button
                            type="primary"
                            ghost
                            @click="edit"
                            :disabled="selectedObj.catalogType !== 'ORGANIZATION'"
                            >编辑</a-button
                        >
                        <a-button type="primary" ghost @click="del">删除</a-button>
                    </a-button-group>
                </a-col>
            </a-row>
        </my-card>
        <my-card class="tw-mt-2.5">
            <a-row :gutter="[16, 16]">
                <a-col :span="24">
                    <a-tree
                        :treeData="treeData"
                        :replaceFields="replaceFields"
                        :selectedKeys="selectedKeys"
                        @select="onSelect"
                        :load-data="onLoadData"
                    />
                </a-col>
            </a-row>
            <TreeDrawer ref="TreeDrawer" :refresh="init" />
        </my-card>
    </div>
</template>

<script>
import Api from '@/api/oceanus';
import { formatObj } from '@/utils';
import TreeDrawer from './TreeDrawer.vue';

export default {
    components: { TreeDrawer },
    data() {
        return {
            catalogId: -1,
            searchValue: undefined,
            dataSource: [],
            replaceFields: { title: 'catalogName', key: 'catalogId', children: 'children' },
            treeData: [],
            selectedKeys: [],
            selectedObj: {},
            allData: [],
        };
    },
    model: {
        prop: 'value',
        event: 'change',
    },
    mounted() {
        this.init(this.catalogId);
    },
    methods: {
        async init(id) {
            const data = await Api.getEquipmentsTree({ catalogId: id });
            this.treeData = data;
            this.selectedKeys = [data[0]?.catalogId];
            this.selectedObj = data[0];
            this.$emit('change', data[0]);
            this.allData = [...this.allData, ...data];
        },
        onLoadData(treeNode) {
            return new Promise((resolve) => {
                if (treeNode.dataRef.children) {
                    resolve();
                    return;
                }
                Api.getEquipmentsTree({ catalogId: treeNode.dataRef.catalogId }).then((resp) => {
                    if (resp.length === 0) {
                        treeNode.dataRef.isLeaf = true;
                    } else {
                        this.allData = [...this.allData, ...resp];
                        const newData = resp.map((i) => {
                            return {
                                ...i,
                                isLeaf: i.catalogType !== 'ORGANIZATION',
                            };
                        });
                        treeNode.dataRef.children = newData;
                    }
                    this.treeData = [...this.treeData];
                    resolve();
                });
            });
        },
        async onSearch(searchText) {
            const dataList = this.allData;
            const newData = dataList.filter((i) => i.catalogName.indexOf(searchText) != -1);
            this.dataSource = await formatObj(newData, { label: 'catalogName', value: 'catalogId' });
        },
        onChange(val) {
            const data = this.allData.find((i) => i.catalogId === val);
            this.selectedObj = data;
            this.selectedKeys = [val];
            this.searchValue = val;
            this.$emit('change', data);
        },
        onSelect(selectedKeys, { node }) {
            if (selectedKeys.length !== 0) {
                this.selectedKeys = selectedKeys;
                const cueData = node.$props.dataRef;
                this.selectedObj = cueData;
                this.searchValue = undefined;
                this.$emit('change', cueData);
            }
        },
        async view(data = {}, type = 0) {
            this.$refs['TreeDrawer']?.open();
            this.$nextTick(() => {
                this.$refs['TreeDrawer'].setData({ ...data }, type);
            });
        },
        addEqu() {
            const { categoryId } = this.selectedObj;
            this.view({ parentCategoryId: categoryId }, 0);
        },
        addOrg() {},
        edit() {
            const data = this.selectedObj;
            delete data.children;
            this.view(data, 1);
        },
        del() {
            const categoryId = this.selectedObj?.categoryId;
            if (categoryId) return;
            try {
                this.Api.delOceanusTree({ categoryId });
                this.$message.success('删除成功!');
                this.init();
            } catch (e) {
                this.$message.warning('删除失败!');
            }
        },
    },
};
</script>
