<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 :disabled="!treeNode">
                            <a-menu slot="overlay">
                                <a-menu-item
                                    key="1"
                                    @click="addOrg"
                                    :disabled="!(treeNode && treeNode.dataRef.catalogType !== 'EQUIPMENT')"
                                    >新增组织
                                </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="
                                selectedKeys.length === 0 || selectedObj.catalogType === 'ORGANIZATION'
                            "
                            >编辑</a-button
                        > 
                        <a-button
                            type="primary"
                            ghost
                            @click="del"
                            :disabled="selectedKeys.length === 0 || selectedObj.catalogType === 'ROOTNODE'"
                            >删除</a-button
                        > -->
                        <a-button
                            type="primary"
                            ghost
                            @click="edit"
                            :disabled="!(treeNode && treeNode.dataRef.catalogType === 'EQUIPMENT')"
                            >编辑</a-button
                        >
                        <a-button
                            type="primary"
                            ghost
                            @click="del"
                            :disabled="!(treeNode && treeNode.dataRef.catalogType !== 'ROOTNODE')"
                            >删除</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
                        ref="Tree"
                        :treeData="treeData"
                        :replaceFields="replaceFields"
                        :selectedKeys="selectedKeys"
                        @select="onSelect"
                        :load-data="onLoadData"
                    />
                </a-col>
            </a-row>
            <TreeDrawer ref="TreeDrawer" :refresh="treeDrawerRefresh" />
            <TreeModal ref="TreeModal" :parentNodeId="selectedKeys[0]" :afterSubmit="afterSubmit" />
        </my-card>
    </div>
</template>

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

export default {
    components: { TreeDrawer, TreeModal },
    data() {
        return {
            searchValue: undefined,
            dataSource: [],
            replaceFields: { title: 'catalogName', key: 'catalogId', children: 'children' },
            treeData: [],
            selectedKeys: [],
            allData: [],
            treeNode: undefined,
        };
    },
    model: {
        prop: 'value',
        event: 'change',
    },
    mounted() {
        this.init();
    },

    methods: {
        async init() {
            this.treeData = [];
            const parentNode = {
                catalogId: -1,
                catalogName: '根节点',
                catalogType: 'ROOTNODE',
                isLeaf: false,
            };
            this.treeData = [parentNode];
            this.allData = [...this.allData, parentNode];
            this.treeNode = undefined;
            this.selectedKeys = [];
        },
        onLoadData(treeNode) {
            return new Promise((resolve) => {
                Api.getEquipmentsTree({ catalogId: treeNode.dataRef.catalogId }).then((resp) => {
                    if (resp.length === 0) {
                        treeNode.dataRef.isLeaf = false;
                    } else {
                        this.allData = [...this.allData, ...resp];
                        treeNode.dataRef.children = resp;
                    }
                    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.selectedKeys = [val];
            this.searchValue = val;
            this.$emit('change', data);
        },
        async onSelect(selectedKeys, { node }) {
            this.treeNode = node;
            this.selectedKeys = selectedKeys;
            let data = {};
            if (selectedKeys.length !== 0) {
                const curData = node.dataRef;
                this.searchValue = undefined;
                if (curData.catalogType === 'EQUIPMENT') {
                    data = await Api.getEquipmentsInfo(curData);
                    Object.keys(data).forEach((key) => {
                        node.dataRef[key] = data[key];
                    });
                    data = {
                        ...data,
                        catalogId: curData.catalogId,
                        catalogType: curData.catalogType,
                        catalogName: curData.catalogName,
                    };
                    this.treeData = [...this.treeData];
                }
            }
            this.$emit('change', data);
        },
        async view(data = {}, type = 0) {
            this.$refs['TreeDrawer']?.open();
            this.$nextTick(() => {
                this.$refs['TreeDrawer'].setData({ ...data }, type);
            });
        },
        addEqu() {
            const data = { ...this.treeNode.dataRef };
            const { catalogId } = data;
            this.view({ parentCatalogId: catalogId, catalogType: 'EQUIPMENT' }, 0);
        },
        addOrg() {
            this.$refs.TreeModal.open();
        },
        afterSubmit() {
            this.onLoadData(this.treeNode);
        },
        edit() {
            const curData = { ...this.treeNode.dataRef };
            const data = {
                ...curData,
                installTime: curData.installTime && moment(curData.installTime, 'YYYY-MM-DD'),
                runTime: curData.runTime && moment(curData.runTime, 'YYYY-MM-DD'),
            };
            delete data.children;
            this.view(data, 1);
        },
        async del() {
            const data = { ...this.treeNode.dataRef };
            if (isObjEmpty(data)) return;
            try {
                await Api.delEquipmentsTree(data);
                this.$message.success('删除成功!');
                this.onLoadData(this.treeNode.$parent);
                this.treeNode = undefined;
                this.selectedKeys = [];
            } catch (e) {
                this.$message.warning('删除失败!');
            }
        },
        treeDrawerRefresh(type, data) {
            if (type === 0) {
                this.onLoadData(this.treeNode);
            }
            if (type === 1) {
                const { equipmentForm, catalogForm } = data;
                const { equipmentName } = equipmentForm;
                const { catalogId, catalogType, catalogName } = catalogForm;
                this.treeNode.dataRef.catalogName = equipmentName;
                const newData = {
                    ...equipmentForm,
                    catalogId,
                    catalogType,
                    catalogName,
                };
                this.treeData = [...this.treeData];
                this.$emit('change', newData);
            }
        },
    },
};
</script>
