<template>
    <div class="table-page">
        <div class="table-page-content">
            <div class="left-tree">
                <tree-side
                    ref="treeRef"
                    :customIcon="true"
                    :dataLoading="treeLoading"
                    :default-expand-all="true"
                    :defaultProps="defaultProps"
                    :tabList="['物资类型列表']"
                    :treeData="treeData"
                    :isAll="true"
                    :current="currentClassType"
                    isDeselect
                    @operateEvent="getClass"
                    node-key="id"
                    @node-click="nodeClick"
                >
                    <template v-slot:treeIcon="{ data }">
                        <div class="custom-tree-node">
                            <el-icon>
                                <Folder v-if="data.grade === '1'" />
                                <Film v-else />
                            </el-icon>
                        </div>
                    </template>
                </tree-side>
            </div>
            <div class="right-table">
                <div class="full-page">
                    <div class="main-table-container">
                        <div
                            :class="[
                                'search-wrapper',
                                { hide: !isShowSearch },
                                { show: isShowSearchAll }
                            ]"
                        >
                            <CustomSearch
                                :customOptionList="customOptionList"
                                :firstLineColumnCount="4"
                                :fixedOptionList="fixedOptionList"
                                @clearQuery="handleClearQuery"
                                @reset="handleReset"
                                @search="handleSearch"
                                @show-all="handleShowAll"
                            />
                        </div>
                        <div class="table-container">
                            <div ref="tableRef" class="table-content">
                                <div ref="btnGroupPanel" class="btn-box">
                                    <div class="left-btn-group">
                                        <!-- <el-button icon="Plus" type="primary" @click="handleAdd"
                                            >新增
                                        </el-button>
                                        <el-button
                                            :loading="downloadLoading"
                                            icon="Upload"
                                            type="success"
                                            @click="handleExport"
                                            >导入
                                        </el-button>
                                        <el-button
                                            icon="Download"
                                            type="warning"
                                            @click="handleExport"
                                            >导出
                                        </el-button> -->
                                        <el-button icon="Plus" type="primary" @click="handleMove"
                                            >绑定分类
                                        </el-button>
                                        <el-button
                                            icon="Delete"
                                            type="danger"
                                            @click="handleDelete()"
                                            >清除分类
                                        </el-button>
                                    </div>
                                    <div class="right-btn-group">
                                        <div
                                            :class="{ active: isShowSearch }"
                                            :title="isShowSearch ? '折叠搜索' : '展开搜索'"
                                            class="btn-group-item"
                                            @click="toggleSearch"
                                        >
                                            <el-icon>
                                                <Search />
                                            </el-icon>
                                        </div>
                                        <div
                                            class="btn-group-item"
                                            title="刷新列表"
                                            @click="refresh"
                                        >
                                            <el-icon>
                                                <Refresh />
                                            </el-icon>
                                        </div>
                                        <div
                                            ref="tableHeaderSettingBtn"
                                            class="btn-group-item"
                                            title="设置表头"
                                            @click="toggleSetting"
                                        >
                                            <el-icon>
                                                <Grid />
                                            </el-icon>
                                        </div>
                                        <div
                                            v-show="isShowSetting"
                                            ref="tableHeaderSettingRef"
                                            class="table-header-setting"
                                            tabindex="0"
                                            @focusout="handleSettingFocusOut"
                                        >
                                            <el-scrollbar>
                                                <el-checkbox
                                                    v-model="checkAll"
                                                    :indeterminate="isIndeterminate"
                                                    @change="handleCheckAllChange"
                                                    >全选
                                                </el-checkbox>
                                                <el-checkbox-group
                                                    v-model="currentColumnsKeys"
                                                    @change="handleCheckedChange"
                                                >
                                                    <el-checkbox
                                                        v-for="opt in columnsList"
                                                        :key="opt.prop"
                                                        :title="opt.title"
                                                        :value="opt.prop"
                                                        >{{ opt.title }}
                                                    </el-checkbox>
                                                </el-checkbox-group>
                                            </el-scrollbar>
                                        </div>
                                    </div>
                                </div>
                                <el-table
                                    ref="multipleSelection"
                                    v-loading="tableLoading"
                                    :data="tableData"
                                    border
                                    :tree-props="{
                                        children: 'children',
                                        hasChildren: 'hasChildren'
                                    }"
                                    class="table-list"
                                    element-loading-background="rgba(10 ,38 ,61, 0.9)"
                                    height="100%"
                                    row-key="id"
                                    stripe
                                    @select="handleSelect"
                                    @selection-change="handleSelectionChange"
                                >
                                    <el-table-column align="center" type="selection" width="55" />
                                    <el-table-column
                                        :index="
                                            (index: number) =>
                                                index +
                                                1 +
                                                (params.pageBean.page - 1) *
                                                    params.pageBean.pageSize
                                        "
                                        align="center"
                                        label="序号"
                                        type="index"
                                        width="80"
                                    />
                                    <template v-if="currentColumns.length">
                                        <el-table-column
                                            v-for="col in currentColumns"
                                            :key="col.prop"
                                            :formatter="
                                                col.formatter
                                                    ? col.formatter
                                                    : col.formatter === false
                                                      ? null
                                                      : (row) => row[col.prop] || '-'
                                            "
                                            :label="col.title"
                                            :min-width="col.minWidth"
                                            :prop="col.prop"
                                            :show-overflow-tooltip="
                                                col.showOverflowTooltip
                                                    ? col.showOverflowTooltip
                                                    : true
                                            "
                                            :sortable="col.sortable"
                                            align="center"
                                        >
                                        </el-table-column>
                                        <!-- <el-table-column align="center" label="操作" width="160">
                                            <template v-slot="{ row }">
                                                <div class="operation-buttons">
                                                    <el-link
                                                        type="primary"
                                                        underline="never"
                                                        @click="handleMove(row)"
                                                    >
                                                        绑定分类
                                                    </el-link>
                                                    <el-link
                                                        type="danger"
                                                        underline="never"
                                                        @click="handleDelete(row)"
                                                    >
                                                        清除分类
                                                    </el-link>
                                                </div>
                                            </template>
                                        </el-table-column> -->
                                    </template>
                                </el-table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <moveDialog
            ref="dialogRef"
            v-model:isShowAdd="isShowDialog"
            v-model:info="info"
            title="物资类型选择"
            @refresh="handleRefresh"
            @cancel="handleCancel"
        ></moveDialog>
    </div>
</template>

<script lang="ts" setup>
import moveDialog from '@/views/SupplierMonitor/ConfigManagement/MaterialClassificationManagement/moveDialog.vue'
import shaixuanIcon from '@/assets/img/common/icon-shaixuan.png'
import TreeSide from '@/components/TreeSide/index.vue'
import CustomSearch from '@/components/CustomSearch/index.vue'
import Pagination from '@/components/Pagination/index.vue'
import { refineRequestBody } from '@/utils/requestWrappers'
import { createAddHandler, createEditHandler } from '@/utils/routeNavigation'
import { generateTreeWithRoot } from '@/utils/treeGenerator'
import { getNodesByIds } from '@/utils/treeUtils'
import { useTableOptionConfig } from './hooks/useTableOptionConfig'
import { useSearch } from '@/hooks/useSearch'
import { usePagination } from '@/hooks/usePagination'
import {
    dataTable,
    dataDelete,
    dataSupplierClass,
    treeCount
} from '@/api/supplierMonitor/ConfigManagement/MaterialClassificationManagement'
onMounted(async () => {
    await getClassCount()
    await getClassList()
    loadData()
})
// 树列表
interface TreeNode {
    id: string
    name: string
    path_: string
    vehicleSum?: number
    grade?: string
    bridgeCode?: string
    bridgeShortName?: string
    children?: TreeNode[]

    [key: string]: any
}
const userDetail = ref<any>({})
const treeLoading = ref<boolean>(false)
const treeData = ref<TreeNode[]>([])
const treeItem = ref<TreeNode | null>(null)
const treeRef = ref<InstanceType<typeof TreeSide> | null>(null)
const defaultProps: {
    children: string
    label: string
    number: string
} = {
    children: 'children', //子节点
    label: 'name', //节点标签
    number: 'vehicleSum'
}

const nodeClick = (nodeItem: TreeNode): void => {
    console.log(nodeItem, 'nodeItem')
    treeItem.value = nodeItem || ({} as TreeNode)
    if (treeItem.value.id == 'root') {
        params.value.querys[2].value = ''
    } else {
        params.value.querys[2].value = treeItem.value.id
    }

    loadData()
}

function treeInit() {
    treeItem.value = treeData.value[0] || ({} as TreeNode)
    nextTick(() => {
        treeRef.value!.setCurrentKey(treeItem.value?.id || 'root')
        treeRef.value!.expandHandle(true, 3)
    })
    loadData()
}
/**
 * 移动物资类型
 */
const countList = ref<any[]>([])
const isShowDialog = ref(false)
const currentClassType = ref<string>('全部')

// 处理绑定分类成功后的刷新
const handleRefresh = async () => {
    await getClassCount()
    await getClassList()
    loadData()
}

// 处理取消操作，不进行刷新
const handleCancel = () => {
    // 取消操作不需要刷新数据
}
const info = ref<any>([])
const dialogRef = ref<InstanceType<typeof moveDialog> | null>(null)

const handleMove = async (row?: { id: string }) => {
    let ids: any = currentDataDel.value
    if (ids === undefined || ids === null || ids === '' || ids.length == 0) {
        ElMessage.error('请选择要绑定的数据')
        return
    }
    const storedData = localStorage.getItem('user')
    if (storedData) {
        userDetail.value = JSON.parse(storedData)
    }

    // 根据选中的ID递归获取id和名称数组
    const selectedData = getNodesByIds(tableData.value, ids)
    selectedData.map((item) => {
        item.enterpriseCode = userDetail.value.userDetail.org[0].orgCode
        item.enterpriseName = userDetail.value.userDetail.org[0].orgName
        item.enterpriseId = userDetail.value.userDetail.org[0].orgId
    })
    info.value = selectedData
    isShowDialog.value = true
}

// 获取树形绑定分类数量
const getClassCount = async () => {
    let params = {
        pageBean: {
            page: -1,
            pageSize: -1
        },
        querys: []
    }
    const value = await treeCount(params)
    countList.value = value.value
}
/**
 * table列表
 */

interface TableRow {
    id: string

    [key: string]: any
}

interface QueryParam {
    operation: string
    property: string
    value?: any
}

interface PageBean {
    pageSize: number
    page: number
    total: number
}

interface Params {
    pageBean: PageBean
    querys: QueryParam[]
    sorter: any[]
}
const tableData = ref<TableRow[]>([])
const tableLoading = ref<boolean>(false)

const params = ref<Params>({
    pageBean: { pageSize: 20, page: 1, total: 0 },
    querys: [
        { operation: 'LIKE', property: 'catNo' },
        { operation: 'LIKE', property: 'catName' },
        { operation: 'EQUAL', property: 'cted.id_', value: '' }
    ],
    sorter: []
})

const currentColumnsKeys = ref<string[]>(['catNo', 'catName', 'categoryName'])

const currentColumns = computed(() => {
    return columnsList.filter((col) => currentColumnsKeys.value.includes(col.prop))
})
async function loadData(): Promise<void> {
    try {
        tableLoading.value = true
        const query = refineRequestBody(params.value)
        const val = await dataTable(query)
        tableData.value = val.value
    } finally {
        tableLoading.value = false
    }
}

const getClassList = async () => {
    treeLoading.value = true
    let params = {
        pageBean: {
            page: -1,
            pageSize: -1
        },
        querys: [
            { group: 'main', operation: 'EQUAL', property: 'status', relation: 'AND', value: '1' }
        ]
    }
    const { total = 0, rows = [] } = await dataSupplierClass(params)

    // 递归更新树形数据的名称和数量
    const updateTreeWithCount = (nodes) => {
        nodes.forEach((node) => {
            const countItem = countList.value.find((item) => item.id === node.id)
            if (countItem) {
                node.vehicleSum = countItem.countNum
            } else {
                node.vehicleSum = 0
            }
            if (node.children && node.children.length > 0) {
                updateTreeWithCount(node.children)
            }
        })
    }

    updateTreeWithCount(rows)

    // 计算总数量
    const totalCount = countList.value.reduce((sum, item) => sum + (item.countNum || 0), 0)

    treeData.value = generateTreeWithRoot(rows, {
        rootLabel: `全部(${totalCount})`,
        rootId: 'root'
    })
    treeLoading.value = false

    // 初始化树选中状态
    nextTick(() => {
        if (!treeItem.value && treeData.value.length > 0) {
            treeItem.value = treeData.value[0]
            treeRef.value?.setCurrentKey('root')
        }
    })
}
const { customOptionList, fixedOptionList, columnsList } = useTableOptionConfig({})

/**
 * 查询相关
 */

const {
    tableHeaderSettingRef,
    isShowSearch,
    isShowSearchAll,
    isShowSetting,
    currentDataDel,
    toggleSearch,
    isIndeterminate,
    checkAll,
    handleShowAll,
    toggleSetting,
    handleSettingFocusOut,
    handleSelectionChange,
    refresh,
    handleClearQuery,
    handleReset,
    handleSearch,
    handleCheckedChange,
    handleCheckAllChange
} = useSearch({
    params: params.value,
    loadData,
    columnsList,
    currentColumnsKeys
})

const { handleSizeChange, handleCurrentChange } = usePagination({
    params: params.value,
    loadData
})

const downloadLoading = ref(false)

const handleExport = async () => {
    try {
        downloadLoading.value = true
        const res = await exportData(refineRequestBody(params.value))
        if (res) {
            ElMessage.success('导出成功')
        } else {
            ElMessage.error('导出失败')
        }
    } catch (error) {
        console.log(error)
    } finally {
        downloadLoading.value = false
    }
}
const getClass = async (data: any) => {
    currentClassType.value = data
    if (data == '全部') {
        params.value.querys[2].operation = 'EQUAL'
        params.value.querys[2].value = ''
        loadData()
    }
    if (data == '已分类') {
        params.value.querys[2].operation = 'NOTNULL'
        params.value.querys[2].value = 'NULL'
        loadData()
    }
    if (data == '未分类') {
        params.value.querys[2].operation = 'IS_NULL'
        params.value.querys[2].value = 'NULL'
        loadData()
    }
}
const handleDelete = async (row?: { id: string }): Promise<void> => {
    let ids: string = row ? row.id : currentDataDel.value
    if (ids === undefined || ids === null || ids === '') {
        {
            ElMessage.error('请选择要删除的数据')
            return
        }
    }
    ElMessageBox.confirm('确定删除选中的数据吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const { state } = await dataDelete(ids)
            if (state == true) {
                ElMessage.success(`删除成功`)
                await loadData()
                await getClassCount()
                await getClassList()
            } else {
                ElMessage.error(`删除失败`)
                await loadData()
            }
        } catch (error) {
            ElMessage.error(error || '删除失败')
        }
    })
}

/**
 * 跳转页面相关
 */
const basePath: string = 'SupplierMonitor/ConfigManagement/MaterialClassificationManagement' // 基础路径 （当前页面路径）

const handleAdd = (): void => {
    createAddHandler({
        basePath,
        componentUrl:
            '/src/views/SupplierMonitor/ConfigManagement/MaterialClassificationManagement/addEdit.vue',
        routeParams: {}
    })
}

const handleEdit = (row: { id: string; type: string }): void => {
    createEditHandler({
        basePath,
        componentUrl:
            '/src/views/SupplierMonitor/ConfigManagement/MaterialClassificationManagement/addEdit.vue',
        routeParams: {
            id: row.id
        }
    })
}
</script>

<style lang="scss" scoped>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}

.tree-item-custom {
    width: calc(100% - 30px);
    display: flex;
    align-items: center;
    justify-content: flex-start;

    .custom-node-text {
        font-size: 14px;
        margin-left: 5px;
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .tree-add-btn {
        margin-left: 8px;
        flex-shrink: 0;
    }
}
</style>
