<template>
    <div class="djxx-container">
        <!-- 搜索条件 -->
        <div class="search-form">
            <el-form :model="searchForm" ref="searchFormRef" :rules="searchRules" inline>
                <el-form-item label="区块名称" prop="qk">
                    <el-select v-model="searchForm.qk" placeholder="请选择区块名称" clearable filterable style="width: 150px;">
                        <el-option v-for="item in blockOptions" :key="item.qk" :label="item.qk" :value="item.qk" />
                    </el-select>
                </el-form-item>
                <el-form-item label="井号" prop="jh">
                    <el-input v-model="searchForm.jh" placeholder="请输入" style="width: 150px;" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getList">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                    <el-button type="success" @click="handleAdd">新增</el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 数据表格 -->
        <el-table :data="tableData" border style="width: 100%; height: calc(100vh - 230px)">
            <el-table-column prop="famc" label="方案名称" min-width="180" align="center" show-overflow-tooltip sortable />
            <el-table-column prop="qk" label="区块" min-width="110" align="center" show-overflow-tooltip sortable />
            <el-table-column prop="jh" label="井号" min-width="110" align="center" show-overflow-tooltip sortable />
            <el-table-column prop="jhs" label="邻井井号" min-width="160" align="center" show-overflow-tooltip sortable />
            <el-table-column prop="yxzt" label="综合最优" align="center" min-width="160" show-overflow-tooltip sortable />
            <el-table-column prop="jczt" label="进尺最优" align="center" min-width="160" show-overflow-tooltip sortable />
            <el-table-column prop="jxzszt" label="转速最优" align="center" min-width="160" show-overflow-tooltip sortable />
            <el-table-column label="操作" width="200" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-view" @click="handleView(scope.row)">查看</el-button>
                    <el-button size="mini" type="text" icon="el-icon-edit"
                        @click="handleUpdate(scope.row)">编辑</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete"
                        @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 主表格分页组件 -->
        <el-pagination style="margin-top: 10px; text-align: right;" background
            layout="total, sizes, prev, pager, next, jumper" :total="mainPagination.total"
            :page-sizes="[10, 20, 50, 100]" :page-size="mainPagination.pageSize" :current-page="mainPagination.pageNum"
            @size-change="handleMainSizeChange" @current-change="handleMainCurrentChange" />

        <!-- 新增/编辑弹窗 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%" :close-on-click-modal="false"
            @close="handleDialogClose" label-width="100px">
            <el-form :model="formData" ref="formRef" :rules="formRules" label-width="140px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="方案名称" prop="famc">
                            <el-input v-model="formData.famc" placeholder="请输入方案名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="区块" prop="qk">
                            <el-select v-model="formData.qk" placeholder="请选择区块名称" clearable filterable
                                style="width: 100%;">
                                <el-option v-for="item in blockOptions" :key="item.qk" :label="item.qk" :value="item.qk"
                                    style="width: 100%;" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="井号" prop="jh">
                            <div style="cursor: pointer;">
                                <el-input v-model="formData.jh" placeholder="请输入井号" />
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="井口距离" prop="jl">
                            <el-input v-model="formData.jl" placeholder="请输入" style="width: 100%;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="完井时间" prop="wjsjks" required>
                            <el-date-picker v-model="formData.wjsjks" type="date" placeholder="选择开始日期"
                                style="width: 50%;" />
                            <el-date-picker v-model="formData.wjsjjs" type="date" placeholder="选择结束日期"
                                style="width: 50%;" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="开次" prop="kc">
                            <el-input v-model="formData.kc" placeholder="请输入开次" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="井眼尺寸" prop="jycc">
                            <el-input v-model="formData.jycc" placeholder="请输入井眼尺寸" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="选择邻井" prop="jhs">
                            <div style="cursor: pointer;" @click="handleSelectAdjacentWell">
                                <el-input v-model="formData.jhs" placeholder="请点击选择邻井" readonly
                                    style="cursor: pointer;" />
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="进尺最优比例" prop="jcbl" required>
                            <el-select v-model="formData.jcbl" placeholder="请选择进尺最优比例" clearable style="width: 100%;">
                                <el-option label="0.2" value="0.2" />
                                <el-option label="0.3" value="0.3" />
                                <el-option label="0.4" value="0.4" />
                                <el-option label="0.5" value="0.5" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="机械钻速最优比例" prop="jxzsbl" required>
                            <el-select v-model="formData.jxzsbl" placeholder="请选择机械钻速最优比例" clearable
                                style="width: 100%;">
                                <el-option label="0.2" value="0.2" />
                                <el-option label="0.3" value="0.3" />
                                <el-option label="0.4" value="0.4" />
                                <el-option label="0.5" value="0.5" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template slot="footer">
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取 消</el-button>
                    <el-button type="primary" @click="submitForm">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 井号选择弹窗 -->
        <el-dialog title="选择邻井" :visible.sync="wellDialogVisible" width="80%" :close-on-click-modal="false"
            class="well-dialog" :z-index="2000">
            <!-- 选择提示信息 -->
            <!-- <div
                style="margin-bottom: 15px; padding: 10px; background-color: #f0f9ff; border: 1px solid #b3d8ff; border-radius: 4px; color: #1890ff;">
                <i class="el-icon-info"></i>
                <span>提示：您最多可以选择2个邻井，当前已选择 {{ wellSelection.length }} 个</span>
            </div> -->
            <el-table :data="wellTableData" border style="width: 100%;height: 400px" max-height="400px"
                v-loading="wellLoading" @selection-change="handleWellSelectionChange" ref="wellTable"
                :row-key="row => row.jh">
                <el-table-column type="selection" width="55" :selectable="checkSelectable" />
                <el-table-column prop="jh" label="井号" align="center" show-overflow-tooltip />
                <el-table-column prop="jx" label="井型" align="center" show-overflow-tooltip />
                <el-table-column prop="wjjs" label="斜深" align="center" show-overflow-tooltip />
                <el-table-column prop="wjczjs" label="垂深" align="center" show-overflow-tooltip />
                <el-table-column prop="wzcw" label="完钻层位" align="center" show-overflow-tooltip />
                <el-table-column prop="kc" label="总开次" align="center" show-overflow-tooltip />
                <el-table-column prop="zjzq" label="钻井周期(天)" align="center" show-overflow-tooltip />
                <el-table-column prop="wjzq" label="钻完周期(天)" align="center" show-overflow-tooltip />
                <el-table-column prop="jkjl" label="井口距离" align="center" show-overflow-tooltip />
                <!-- <el-table-column prop="jdjl" label="井底距离" align="center" show-overflow-tooltip /> -->
            </el-table>

            <!-- 分页组件 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                :current-page="wellPagination.pageNum" :page-sizes="[10, 20, 50, 100]"
                :page-size="wellPagination.pageSize" layout="total, sizes, prev, pager, next, jumper"
                :total="wellPagination.total" style="margin-top: 10px; text-align: right;" />
            <template slot="footer">
                <span class="dialog-footer">
                    <el-button @click="handleWellCancel">取 消</el-button>
                    <el-button type="primary" @click="handleWellSubmit">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { listSj } from '@/api/adjacentWell'
import { getQkxl } from "@/api/system/jsaa";
import { listDjnxfxfa, getDjnxfxfa, delDjnxfxfa, addDjnxfxfa, updateDjnxfxfa } from "@/api/system/djnxfxfa";

export default {
    name: 'DjxxIndex',
    dicts: ['qkinfo', 'js_jx', 'js_jb'],
    data() {
        return {
            blockOptions: [],
            // 搜索表单
            searchForm: {
                qk: ''
            },
            searchRules: {

            },

            // 表格数据
            tableData: [],

            // 弹窗相关
            dialogVisible: false,
            dialogTitle: '',
            formData: {
                famc: '',
                qk: '',
                jhs: '',
                kc: '',
                jycc: '',
                jl: '10000', // 距离默认值10000
                wjsjks: null, // 完井时间开始默认五年前的今天
                wjsjjs: null, // 完井时间结束默认今天
                jcbl: '', // 进尺最优比例
                jxzsbl: '' // 机械钻速最优比例
            },
            formRules: {
                famc: [{ required: true, message: '请输入方案名称', trigger: 'blur' }],
                qk: [{ required: true, message: '请选择区块', trigger: 'change' }],
                jhs: [{ required: true, message: '请选择井号', trigger: 'change' }],
                jcbl: [{ required: true, message: '请选择进尺最优比例', trigger: 'change' }],
                jxzsbl: [{ required: true, message: '请选择机械钻速最优比例', trigger: 'change' }]
            },

            // 井号选择弹窗
            wellDialogVisible: false,
            wellTableData: [],
            wellLoading: false,
            wellSelection: [],
            wellPagination: {
                pageNum: 1,
                pageSize: 10,
                total: 0
            },
            isUserSelecting: false,
            isSettingSelection: false,
            // 添加页面选择状态缓存
            pageSelectionCache: new Map(),
            // 添加初始化标志
            isInitializing: false,
            // 主表格分页
            mainPagination: {
                pageNum: 1,
                pageSize: 10,
                total: 0
            },
        }
    },
    created() {
        this.getBlockOptions();
        this.getList();
        // 设置默认日期值
        this.formData.wjsjks = this.getFiveYearsAgoDate();
        this.formData.wjsjjs = this.getCurrentDate();
    },
    methods: {
        /** 获取五年前的今天 */
        getFiveYearsAgoDate() {
            const date = new Date();
            date.setFullYear(date.getFullYear() - 5);
            return date;
        },
        /** 获取今天的日期 */
        getCurrentDate() {
            return new Date();
        },
        /** 格式化日期为 yyyy-MM-dd 格式 */
        formatDate(date) {
            // 如果date不是Date对象，尝试转换
            if (!(date instanceof Date)) {
                if (typeof date === 'string') {
                    date = new Date(date);
                } else if (date === null || date === undefined) {
                    return '';
                } else {
                    console.warn('formatDate received invalid date:', date);
                    return '';
                }
            }

            // 检查转换后的日期是否有效
            if (isNaN(date.getTime())) {
                console.warn('formatDate received invalid date:', date);
                return '';
            }

            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },
        /** 查询多井能效分析方案信息列表 */
        getList() {
            this.loading = true;
            // 合并分页参数
            const params = {
                ...this.searchForm,
                pageNum: this.mainPagination.pageNum,
                pageSize: this.mainPagination.pageSize
            };
            listDjnxfxfa(params).then(response => {
                this.tableData = response.rows;
                this.mainPagination.total = response.total;
                console.log('获取到的表格数据:', this.tableData);
                // 检查每条数据的jhs字段
                this.tableData.forEach((row, index) => {
                    console.log(`第${index + 1}行数据:`, row);
                    console.log(`第${index + 1}行jhs字段:`, row.jhs);
                });
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.formData = {
                famc: '',
                qk: '',
                jhs: '',
                kc: '',
                jycc: '',
                jl: '10000', // 距离默认值10000
                wjsjks: this.getFiveYearsAgoDate(), // 完井时间开始默认五年前的今天
                wjsjjs: this.getCurrentDate(), // 完井时间结束默认今天
                jcbl: '', // 进尺最优比例
                jxzsbl: '' // 机械钻速最优比例
            };
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加多井能效分析方案信息";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const id = row.id || this.ids
            getDjnxfxfa(id).then(response => {
                this.formData = response.data;
                // 确保日期字段是Date对象
                if (this.formData.wjsjks && typeof this.formData.wjsjks === 'string') {
                    this.formData.wjsjks = new Date(this.formData.wjsjks);
                }
                if (this.formData.wjsjjs && typeof this.formData.wjsjjs === 'string') {
                    this.formData.wjsjjs = new Date(this.formData.wjsjjs);
                }
                this.dialogVisible = true;
                this.dialogTitle = "修改多井能效分析方案信息";
                // 编辑时不清空选择状态，保留之前的选择
                // this.wellSelection = []
                // this.pageSelectionCache.clear()
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["formRef"].validate(valid => {
                if (valid) {
                    // 格式化日期为字符串格式传给后台
                    const submitData = {
                        ...this.formData,
                        wjsjks: this.formData.wjsjks ? this.formatDate(this.formData.wjsjks) : '',
                        wjsjjs: this.formData.wjsjjs ? this.formatDate(this.formData.wjsjjs) : ''
                    };

                    if (this.formData.id != null) {
                        updateDjnxfxfa(submitData).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.dialogVisible = false;
                            this.getList();
                            // 保存成功后，重置井号选择状态
                            this.wellSelection = []
                            this.pageSelectionCache.clear()
                        });
                    } else {
                        addDjnxfxfa(submitData).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.dialogVisible = false;
                            this.getList();
                            // 保存成功后，重置井号选择状态
                            this.wellSelection = []
                            this.pageSelectionCache.clear()
                        });
                    }
                }
            });
        },
        /** 查看按钮操作 */
        handleView(row) {
            console.log('查看按钮点击，行数据:', row);
            const params = {
                id: row.id || '',
                jh: row.jh || '',
                famc: row.famc || '',
                qk: row.qk || '',
                jhs: row.jhs || ''
            };
            console.log('准备传递的参数:', params);

            this.$router.push({
                name: 'DjxxDetail',
                query: params
            }).then(() => {
                console.log('路由跳转成功');
            }).catch(err => {
                console.error('路由跳转失败:', err);
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.id || this.ids;
            this.$modal.confirm('是否确认删除多井能效分析方案信息编号为"' + ids + '"的数据项？').then(function () {
                return delDjnxfxfa(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => { });
        },
        /** 获取区块下拉选项 */
        getBlockOptions() {
            getQkxl().then(response => {
                // 过滤掉无效的选项
                this.blockOptions = response.data.filter(item => item && item.qk);
            });
        },


        // 重置搜索
        resetSearch() {
            this.$refs.searchFormRef.resetFields()
            this.searchForm = {
                qk: ''
            }
            this.tableData = []
            // 重置后重新获取数据
            this.getList()
        },

        // 新增
        handleAdd() {
            this.dialogTitle = '新增'
            this.dialogVisible = true
            this.formData = {
                famc: '',
                qk: '',
                jhs: '',
                kc: '',
                jycc: '',
                jl: '10000', // 距离默认值10000
                wjsjks: this.getFiveYearsAgoDate(), // 完井时间开始默认五年前的今天
                wjsjjs: this.getCurrentDate(), // 完井时间结束默认今天
                jcbl: '', // 进尺最优比例
                jxzsbl: '' // 机械钻速最优比例
            }
            // 新增时重置井号选择状态
            this.wellSelection = []
            this.pageSelectionCache.clear()
        },


        // 选择邻井
        handleSelectAdjacentWell() {
            console.log('点击选择邻井输入框')

            // 验证必要参数是否已填写
            if (!this.formData.qk) {
                this.$message.warning('请先选择区块')
                return
            }
            if (!this.formData.jh) {
                this.$message.warning('请先输入井号')
                return
            }
            if (!this.formData.jl) {
                this.$message.warning('请先输入距离')
                return
            }
            if (!this.formData.wjsjks || !this.formData.wjsjjs) {
                this.$message.warning('请先选择完井时间')
                return
            }

            this.dialogVisible = false
            this.wellDialogVisible = true

            console.log('弹窗状态:', this.wellDialogVisible)
            // 重置分页
            this.wellPagination.pageNum = 1
            this.wellPagination.pageSize = 10
            this.wellPagination.total = 0

            // 保留上次的选择状态，不清空
            // this.pageSelectionCache.clear()
            // this.isInitializing = false

            // 不清空井号选择状态，保留上次选择
            // this.wellSelection = []
            // this.formData.jhs = ''

            // 设置用户选择标志
            this.isUserSelecting = true

            // 自动获取邻井数据
            this.$nextTick(() => {
                this.fetchWellData()
            })
        },

        // 选择井号
        handleSelectWell() {
            console.log('点击井号输入框')
            this.dialogVisible = false
            this.wellDialogVisible = true

            console.log('弹窗状态:', this.wellDialogVisible)
            // 重置分页
            this.wellPagination.pageNum = 1
            this.wellPagination.pageSize = 10
            this.wellPagination.total = 0

            // 重置页面选择缓存和初始化标志
            this.pageSelectionCache.clear()
            this.isInitializing = false

            // 清空井号选择状态，每次点击都重新开始选择
            this.wellSelection = []
            this.formData.jh = ''

            // 设置用户选择标志
            this.isUserSelecting = true

            // 自动获取井号数据
            this.$nextTick(() => {
                this.fetchWellData()
            })
        },

        // 井号搜索（简化版，直接获取数据）
        handleWellSearch() {
            // 保存当前页面的选择状态（如果有的话）
            if (this.$refs.wellTable) {
                const currentSelection = this.$refs.wellTable.selection || []
                const currentPageSelection = currentSelection.map(item => item.jh)
                if (currentPageSelection.length > 0) {
                    this.pageSelectionCache.set(this.wellPagination.pageNum, currentPageSelection)
                    console.log('搜索前保存当前页面选择:', currentPageSelection)
                }
            }

            this.fetchWellData()
        },

        // 获取井号数据
        fetchWellData() {
            this.wellLoading = true
            this.isInitializing = true

            const params = {
                pageNum: this.wellPagination.pageNum,
                pageSize: this.wellPagination.pageSize,
                // 传递表单参数
                qk: this.formData.qk || '', // 区块
                jh: this.formData.jh || '', // 井号
                jl: this.formData.jl || '', // 距离
                wjsjks: this.formData.wjsjks ? this.formatDate(this.formData.wjsjks) : '', // 完井时间开始
                wjsjjs: this.formData.wjsjjs ? this.formatDate(this.formData.wjsjjs) : '' // 完井时间结束
            }
            listSj(params).then(res => {
                this.wellTableData = res.rows || []
                this.wellPagination.total = res.total || 0
                console.log('数据加载完成，准备设置选择状态')

                // 如果是第一次打开弹窗，需要从formData.jhs中恢复选择状态
                if (this.wellSelection.length === 0 && this.formData.jhs) {
                    const selectedWells = this.formData.jhs.split(',').filter(well => well.trim())
                    this.wellSelection = selectedWells
                    console.log('从formData.jhs恢复选择状态:', selectedWells)
                }

                // 完全禁用选择变化事件处理
                this.isUserSelecting = false
                this.isSettingSelection = true

                // 延迟设置选择状态，确保DOM更新完成且不会触发选择变化事件
                setTimeout(() => {
                    this.setCurrentPageSelection()
                }, 200)
            }).catch(error => {
                this.$message.error('获取井号数据失败')
            }).finally(() => {
                this.wellLoading = false
            })
        },

        // 重置井号搜索（简化版）
        resetWellSearch() {
            this.wellTableData = []
            this.wellSelection = []
            this.wellPagination.pageNum = 1

            // 重置页面选择缓存
            this.pageSelectionCache.clear()

            // 重置后自动获取数据
            this.$nextTick(() => {
                this.fetchWellData()
            })
        },

        // 检查是否可选
        checkSelectable(row) {
            // 取消数量限制，所有行都可选择
            return true
        },

        // 设置当前页面的选择状态
        setCurrentPageSelection() {
            if (!this.$refs.wellTable) {
                return
            }

            console.log('设置页面选择状态，当前选择:', this.wellSelection)

            // 获取当前页面应该选中的井号
            let currentPageSelection = this.pageSelectionCache.get(this.wellPagination.pageNum) || []

            // 如果是第一次加载且没有缓存，从总选择中筛选当前页面的井号
            if (currentPageSelection.length === 0 && this.wellSelection.length > 0) {
                currentPageSelection = this.wellSelection.filter(well =>
                    this.wellTableData.some(row => row.jh === well)
                )
                // 更新缓存
                this.pageSelectionCache.set(this.wellPagination.pageNum, currentPageSelection)
                console.log('从总选择中筛选当前页面井号:', currentPageSelection)
            }

            console.log('当前页面应该选中的井号:', currentPageSelection)

            // 先清除所有选择
            this.$refs.wellTable.clearSelection()

            // 设置当前页面的选择状态
            this.wellTableData.forEach(row => {
                const isSelected = currentPageSelection.includes(row.jh)
                if (isSelected) {
                    this.$refs.wellTable.toggleRowSelection(row, true)
                    console.log('选中行:', row.jh)
                }
            })

            // 延迟恢复标志，确保选择状态设置完成且不会触发选择变化事件
            setTimeout(() => {
                this.isUserSelecting = true
                this.isSettingSelection = false
                this.isInitializing = false
                console.log('恢复用户选择标志，设置完成')
            }, 500)
        },

        // 分页大小改变
        handleSizeChange(size) {
            // 保存当前页面的选择状态
            if (this.$refs.wellTable) {
                const currentSelection = this.$refs.wellTable.selection || []
                const currentPageSelection = currentSelection.map(item => item.jh)
                this.pageSelectionCache.set(this.wellPagination.pageNum, currentPageSelection)
                console.log('保存当前页面选择:', currentPageSelection)
            }

            this.wellPagination.pageSize = size
            this.wellPagination.pageNum = 1
            this.fetchWellData()
        },

        // 当前页改变
        handleCurrentChange(page) {
            console.log('翻页前选择状态:', this.wellSelection)

            // 保存当前页面的选择状态
            if (this.$refs.wellTable) {
                const currentSelection = this.$refs.wellTable.selection || []
                const currentPageSelection = currentSelection.map(item => item.jh)
                this.pageSelectionCache.set(this.wellPagination.pageNum, currentPageSelection)
                console.log('保存当前页面选择:', currentPageSelection)
            }

            this.wellPagination.pageNum = page
            this.fetchWellData()
        },



        // 井号选择变化
        handleWellSelectionChange(selection) {
            console.log('选择变化事件触发，selection长度:', selection.length, 'isUserSelecting:', this.isUserSelecting, 'isSettingSelection:', this.isSettingSelection, 'isInitializing:', this.isInitializing)

            // 如果是页面初始化或正在设置选择状态，不处理选择变化
            if (!this.isUserSelecting || this.isSettingSelection || this.isInitializing) {
                console.log('页面初始化或正在设置选择状态，跳过选择变化处理')
                return
            }

            // 获取当前页面选中的井号
            const currentPageSelection = selection.map(item => item.jh)
            console.log('当前页面选择:', currentPageSelection)

            // 缓存当前页面的选择状态
            this.pageSelectionCache.set(this.wellPagination.pageNum, currentPageSelection)

            // 重新构建总的选择列表
            let allSelectedWells = []

            // 从缓存中获取所有页面的选择
            for (let pageNum = 1; pageNum <= Math.ceil(this.wellPagination.total / this.wellPagination.pageSize); pageNum++) {
                const pageSelection = this.pageSelectionCache.get(pageNum) || []
                allSelectedWells.push(...pageSelection)
            }



            this.wellSelection = allSelectedWells
            console.log('最终选择状态:', this.wellSelection)
        },

        // 井号确定按钮点击
        handleWellSubmit() {
            if (this.wellSelection.length === 0) {
                this.$message.warning('请选择邻井')
                return
            }
            console.log('提交时的选择:', this.wellSelection)

            // 邻井选择，用逗号隔开显示
            this.formData.jhs = this.wellSelection.join(',')
            console.log('赋值到邻井输入框:', this.formData.jhs)
            this.$message.success(`邻井选择成功，已选择${this.wellSelection.length}个井号`)

            this.wellDialogVisible = false

            // 重新打开主弹窗并清除验证错误
            this.$nextTick(() => {
                this.dialogVisible = true
                // 清除井号字段的验证错误
                if (this.$refs.formRef) {
                    this.$refs.formRef.clearValidate('jhs')
                }
            })
        },

        // 井号选择弹窗取消按钮点击
        handleWellCancel() {
            this.wellDialogVisible = false
            // 重新打开主弹窗
            this.$nextTick(() => {
                this.dialogVisible = true
            })
        },

        // 弹窗关闭处理
        handleDialogClose() {
            // 弹窗关闭时不清空选择状态，保留选择直到确定提交
            // this.wellSelection = []
            // this.pageSelectionCache.clear()
        },

        // 主表格分页事件
        handleMainSizeChange(size) {
            this.mainPagination.pageSize = size;
            this.mainPagination.pageNum = 1;
            this.getList();
        },
        handleMainCurrentChange(page) {
            this.mainPagination.pageNum = page;
            this.getList();
        },


    }
}
</script>

<style lang="scss" scoped>
.djxx-container {
    padding: 15px;
    height: calc(100vh - 85px);
    overflow: hidden;
    position: relative;

    .search-form {
        margin-bottom: 10px;
    }

    .el-table {
        margin-top: 10px;
    }
}

::v-deep .el-table--medium .el-table__cell {
    padding: 5px 0 !important;
}

::v-deep.pagination-container {
    padding: 0px !important;
    margin: 0;
}
</style>