<template>
    <div class="user-select-component">
        <el-input
            v-model:value="displayValue"
            placeholder="请选择审批单"
            :disabled="componentSchema?.disabled"
            readonly
            :class="{ selected: isSelected }"
        />

        <!-- 用户选择弹窗 -->
        <el-dialog v-model="isModalVisible" title="关联审批单" width="70%" @close="handleModalClose">
            <div style="width: 400px; margin-top: 20px">
                <el-input
                    v-model="searchQuery"
                    placeholder="输入关键字按enter键查询"
                    class="search-input"
                    @keyup.enter="handleSearch"
                >
                    <template #append>
                        <el-button @click="handleSearch">
                            <el-icon><Search /></el-icon>
                        </el-button>
                    </template>
                </el-input>
            </div>

            <div>
                <!-- 审批单(用于做关联) -->
                <div class="table-container">
                    <el-table
                        :data="currentPageData"
                        style="width: 100%"
                        @row-click="handleRowClick"
                        :row-class-name="tableRowClassName"
                        v-loading="loading"
                        height="300"
                        border
                    >
                        <el-table-column prop="date" label="Date" width="180" />
                        <el-table-column prop="name" label="Name" width="180" />
                        <el-table-column prop="address" label="Address" />
                    </el-table>

                    <!-- 分页组件 -->
                    <div class="pagination-container">
                        <el-pagination
                            :background="true"
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="currentPage"
                            :page-sizes="[5, 10, 20, 50]"
                            :page-size="pageSize"
                            layout="total, sizes, prev, pager, next, jumper"
                            :total="total"
                        />
                    </div>
                </div>
            </div>

            <template #footer>
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" @click="handleConfirm">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, watch } from "vue";
import { inject } from "vue";
import { Designer } from "epic-designer";
import $Bus from "@/utils/mittBus";
import { ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";

// 定义User接口
interface User {
    date: string;
    name: string;
    address: string;
    id: number;
}

// 接收props
const props = defineProps({
    componentSchema: {
        type: Object,
        default: () => ({
            placeholder: "请选择组织",
            value: null,
            disabled: false,
            componentProps: {},
            field: ""
        })
    },
    modelValue: {
        type: String,
        default: null
    }
});

// 状态管理
const isModalVisible = ref(false);
const selectedApprove = ref<string | null>(null);
const isSelected = ref(false);
const loading = ref(false);

// 分页相关状态
const currentPage = ref(1);
const pageSize = ref(5);
const total = ref(0);
const allTableData = ref<User[]>([]);
const filteredData = ref<User[]>([]);

// 设计器实例
const designer = inject("designer") as Designer;

// 选择的审批单（单选）
const selectedRow = ref<User | null>(null);

// 搜索查询
const searchQuery = ref("");

// 初始化表格数据
const initTableData = () => {
    loading.value = true;
    // 模拟API请求延迟
    setTimeout(() => {
        const mockData: User[] = [];
        for (let i = 1; i <= 30; i++) {
            mockData.push({
                date: `2016-05-${i < 10 ? "0" + i : i}`,
                name: `User ${i}`,
                address: `No. ${i}, Grove St, Los Angeles`,
                id: i
            });
        }
        allTableData.value = mockData;
        filteredData.value = [...allTableData.value];
        total.value = filteredData.value.length;
        loading.value = false;
    }, 500);
};

// 当前页数据
const currentPageData = computed(() => {
    const startIndex = (currentPage.value - 1) * pageSize.value;
    return filteredData.value.slice(startIndex, startIndex + pageSize.value);
});

// 搜索事件
const handleSearch = () => {
    if (!searchQuery.value.trim()) {
        filteredData.value = [...allTableData.value];
    } else {
        const query = searchQuery.value.toLowerCase().trim();
        filteredData.value = allTableData.value.filter(
            item =>
                item.name.toLowerCase().includes(query) || item.address.toLowerCase().includes(query) || item.date.includes(query)
        );
    }
    total.value = filteredData.value.length;
    currentPage.value = 1;
};

// 表格row点击事件 - 单选逻辑
const handleRowClick = (row: User) => {
    if (selectedRow.value && selectedRow.value.id === row.id) {
        selectedRow.value = null;
    } else {
        selectedRow.value = row;
    }
};

// 为选中的行添加样式类
const tableRowClassName = ({ row }: { row: User }) => {
    return selectedRow.value && selectedRow.value.id === row.id ? "selected-row" : "";
};

// 分页事件处理
const handleSizeChange = (val: number) => {
    pageSize.value = val;
    currentPage.value = 1;
};

const handleCurrentChange = (val: number) => {
    currentPage.value = val;
};

// 确认选择
const handleConfirm = () => {
    if (!selectedRow.value) {
        ElMessage.warning("请选择一个审批单");
        return;
    }

    selectedApprove.value = selectedRow.value.name;

    if (designer?.state?.selectedNode) {
        designer.state.selectedNode.componentProps.defaultValue = selectedApprove.value;
        designer.state.selectedNode.componentProps.defaultValueIds = [selectedRow.value.id];
        designer.state.selectedNode.componentProps.selectedRowData = selectedRow.value;
    }

    isModalVisible.value = false;
    selectedRow.value = null;
};

// 关闭弹窗回调
const handleModalClose = () => {
    selectedRow.value = null;
};

// 关闭弹窗
const handleClose = () => {
    isModalVisible.value = false;
    selectedRow.value = null;
};

// 显示在输入框的文本
const displayValue = computed(() => {
    return selectedApprove.value || "";
});

// 监听设计器选中状态变化
watch(
    () => designer?.state.selectedNode?.field,
    newField => {
        isSelected.value = newField === props.componentSchema.field;
    },
    { immediate: true }
);

// 监听modelValue变化
watch(
    () => props.modelValue,
    newValue => {
        selectedApprove.value = newValue;
    },
    { immediate: true }
);

// 监听弹窗显示状态
watch(
    () => isModalVisible.value,
    isVisible => {
        if (isVisible) {
            initTableData();

            if (designer?.state?.selectedNode) {
                const savedRow = designer.state.selectedNode.componentProps.selectedRowData;
                if (savedRow) {
                    setTimeout(() => {
                        selectedRow.value = allTableData.value.find(row => row.id === savedRow.id) || null;
                    }, 600);
                } else if (designer.state.selectedNode.componentProps.defaultValueIds?.length) {
                    const savedId = designer.state.selectedNode.componentProps.defaultValueIds[0];
                    setTimeout(() => {
                        selectedRow.value = allTableData.value.find(row => row.id === savedId) || null;
                    }, 600);
                }
            }
        }
    }
);

// 监听按钮触发的全局事件
const handleGlobalTrigger = () => {
    if (isSelected.value && !props.componentSchema.disabled) {
        isModalVisible.value = true;
    }
};

// 事件监听
onMounted(() => {
    $Bus.on("trigger-approve-select-modal", handleGlobalTrigger);
});

// 清理事件监听
onUnmounted(() => {
    $Bus.off("trigger-approve-select-modal", handleGlobalTrigger);
});
</script>

<style scoped lang="scss">
.user-select-component {
    width: 100%;
}
:deep(.el-input__inner) {
    cursor: pointer;
}
.table-container {
    margin-top: 10px;
}
.search-input {
    margin-bottom: 10px;
}

/* 表格选中行样式 */
::v-deep .selected-row {
    background-color: #e6f7ff !important;

    // &:hover {
    //     background-color: #f5f7fa;
    // }
}
.selected-row:hover {
    background-color: #f5f7fa;
}

/* 表格行 hover 样式增强 */

/* :deep (.el-table__row:hover) {
    background-color: #f5f7fa;
} */

/* 分页容器样式 */
.pagination-container {
    /* padding: 10px 0;
    margin-top: 15px; */
    text-align: right;
}

/* 优化表格滚动条样式 */
.el-table__body-wrapper {
    scrollbar-width: thin;

    // &::-webkit-scrollbar {
    //     width: 6px;
    //     height: 6px;
    // }
    // &::-webkit-scrollbar-thumb {
    //     background-color: #dddddd;
    //     border-radius: 3px;
    // }
    // &::-webkit-scrollbar-track {
    //     background-color: #f5f5f5;
    // }
}
.el-table__body-wrapper::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}
.el-table__body-wrapper::-webkit-scrollbar-thumb {
    background-color: #dddddd;
    border-radius: 3px;
}
.el-table__body-wrapper::-webkit-scrollbar-track {
    background-color: #f5f5f5;
}
</style>
