<template>
    <div class="table-page">
        <div class="table-page-content">
            <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="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
                                    class="table-list"
                                    element-loading-background="rgba(10 ,38 ,61, 0.9)"
                                    height="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 === 'reviewRequirements'">
                                                    <div class="review-requirements-content">
                                                        
                                                    </div>
                                                </template>
                                                <template v-else-if="col.prop === 'status'">
                                                    <el-switch
                                                        v-model="row.status"
                                                        active-value="1"
                                                        active-text="启用"
                                                        inline-prompt
                                                        inactive-text="禁用"
                                                        inactive-value="0"
                                                        style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                                                        @change="switchBeforeChange(row)"
                                                    />
                                                </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 { refineRequestBody } from '@/utils/requestWrappers'
import { createAddHandler, createEditHandler } from '@/utils/routeNavigation'
import {
    dataTable,
    dataStatus,
    dataDelete
} from '@/api/supplierMonitor/PerformanceManagement/PerformanceConfig'
/**
 * table查询参数，列头设置相关配置
 */
import { useTableOptionConfig } from './hooks/useTableOptionConfig'
import { useSearch } from '@/hooks/useSearch'
/**
 * 分页相关
 */
import { usePagination } from '@/hooks/usePagination'

onMounted(() => {
    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[]
}

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: 'name' },
        { operation: 'LIKE', property: 'desc' },
        { operation: 'BETWEEN', property: 'createTime' },
        { operation: 'EQUAL', property: 'status' }
    ],
    sorter: [
        {
            direction: 'DESC',
            property: 'createTime'
        }
    ]
})

const currentColumnsKeys = ref<string[]>([
    'name',
    'code',
    'totalScore',
    'desc',
    'remarks',
    'status',
    'createTime',
    'enterpriseName'
])

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 switchBeforeChange = async (row: { id: string; status: number }): Promise<void> => {
  try {
    const response = await dataStatus(row.id, row.status)
    console.log(response,'response');
    if(response.state){
        ElMessage.success(response.message)
        loadData()
    }
  } catch (error) {
    console.error('数据加载失败:', error);
  }
}
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 basePath: string = 'SupplierMonitor/PerformanceManagement/PerformanceConfig' // 基础路径 （当前页面路径）

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

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

<style lang="scss" scoped>
.review-requirements-content {
    white-space: pre-wrap;
    text-align: left;
}
</style>
