<template>
    <super-dialog
        v-model="dialogVisible"
        :title="title"
        custom-class="notification-dialog"
        top="5%"
        width="60%"
        :close-on-click-modal="false"
        @closed="closePage"
    >
        <div
            v-loading="detailLoading"
            class="table-container"
            element-loading-background="rgba(10 ,38 ,61, 0.9)"
        >
            <div class="search-container">
                <el-input
                    v-model="searchText"
                    placeholder="搜索供应商名称"
                    clearable
                    style="width: 300px;"
                    @input="handleSearch"
                >
                    <template #prefix>
                        <el-icon><Search /></el-icon>
                    </template>
                </el-input>
            </div>
            <el-table
                :data="filteredTableData"
                ref="tableRef"
                height="400px"
                v-loading="tableLoading"
                border
                fit
                stripe
                row-key="supplierId"
                style="width: 100%"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="50px" align="center"> </el-table-column>
                <el-table-column type="index" label="序号" width="80px" align="center">
                </el-table-column>
                <el-table-column
                    prop="supplierCode"
                    label="供应商编码"
                    min-width="120px"
                    align="center"
                ></el-table-column>
                <el-table-column
                    prop="supplierName"
                    label="供应商名称"
                    min-width="180px"
                    align="center"
                >
                </el-table-column>
                <el-table-column prop="selectionDate" label="准入时间" align="center">
                </el-table-column>
                <el-table-column prop="currentIsBind" label="是否绑定" align="center">
                    <template v-slot="{ row }">
                        <div v-if="row.currentIsBind == 0">未绑定</div>
                        <div v-if="row.currentIsBind == 1">已绑定</div>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div
            slot="footer"
            style="display: flex; justify-content: center; width: 100%; margin-top: 5px"
        >
            <el-button type="primary" @click="submitObject" :loading="btnLoading">确定</el-button>
            <el-button @click="closePage">取消</el-button>
        </div>
    </super-dialog>
</template>

<script lang="ts" setup>
import {
    dataUnBindSupplier,
    dataDistribution
} from '@/api/supplierMonitor/PerformanceManagement/PerformanceConfig'
import SuperDialog from '@/components/Dialog/index.vue'
import { onMounted, reactive, ref, computed, watch, nextTick } from 'vue'
import { Search } from '@element-plus/icons-vue'
import Pagination from '@/components/Pagination/index.vue'
import { refineRequestBody } from '@/utils/requestWrappers'
/**
 * 分页相关
 */
import { usePagination } from '@/hooks/usePagination'
// 1. 定义 props
const props = defineProps({
    isShowAdd: {
        type: Boolean,
        default: false
    },
    title: {
        type: String,
        default: ''
    },
    info: {
        type: Array,
        default: () => []
    }
})

const params = ref<Params>({
    pageBean: { pageSize: 20, page: 1, total: 0 },
    querys: [],
    sorter: []
})

// 监听弹窗打开状态
watch(
    () => props.isShowAdd,
    (newVal) => {
        console.log(newVal, 'newVal')
        if (newVal) {
            getTableData()
        }
    }
)

const getTableData = async () => {
    try {
        tableLoading.value = true
        const res = await dataUnBindSupplier(props.info.id, props.info.supplierCategoryId)
        tableData.value = res.value
        
        // 重置选中状态
        selectedSuppliers.value = []
        
        // 数据加载完成后，自动选中currentIsBind为1的行
        nextTick(() => {
            if (tableRef.value && tableData.value && tableData.value.length > 0) {
                const autoSelectedRows = []
                tableData.value.forEach((row) => {
                    if (row.currentIsBind === 1) {
                        tableRef.value.toggleRowSelection(row, true)
                        autoSelectedRows.push(row)
                    }
                })
                selectedSuppliers.value = autoSelectedRows
            }
        })
    } finally {
        tableLoading.value = false
    }
}
const tableData = ref<TableRow[]>([])
const selectedSuppliers = ref<TableRow[]>([])
const searchText = ref('')

// 过滤后的表格数据
const filteredTableData = computed(() => {
    if (!searchText.value) {
        return tableData.value
    }
    return tableData.value.filter(item => 
        item.supplierName && item.supplierName.toLowerCase().includes(searchText.value.toLowerCase())
    )
})

// 监听过滤数据变化，管理选中状态
watch(
    () => filteredTableData.value,
    () => {
        nextTick(() => {
            if (tableRef.value) {
                tableRef.value.clearSelection()
                // 如果有搜索条件，只恢复当前过滤结果中的选中项
                if (searchText.value) {
                    filteredTableData.value.forEach((row) => {
                        if (selectedSuppliers.value.some(selected => selected.supplierId === row.supplierId)) {
                            tableRef.value.toggleRowSelection(row, true)
                        }
                    })
                } else {
                    // 没有搜索条件时，恢复初始选中状态（currentIsBind === 1）
                    const initialSelectedRows = []
                    tableData.value.forEach((row) => {
                        if (row.currentIsBind === 1) {
                            tableRef.value.toggleRowSelection(row, true)
                            initialSelectedRows.push(row)
                        }
                    })
                    selectedSuppliers.value = initialSelectedRows
                }
            }
        })
    },
    { deep: true }
)

// 处理搜索
const handleSearch = () => {
    // 搜索逻辑已通过computed属性实现
}
const tableRef = ref()
const btnLoading = ref(false)
const detailLoading = ref<Boolean>(false)
const tableLoading = ref<Boolean>(false)

// 处理选择变化
const handleSelectionChange = (selection: TableRow[]) => {
    selectedSuppliers.value = selection
}

// 2. 定义 emit
const emit = defineEmits(['update:isShowAdd', 'refresh', 'cancel'])

const openPage = () => {}

const closePage = () => {
    emit('cancel')
    emit('update:isShowAdd', false)
    selectedSuppliers.value = []
    searchText.value = ''
    if (tableRef.value) {
        tableRef.value.clearSelection()
    }
}

defineExpose({
    openPage
})
// 保存绑定
const submitObject = async () => {
    if (selectedSuppliers.value.length === 0) {
        ElMessage.warning('请选择供应商')
        return
    }

    try {
        btnLoading.value = true
        // 处理选中的供应商数据
        let dto = {
            id: props.info.id,
            configurationUsers: selectedSuppliers.value
        }
        const { state, message } = await dataDistribution(dto)
        if (state) {
            ElMessage.success(message)
            emit('refresh')
            emit('update:isShowAdd', false)
            selectedSuppliers.value = []
        } else {
            ElMessage.error(message)
        }
    } finally {
        btnLoading.value = false
    }
}
// 3. 使用 computed 定义双向绑定
const dialogVisible = computed({
    get() {
        return props.isShowAdd
    },
    set(val) {
        emit('update:isShowAdd', false)
    }
})
</script>

<style lang="scss" scoped>
.move-type-list {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: flex-start;
    margin: 0 0 20px 10px;
}

.search-container {
    margin-bottom: 16px;
    display: flex;
    align-items: center;
}
</style>
