<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="false"
                    :defaultProps="defaultProps"
                    :tabList="['企业供应商列表']"
                    :treeData="treeData"
                    isDeselect
                    node-key="id"
                    @node-click="nodeClick"
                >
                    <template v-slot:treeIcon="{ data }">
                        <el-icon>
                            <Folder v-if="data.grade === '1'" />
                            <Film v-else />
                        </el-icon>
                    </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
                                            icon="Download"
                                            type="warning"
                                            @click="handleDownload"
                                            >导出
                                        </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 class="grid-list">
                                        <i
                                            :class="[
                                                'fvue-icon',
                                                'fvue-icon-leibie',
                                                { activeGrid: activeGrid == 'list' }
                                            ]"
                                            @click="changeGrid('list')"
                                        ></i>
                                        <i
                                            :class="[
                                                'fvue-icon',
                                                'fvue-icon-liebiao1',
                                                { activeGrid: activeGrid == 'block' }
                                            ]"
                                            @click="changeGrid('block')"
                                        ></i>
                                    </div>
                                </div>

                                <div class="table-list" v-if="activeGrid == 'block'">
                                    <div v-for="value in tableData" :key="value.id" class="table-item">
                                        <div class="table-item-title">
                                            <el-icon size="16">
                                                <folder-opened />
                                            </el-icon>
                                            <div>版本号:1</div>
                                        </div>
                                        <div class="table-item-content">
                                            <div class="table-item-content-left">
                                                <img src="@/assets/img/common/empty.png" alt="" />
                                            </div>
                                            <div class="table-item-content-right">
                                                <div class="table-item-content-right-title">
                                                    {{value.name}}
                                                </div>
                                                <div class="table-item-content-right-info">
                                                    <div>资质编码：{{value.code}}</div>
                                                    <div>资质所属：{{ value.qualificationAttribution }}</div>
                                                    <div>有效开始期：{{ value.issueDate }}</div>
                                                    <div v-if="value.timeLimit==0">有效截止期：{{ value.validUntil }}</div>
                                                    <div v-if="value.timeLimit==1">有效截止期：长期</div>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="table-item-footer">
                                            <div class="table-item-footer-text" @click="handleEdit(value)">编辑</div>
                                            <div style="margin-left: 10px;" class="table-item-footer-delete" @click="handleDelete(value)">删除</div>
                                        </div>
                                    </div>
                                </div>
                                <el-table
                                    ref="multipleSelection"
                                    v-loading="tableLoading"
                                    :data="tableData"
                                    border
                                    v-else
                                    class="table-list"
                                    element-loading-background="rgba(10 ,38 ,61, 0.9)"
                                    height="100%"
                                    style="width: 100%;"
                                    row-key="id"
                                    stripe
                                    @selection-change="handleSelectionChange"
                                >
                                    <el-table-column type="selection" align="center" width="55" />
                                    <el-table-column
                                        :index="
                                            (index) =>
                                                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"
                                        >
                                            <template v-if="col.render" v-slot="{ row }">
                                                <template v-if="col.prop === 'qualificationAttribution'">
                                                    {{ dictionaryEscape('zzss', row.qualificationAttribution) }}
                                                </template>
                                                <template v-if="col.prop === 'industry'">
                                                    {{ dictionaryEscape('hyfl', row.industry) }}
                                                </template>
                                                <template v-if="col.prop === 'timeLimit'">
                                                    <div v-if="row.timeLimit==0">限时</div>
                                                    <div v-if="row.timeLimit==1">长期</div>
                                                </template>
                                                <template v-if="col.prop === 'stauts'">
                                                    {{ dictionaryEscape('qyzzkzt', row.status) }}
                                                </template>
                                                <template v-if="col.prop === 'validUntil'">
                                                    <div v-if="row.timeLimit==0">{{ row.validUntil }}</div>
                                                    <div v-if="row.timeLimit==1">长期</div>
                                                </template>
                                            </template>
                                        </el-table-column>
                                        <el-table-column
                                            align="center"
                                            label="操作"
                                            fixed="right"
                                            show-overflow-tooltip
                                            width="160"
                                        >
                                            <template v-slot="{ row }">
                                                <div class="operation-buttons">
                                                    <el-link
                                                        type="primary"
                                                        underline="never"
                                                        @click="handleEdit(row)"
                                                    >
                                                        编辑
                                                    </el-link>
                                                    <el-link
                                                        type="danger"
                                                        underline="never"
                                                        @click="handleDelete(row)"
                                                    >
                                                        删除
                                                    </el-link>
                                                </div>
                                            </template>
                                        </el-table-column>
                                    </template>
                                </el-table>
                                <pagination
                                    ref="paginationPanel"
                                    :pageResult="params.pageBean"
                                    @size-change="handleSizeChange"
                                    @current-change="handleCurrentChange"
                                />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import CustomSearch from '@/components/CustomSearch/index.vue'
import Pagination from '@/components/Pagination/index.vue'
import { dictionaryEscape, getDictionaryByCode } from '@/utils/dictionary'
import { refineRequestBody } from '@/utils/requestWrappers'
import { createAddHandler, createEditHandler } from '@/utils/routeNavigation'
import { useTableOptionConfig } from './hooks/useTableOptionConfig'
import { useSearch } from '@/hooks/useSearch'
import { usePagination } from '@/hooks/usePagination'
import TreeSide from '@/components/TreeSide/index.vue'
import { onMounted, reactive, ref, computed } from 'vue'
import { dataTable, dataDelete } from '@/api/supplierMonitor/BasicManagement/EnterpriseLibrary'
onMounted(() => {
    treeInit()
    loadData()
})

/**
 * 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[]
}

interface TreeNode {
    id: string
    name: string
    path_: string
    vehicleSum?: number
    grade?: string
    bridgeCode?: string
    bridgeShortName?: string
    children?: TreeNode[]

    [key: string]: any
}

const treeLoading = ref<boolean>(false)
const treeData = ref<TreeNode[]>([
    {
        id: '1',
        name: 'A企业',
        path_: '1',
        vehicleSum: 100,
        grade: '1',
        children: [
            {
                id: '1-1',
                name: 'B企业',
                path_: '1-1',
                vehicleSum: 20,
                grade: '1-1'
            },
            {
                id: '1-2',
                name: 'C企业',
                path_: '1-2',
                vehicleSum: 30,
                grade: '1-2'
            },
            {
                id: '1-3',
                name: 'D企业',
                path_: '1-3',
                vehicleSum: 50,
                grade: '1-3'
            }
        ]
    }
])
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 activeGrid = ref('list')
const nodeClick = (nodeItem: TreeNode): void => {
    // treeItem.value = nodeItem || ({} as TreeNode)
    // params.value.pageBean.page = 1
    // params.value.pageBean.pageSize = 20
    // 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 tableData = ref<TableRow[]>([])
const tableLoading = ref<boolean>(false)

const params = ref<Params>({
    pageBean: { pageSize: 20, page: 1, total: 0 },
    querys: [
        { operation: 'LIKE', property: 'code' },
        { operation: 'LIKE', property: 'enterpriseName' },
        { operation: 'LIKE', property: 'name' },
        { operation: 'EQUAL', property: 'industry' },
        { operation: 'LIKE', property: 'issueDate' },
        { operation: 'LIKE', property: 'issuingAuthority' },
        { operation: 'EQUAL', property: 'e.REGIS_TYPE_' },
        { operation: 'EQUAL', property: 'timeLimit' },
        { operation: 'LIKE', property: 'validUntil' },
        { operation: 'BETWEEN', property: 'createTime' },
        { operation: 'EQUAL', property: 'status' }
    ],
    sorter: [
        {
            direction: 'DESC',
            property: 'createTime'
        }
    ]
})

const currentColumnsKeys = ref<string[]>([
    'code',
    'enterpriseName',
    'name',
    'industry',
    'issueDate',
    'issuingAuthority',
    'qualificationAttribution',
    'timeLimit',
    'validUntil',
    'createTime',
    'status',
    'qualificationCategoryName',
    'remarks',
    'createTime'
])
// 切换页面列表展示方式
const changeGrid = (name: string) => {
    activeGrid.value = name
}
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 { total = 0, rows = [] }: { total: number; rows: TableRow[] } = await dataTable(query)
        params.value.pageBean.total = total
        tableData.value = rows
    } finally {
        tableLoading.value = false
    }
}

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 handleDelete = async (row?: { id: string }): Promise<void> => {
    let ids: string = row ? row.id : currentDataDel.value.join()
    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) {
                ElMessage.success(`删除成功`)
                const { page, pageSize, total } = params.value.pageBean
                const totalPages = Math.ceil(total / pageSize) // 计算总页数
                if (totalPages > 1 && page === totalPages) {
                    if (tableData.value.length === 1) {
                        // 当前页只有一条数据
                        params.value.pageBean.page -= 1 // 返回前一页
                    }
                }
                await loadData()
            }
        } catch (error) {
            ElMessage.error(error || '删除失败')
        }
    })
}

const handleDownload = (): void => {
    console.log('handleDownload')
}

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

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

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

<style lang="scss" scoped>
.left-btn-group {
    flex: 1;
}
.grid-list {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 5px 10px;
    border-radius: 3px;
    margin-left: 20px;
    line-height: 20px;
    width: 50px;

    border: 1px solid rgba(67, 161, 255, 0.3);
    .cqlt-icon {
        font-size: 18px;
    }
    .activeGrid {
        color: #409eff;
    }
}
.table-list {
    width: 100%;
    height: 100%;
    display: flex;
    flex-wrap: wrap;
    align-content: flex-start;
    gap: 10px;
    overflow-y: auto;
    overflow-x: auto;
    padding: 5px;
    .table-item {
        width: calc(33.33% - 15px);
        background-color: #ffffff;
        box-shadow: -1px 2px 10px 0 rgba(0, 0, 0, 0.1);
        border-radius: 10px;
        padding: 15px;
        box-sizing: border-box;
        .table-item-title {
            display: flex;
            font-size: 16px;
            background-color: #f7f8fa;
            align-items: center;
            padding: 5px 10px;
            div {
                margin-left: 6px;
            }
        }
        .table-item-content {
            display: flex;
            margin-top: 10px;
            .table-item-content-left {
                width: 140px;
                height: 140px;
                border: 1px solid #f2f2f2;
                padding: 10px;
                box-sizing: border-box;
                margin-right: 20px;
                img {
                    width: 100%;
                    height: 100%;
                }
            }
            .table-item-content-right {
                display: flex;
                flex-direction: column;
                justify-content: space-between;
                .table-item-content-right-title {
                    font-size: 20px;
                    font-weight: bold;
                }
                .table-item-content-right-info {
                    div {
                        font-size: 14px;
                        line-height: 1.7;
                    }
                }
            }
        }
        .table-item-footer {
            border-top: 1px solid #e6e6e6;
            margin-top: 10px;
            padding-top: 10px;
            box-sizing: border-box;
            .table-item-footer-text {
                display: inline-block;
                font-size: 14px;
                color: #1a8cff;
                background: rgba(26, 140, 255, 0.1);
                padding: 4px 16px;
                cursor: pointer;
            }
            .table-item-footer-delete{
                display: inline-block;
                font-size: 14px;
                color: #ff1a1a;
                background: rgba(26, 140, 255, 0.1);
                padding: 4px 16px;
                cursor: pointer;
            }
        }
    }
}
</style>
