<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)"
        >
            <el-table
                :data="tableData"
                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 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

        // 数据加载完成后，自动选中currentIsBind为1的行
        nextTick(() => {
            if (tableRef.value && tableData.value && tableData.value.length > 0) {
                tableData.value.forEach((row) => {
                    if (row.currentIsBind === 1) {
                        tableRef.value.toggleRowSelection(row, true)
                    }
                })
            }
        })
    } finally {
        tableLoading.value = false
    }
}
const tableData = ref<TableRow[]>([])
const selectedSuppliers = ref<TableRow[]>([])
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 = []
    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;
}
</style>
