<template>
    <div
        v-loading.fullscreen.lock="loading.isLoading"
        class="treeOperations"
    >
        <h4>{{ $t(config.title) }}</h4>
        <!--操作按钮下拉框-->
        <info-drop-down
            :key="keyUp"
            :row="ddConfig"
        />
        <!-- schema,datasource,dataset 列表弹窗 移动 -->
        <info-resource
            ref="resource_dir"
            :config="{isShowTable: false, rowKey: 'id'}"
            @handleSelectionChange="moveSave"
            @treeCurrentData="selectTreeCurrentData"
        />
        <info-dialog
            :options="options"
            @closeDialog="closeDialog"
            @confirmDialog="save"
        >
            <el-form
                ref="refForm"
                :model="dialog.entity"
                :rules="rules"
                label-width="100px"
                @submit.prevent
            >
                <el-form-item
                    :label="$t('name')"
                    test-cy="name"
                    prop="name"
                >
                    <el-input
                        v-model="dialog.entity.name"
                        required
                    />
                </el-form-item>
            </el-form>
        </info-dialog>
        <!-- sortDir 排序弹框-->
        <info-dialog
            :options="sortOptions"
            @closeDialog="closeDialog"
            @confirmDialog="saveSort"
        >
            <el-tree
                :data="sortTree.list"
                node-key="id"
                default-expand-all
                :allow-drop="allowDrop"
                draggable
            >
                <template #default="{ data }">
                    {{ data.name }}
                </template>
            </el-tree>
        </info-dialog>
    </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, watch } from 'vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import type { AllowDropType } from 'element-plus/es/components/tree/src/tree.type'
import { FolderAdd, Sort, Rank, Delete, EditPen, Upload } from '@element-plus/icons-vue'
import infoDialog from '../infoDialog/index.vue'

import infoDropDown from '../infoDropdown/index.vue'
import { RowInterface } from '../infoDropdown/index'
import { __getItem, __setItem, ObjectInterface, serverApi } from '../../script'
import { DialogInterface, ListInterface, NameInterface } from './index'
import InfoResource from '../../businessComponents/infoResource/index.vue'
import api from './api/tree'

export default defineComponent({
    name: 'InfoTreeOperations',
    components: {
        InfoResource,
        infoDialog,
        infoDropDown
    },
    props: {
        /**
         * title：如资源目录，流程目录，项目目录等
         * isShowOperBtn: 是否显示操作按钮
         */
        config: {
            type: Object,
            default: () => {
            }
        },
        nodeData: {
            // 被选中的的node数据
            type: Object,
            default: () => {
            }
        }
    },
    emits: ['addDatas', 'saveDir', 'removeDir', 'moveDir', 'sortDir', 'exportDir'],
    setup (props, { emit, expose }) {
        let iconMap = {
            addDatas: FolderAdd,
            add: FolderAdd,
            move: Rank,
            sort: Sort,
            remove: Delete,
            export: Upload,
            rename: EditPen
        }
        let resource_dir = ref()
        // eslint-disable-next-line vue/no-setup-props-destructure
        let { nodeData, config } = props
        const refForm = ref()
        const rules = reactive<NameInterface>({
            name: [
                { required: true, message: 'pleaseInputName', trigger: 'blur' },
                { max: 30, message: 'nameMaxLength', trigger: 'blur' }
            ]
        })
        const sortTree = reactive<ListInterface>({ list: [] })
        const resId = ref()
        const keyUp = ref<number>(0)
        const routeName = location.pathname
        const loading = reactive<ObjectInterface>({
            isLoading: false
        })
        const dialog = reactive<DialogInterface>({
            entity: { // 新建重命名弹框的数据
                name: '',
                parentId: nodeData?.id,
                resType: nodeData?.resType || 'flow_dir'
            },
            isShowExportDialog: false, // 导出弹窗
            exportEntity: { // 导出弹窗数据
                resourceId: '', // 导出的目录
                withDependencies: false, // 是否级联导出
                withChildDir: false// 是否包含子目录
            },
            title: 'add'
        })
        // 新建/重命名 弹窗
        let options = reactive({
            width: '50%',
            isShowBtn: true,
            title: dialog.title,
            isShowDialog: false,
            clickModalClose: false
        })
        // 排序 弹窗
        const sortOptions = reactive({
            width: '50%',
            title: 'sort',
            isShowDialog: false,
            isShowBtn: true,
            clickModalClose: false
        })
        const isAdmin = ref<boolean>(true)
        const ddConfig = reactive<RowInterface>({
            title: () => 'operation',
            show: () => config.isShowOperBtn,
            size: 'default',
            method: (command: any) => {
                operations(command)
            },
            class: 'infoTree',
            disabled: () => !nodeData.id || config.disabled?.(nodeData) || nodeData.selected === 0,
            dropdown: () => config?.operBtns.filter((item: ObjectInterface) => item.isShow).map((item: ObjectInterface) => {
                item.icon = iconMap[item.command]
                return item
            })
        })
        const selectTreeCurrentData = (data: ObjectInterface): void => { // 点击树节点调用
            // 选择存放位置，被选中的tree数据
            resId.value = data.id
        }
        const isShowOperation = (nodeData: ObjectInterface): void => { // 按钮显示与否的判断
            // eslint-disable-next-line complexity
            let isShow = (type: string) => {
                switch (type) {
                    case 'add':
                        return !!nodeData?.id
                    case 'export':
                        return !!nodeData?.id
                    case 'remove':
                        return !!nodeData?.id && nodeData.parentId
                    case 'rename':
                        return !!nodeData?.id && nodeData.parentId
                    case 'move':
                        return !!nodeData?.id && nodeData?.parentId
                    case 'sort':
                        return !!nodeData?.id && nodeData.children && nodeData.children.length > 1
                    case 'addDatas':
                        return !nodeData.children || nodeData.children.length <= 0
                }
            }
            config?.operBtns.forEach((item: ObjectInterface) => {
                item.isShow = item.display !== undefined ? item.display() : isShow(item.command)
            })
            keyUp.value += 1
        }
        // eslint-disable-next-line complexity
        const operations = (option: string): void => { // 操作方法
            hiddenDialog()
            switch (option) {
                case 'add':
                    addDir()
                    break
                case 'remove':
                    removeDir()
                    break
                case 'rename':
                    renameDir()
                    break
                case 'move':
                    moveDir()
                    break
                case 'sort':
                    sortDir()
                    break
                case 'export':
                    exportDir()
                    break
                case 'addDatas':
                    emit('addDatas')
            }
        }
        const hiddenDialog = (): void => { // 其余弹框都为不显示
            dialog.isShowSortDialog = false
            dialog.isShowExportDialog = false
            dialog.isShowDialog = false
        }
        const closeDialog = (): void => { // 关闭弹框
            options.isShowDialog = false
            sortOptions.isShowDialog = false
        }
        const getAddEntityDefault = (): void => { // 设置新建entity的默认值
            dialog.entity = {
                name: '',
                parentId: nodeData.id,
                resType: nodeData.resType
            }
        }
        const addDir = (): void => { // 新建目录
            getAddEntityDefault()
            options.title = 'add'
            options.isShowDialog = true
        }
        const renameDir = (): void => { // 目录重命名
            getAddEntityDefault()
            dialog.entity = { ...dialog.entity, ...nodeData }
            options.title = 'rename'
            options.isShowDialog = true
        }
        // 新建和重命名的save
        const save = (): void => {
            let data: object = { ...dialog.entity }
            refForm.value.validate((valid: boolean) => {
                if (valid) {
                    // closeDialogAdd()
                    emit('saveDir', data)
                }
            })
        }
        // 删除目录
        const removeDir = (): void => {
            emit('removeDir', nodeData)
            const _nodeData = __getItem('nodeData')
            delete _nodeData[routeName]
            __setItem('nodeData', _nodeData)
        }
        // 移动目录
        const moveDir = () => {
            const typeMap = {
                datasource_dir: 'datasource',
                poseidon_task_dir: 'task',
                dataset_dir: 'dataset',
                suppl_stragy_dir: 'supplement',
                schema_dir: 'schema'
            }
            resource_dir.value.init(typeMap[nodeData.resType] || nodeData.resType)
        }
        // 移动的保存
        const moveSave = () => {
            emit('moveDir', resId.value, nodeData.id)
        }
        // 目录排序
        const sortDir = (): void => {
            // 只查询一级数据
            serverApi({
                params: { id: props.nodeData.id },
                interface: config.sortApi || api.resourceChildren,
                success: (res: any) => {
                    sortTree.list = res
                }
            })
            sortOptions.isShowDialog = true

        }
        const allowDrop = (araggingNode: Node, dropNode: Node, type: AllowDropType) => {
            return type !== 'inner'
        }
        const saveSort = () => {
            emit('sortDir', sortTree.list)
        }
        // 目录导出由对应业务模块处理
        const exportDir = () => {
            emit('exportDir')
        }
        watch(() => props.nodeData, (newValue) => {
            newValue && (nodeData = newValue)
            isShowOperation(nodeData)
        }, {
            immediate: true,
            deep: true
        })
        isAdmin.value = __getItem('isAdmin')?.toString() === 'true'
        // hiddenDialog()
        expose({
            closeDialog
        })

        return {
            refForm,
            rules,
            sortTree, // 存储排序树节点
            loading,
            dialog,
            options,
            ddConfig,
            keyUp,
            sortOptions,
            selectTreeCurrentData,
            closeDialog,
            save,
            moveSave,
            allowDrop,
            saveSort,
            resource_dir
        }
    }
})
</script>

<style lang="scss" scoped>
.treeOperations {
    width: 100%;
    height: 60px;
    line-height: 60px;
    padding-left: 10px;
    border-bottom: 1px solid #eee;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
    h4 {
        float: left;
        margin-left: 5px;
    }
    .info-dropdown {
        float: right;
        margin-right: 10px;
    }
}
</style>
