<template>
    <hc-drawer v-model="isShow" to-id="hc-main-box" is-close @close="drawerClose">
        <hc-body split>
            <template #left>
                <hc-card scrollbar>
                    <template #header>
                        <hc-search-input v-model="searchTreeName" placeholder="请输入关键字" @search="searchTreeNameClick" />
                    </template>
                    <template v-if="isTreeMode === 1">
                        <hc-lazy-tree
                            v-if="isShow" :root-menu="treeMenuRoot" is-load-menu :h-props="treeProps" tree-key="id"
                            @load-menu="treeLazyMenu" @load="treeLoadNode" @node-tap="treeNodeTap" @menu-tap="treeMenuClick"
                        >
                            <template #name="{ data }">
                                <span class="text-16px font-400">{{ data.name }}</span>
                            </template>
                        </hc-lazy-tree>
                    </template>
                    <template v-if="isTreeMode === 2">
                        <hc-data-tree
                            ref="treeRef" :root-menu="treeMenuRoot" is-load-menu :h-props="treeProps" tree-key="id" :datas="treeData"
                            @load-menu="treeDataMenu" @node-tap="treeNodeTap" @menu-tap="treeMenuClick"
                        >
                            <template #name="{ data }">
                                <span class="text-16px font-400">{{ data.name }}</span>
                            </template>
                        </hc-data-tree>
                    </template>
                </hc-card>
            </template>
            <hc-card>
                <template #header>
                    <template v-if="isCheckd">
                        <template v-if="tableTempExcelProps.file">
                            <div class="table-temp-name truncate">
                                <span>{{ tableTempExcelProps.title }}</span>
                                <i class="i-iconoir-check-circle-solid" />
                            </div>
                            <el-upload
                                ref="file1Ref" :auto-upload="false" :show-file-list="false" action="#"
                                :limit="1" :file-list="fileList" accept=".xls,.xlsx" :on-change="uploadChange"
                            >
                                <el-button hc-btn type="primary">重新上传</el-button>
                            </el-upload>
                            <el-button class="ml-2" hc-btn type="danger" @click="delectExcelMS">删除</el-button>
                            <el-button hc-btn type="success" @click="downloadExcel">下载Excel</el-button>
                        </template>
                        <template v-else>
                            <el-upload
                                ref="file2Ref" :auto-upload="false" :show-file-list="false" action="#" :limit="1"
                                :file-list="fileList" accept=".xls,.xlsx" :on-change="uploadChange"
                            >
                                <el-button hc-btn type="primary">上传Excel</el-button>
                            </el-upload>
                        </template>
                        <template v-if="excelInfo.templateExtension">
                            <div class="table-temp-name truncate">
                                <span>{{ excelInfo.templateExtension }}</span>
                                <i class="i-iconoir-check-circle-solid" />
                            </div>
                            <el-button hc-btn type="danger" @click="delectExcelMSModel">删除</el-button>
                            <el-button hc-btn type="success" @click="downloadExcelModel">下载模板</el-button>
                        </template>
                    </template>
                    <template v-else>
                        <div class="text-red">该目录为根目录没有EXCEL文件</div>
                    </template>
                </template>
                <template #extra>
                    <el-button v-if="tableTempExcelProps.file" hc-btn type="primary" @click="fullScreenClick">全屏显示</el-button>
                </template>
                <div :id="tableTempExcelId" class="relative h-full">
                    <hc-online-office v-if="isShow" ui="hc-table-temp-excel" :props="tableTempExcelProps" />
                </div>
            </hc-card>
        </hc-body>
        <!-- 新增清表 -->
        <HcAddExcel v-model="addExcelShow" :info="addExcelInfo" :type="addExcelType" @finish="pseudoRefresh" />
        <!-- 调整排序 -->
        <HcTreeSort v-model="treeSortShow" :data="treeSortData" @finish="pseudoRefresh" />
        <!-- 上传Excel表格 -->
        <HcExcelUpload v-model="excelUploadShow" :data="excelUploadData" @finish="pseudoRefresh" />
    </hc-drawer>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useAppStore } from '~src/store'
import screenfull from 'screenfull'
import { HcDelMsg } from 'hc-vue3-ui'
import { ElLoading } from 'element-plus'
import { getArrValue, getObjValue, getRandom, isNullES, newDownBlob } from 'js-fast-way'
import HcAddExcel from './add-excel.vue'
import HcTreeSort from './tree-sort.vue'
import HcExcelUpload from './excel-upload.vue'
import mainApi from '~api/exctab/exceltab'

const props = defineProps({
    data: {
        type: Object,
        default: () => ({}),
    },
})

//事件
const emit = defineEmits(['close'])
const store = useAppStore()
const userInfo = ref(store.getUserInfo)

//双向绑定
const isShow = defineModel('modelValue', {
    default: false,
})

//监听数据
const dataInfo = ref(props.data)
watch(() => props.data, (data) => {
    dataInfo.value = data
}, { immediate: true, deep: true })

//监听显示
watch(isShow, (val) => {
    if (val) getDataApi()
})

//处理相关数据
const tableTempExcelId = ref('')
const getDataApi = () => {
    tableTempExcelId.value = getRandom(6)
}

//树搜索
const isTreeMode = ref(1) //1懒加载，2全加载
const searchTreeName = ref('')
const searchTreeNameClick = async () => {
    if (isNullES(searchTreeName.value)) {
        isTreeMode.value = 1
    } else {
        isTreeMode.value = 2
        await getTreeAllData()
        treeRef.value?.treeRef?.filter(searchTreeName.value)
    }
}

//树配置
const treeRef = ref(null)
const treeProps = {
    label: 'name',
    children: 'children',
    isLeaf: (item) => {
        return !item.hasChildren
    },
}

//树菜单根节点
const treeMenuRoot = [
    { icon: 'add-circle', label: '新增', key: 'add' },
    { icon: 'delete-bin', label: '删除', key: 'del' },
]

//懒加载树的菜单
const treeLazyMenu = ({ item, level }, resolve) => {
    let newMenu = []
    if (item.fileType !== 3) {
        newMenu.push({ icon: 'add-circle', label: '新增', key: 'add' })
    }
    if (item.fileType !== 1) {
        newMenu.push({ icon: 'draft', label: '编辑', key: 'edit' })
    }
    if (level !== 1) {
        newMenu.push({ icon: 'arrow-up-down', label: '排序', key: 'rank' })
    }
    if (item.fileType !== 3) {
        newMenu.push({ icon: 'file-upload', label: '上传', key: 'upload' })
    }
    newMenu.push({ icon: 'delete-bin', label: '删除', key: 'del' })
    resolve(newMenu)
}


//全加载树的菜单
const treeDataMenu = ({ node, item, level }, resolve) => {
    const { isLeaf } = node
    let newMenu = []
    if (item.fileType !== 3) {
        newMenu.push({ icon: 'add-circle', label: '新增', key: 'add' })
    }
    if (item.fileType !== 1) {
        newMenu.push({ icon: 'draft', label: '编辑', key: 'edit' })
    }
    if (isLeaf) {
        newMenu.push({ icon: 'sort-asc', label: '排序', key: 'rank' })
    }
    if (level !== 1) {
        newMenu.push({ icon: 'file-upload', label: '上传', key: 'upload' })
    }
    newMenu.push({ icon: 'delete-bin', label: '删除', key: 'del' })
    resolve(newMenu)
}

//菜单被点击
const treeMenuClick = ({ key, data, node }) => {
    console.log(key)
    if (key === 'add') {
        addExcelInfo.value = getObjValue(data)
        addExcelType.value = '新增'
        addExcelShow.value = true
    } else if (key === 'edit') {
        addExcelInfo.value = getObjValue(data)
        addExcelType.value = '编辑'
        addExcelShow.value = true
    } else if (key === 'rank') {
        treeSortData.value = {
            parentId: node?.parent?.data?.id ?? '',
            modeId: dataInfo.value.id,
        }
        treeSortShow.value = true
    } else if (key === 'upload') {
        excelUploadData.value = data
        excelUploadShow.value = true
        console.log(data)
    } else if (key === 'del') {
        if (data.hasChildren) {
            window.$message.warning('该节点下有子节点，无法删除')
            return false
        }
        HcDelMsg(async (resolve) => {
            const { code } = await mainApi.del(data.id)
            resolve() //关闭弹窗的回调
            if (code === 200) {
                window.$message.success('删除成功')
                pseudoRefresh()
            }
        })
    }
}

//新增/编辑清表
const addExcelShow = ref(false)
const addExcelInfo = ref({})
const addExcelType = ref('')

//调整排序
const treeSortShow = ref(false)
const treeSortData = ref({})

//上传文件
const excelUploadShow = ref(false)
const excelUploadData = ref({})

//伪刷新
const pseudoRefresh = () => {
    const val = isTreeMode.value
    isTreeMode.value = 4
    tableTempExcelProps.value = {}
    setTimeout(()=> {
        isTreeMode.value = val
    }, 500)
}

//全加载树
const treeData = ref([])
const getTreeAllData = async () => {
    const { data } = await mainApi.tabLazyTreeAll({
        modeId: dataInfo.value.id,
        //name: searchTreeName.value,
        name: '',
    })
    treeData.value = getArrValue(data)
}

//懒加载树
const treeLoadNode = async ({ item, level }, resolve) => {
    const parentId = level === 0 ? 0 : item.id
    const { data } = await mainApi.tabLazyTree({
        parentId: parentId,
        modeId: dataInfo.value.id,
    })
    resolve(getArrValue(data))
}

//在线编辑表格文件的配置
const tableTempExcelProps = ref({})

//树节点被点击
const nodeInfo = ref({})
const isCheckd = ref(false)
const treeNodeTap = ({ data }) => {
    nodeInfo.value = data
    isCheckd.value = !data.hasChildren || data.fileType === 3
    if (isCheckd.value) {
        getDetailExcel(data.id)
    } else {
        tableTempExcelProps.value = {}
    }
}

//获取模板详情
const excelInfo = ref({})
const getDetailExcel = async (dataId) => {
    const { code, data } = await mainApi.detailExcel(dataId)
    if (code !== 200) return
    const { id, extension, fileUrl } = getObjValue(data)
    const { user_id, user_name } = userInfo.value
    excelInfo.value = getObjValue(data)
    tableTempExcelProps.value = {
        type: 'xlsx',
        key: id + '_' + Math.random() + '',
        title: extension,
        file: fileUrl,
        userId: user_id,
        userName: user_name,
    }
}

//上传
const file1Ref = ref(null)
const file2Ref = ref(null)
const fileList = ref([])

//文件选择
const uploadChange = async (file) => {
    const loading = ElLoading.service({
        text: '上传文件中...',
    })
    const form = excelInfo.value
    fileList.value = [file.raw]
    let formData = new FormData()
    formData.append('file', ...fileList.value)
    formData.append('nodeId', form.id)
    const temp = tableTempExcelProps.value
    if (temp.file && temp.file.length >= 2) {
        formData.append('type', 2)
    } else {
        formData.append('type', 1)
    }
    const { code } = await mainApi.uploadExcel(formData)
    loading.close()
    if (code === 200) {
        window.$message.success('保存成功')
        pseudoRefresh()
    }
    if (file1Ref.value) {
        file1Ref.value?.clearFiles()
    }
    if (file2Ref.value) {
        file2Ref.value?.clearFiles()
    }
}

//删除
const delectExcelMS = () => {
    HcDelMsg(async (resolve) => {
        const form = excelInfo.value
        const { code } = await mainApi.deleteExcel({
            id: form.id,
            fileUrl: '',
        })
        resolve() //关闭弹窗的回调
        if (code === 200) {
            window.$message.success('删除成功')
            pseudoRefresh()
        }
    })
}

//下载Excel
const downloadExcel = async () => {
    const form = excelInfo.value
    const { val } = await mainApi.downExcelFile(form.id)
    newDownBlob(val).then()
}

//删除
const delectExcelMSModel = () => {
    HcDelMsg(async (resolve) => {
        const form = excelInfo.value
        const { code } = await mainApi.deleteExcelModel({
            id: form.id,
            fileUrl: '',
        })
        resolve() //关闭弹窗的回调
        if (code === 200) {
            window.$message.success('删除成功')
            pseudoRefresh()
        }
    })
}

//下载模板
const downloadExcelModel = async () => {
    const form = excelInfo.value
    const { val } = await mainApi.downExcelFileModel(form.id)
    newDownBlob(val).then()
}

//全屏显示
const fullScreenClick = () => {
    // 判断是否支持
    if (!screenfull.isEnabled) {
        window.$message.warning('当前浏览器不支持全屏')
        return false
    }
    //指定全屏区域元素
    const element = document.getElementById(tableTempExcelId.value)
    if (element) screenfull.request(element)
}

//关闭抽屉
const drawerClose = () => {
    isShow.value = false
    tableTempExcelProps.value = {}
    emit('close')
}
</script>

<style scoped lang="scss">
.table-temp-name {
    position: relative;
    box-sizing: border-box;
    min-width: 200px;
    height: 28px;
    border: 1px solid gainsboro;
    padding: 0 10px;
    border-radius: 3px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-right: 10px;
    font-size: 14px;
    i {
        color: #00a870;
        margin-left: 10px;
    }
}
.hc-table-temp-excel {
    position: relative;
}
</style>
